blob: 270de5546bcad6aa76c7e1ac3ba67c05ca2228f9 [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"
29
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31
Douglas Gregor2def4832008-11-17 20:34:05 +000032Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000033 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000034 DeclContext *DC = 0;
35 if (SS) {
36 if (SS->isInvalid())
37 return 0;
38 DC = static_cast<DeclContext*>(SS->getScopeRep());
39 }
40 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroffb327ce02008-04-02 14:35:35 +000041
Douglas Gregor2ce52f32008-04-13 21:07:44 +000042 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
43 isa<ObjCInterfaceDecl>(IIDecl) ||
Douglas Gregor72c3f312008-12-05 18:15:24 +000044 isa<TagDecl>(IIDecl) ||
45 isa<TemplateTypeParmDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000046 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000047 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000048}
49
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000050DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000051 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000052 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000053 if (MD->isOutOfLineDefinition())
54 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000055
56 // A C++ inline method is parsed *after* the topmost class it was declared in
57 // is fully parsed (it's "complete").
58 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000059 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000060 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
61 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000062 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000063 DC = RD;
64
65 // Return the declaration context of the topmost class the inline method is
66 // declared in.
67 return DC;
68 }
69
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000070 if (isa<ObjCMethodDecl>(DC))
71 return Context.getTranslationUnitDecl();
72
73 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
74 return SD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000075
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000076 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000077}
78
Douglas Gregor44b43212008-12-11 16:49:14 +000079void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000080 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +000081 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000082 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +000083 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +000084}
85
Chris Lattnerb048c982008-04-06 04:47:34 +000086void Sema::PopDeclContext() {
87 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +000088
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000089 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000090}
91
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000092/// Add this decl to the scope shadowed decl chains.
93void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000094 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000095
96 // C++ [basic.scope]p4:
97 // -- exactly one declaration shall declare a class name or
98 // enumeration name that is not a typedef name and the other
99 // declarations shall all refer to the same object or
100 // enumerator, or all refer to functions and function templates;
101 // in this case the class name or enumeration name is hidden.
102 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
103 // We are pushing the name of a tag (enum or class).
Douglas Gregor44b43212008-12-11 16:49:14 +0000104 if (CurContext == TD->getDeclContext()) {
105 // We're pushing the tag into the current context, which might
106 // require some reshuffling in the identifier resolver.
107 IdentifierResolver::iterator
108 I = IdResolver.begin(TD->getIdentifier(), CurContext,
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000109 false/*LookInParentCtx*/);
Douglas Gregor44b43212008-12-11 16:49:14 +0000110 if (I != IdResolver.end()) {
111 // There is already a declaration with the same name in the same
112 // scope. It must be found before we find the new declaration,
113 // so swap the order on the shadowed declaration chain.
114 IdResolver.AddShadowedDecl(TD, *I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000115
Douglas Gregor44b43212008-12-11 16:49:14 +0000116 // Add this declaration to the current context.
117 CurContext->addDecl(Context, TD);
118
119 return;
120 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000121 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000122 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000123 // We are pushing the name of a function, which might be an
124 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000125 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000126 if (CurContext == FD->getDeclContext()) {
127 IdentifierResolver::iterator
128 I = IdResolver.begin(FD->getDeclName(), CurContext,
129 false/*LookInParentCtx*/);
130 if (I != IdResolver.end() &&
131 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
132 // There is already a declaration with the same name in
133 // the same scope. It must be a function or an overloaded
134 // function.
135 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
136 if (!Ovl) {
137 // We haven't yet overloaded this function. Take the existing
138 // FunctionDecl and put it into an OverloadedFunctionDecl.
139 Ovl = OverloadedFunctionDecl::Create(Context,
140 FD->getDeclContext(),
141 FD->getDeclName());
142 Ovl->addOverload(cast<FunctionDecl>(*I));
143
144 IdResolver.RemoveDecl(*I);
145 S->RemoveDecl(*I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000146
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000147 // Add the name binding for the OverloadedFunctionDecl.
148 IdResolver.AddDecl(Ovl);
149
150 S->AddDecl(Ovl);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000151 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000152
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000153 // We added this function declaration to the scope earlier, but
154 // we don't want it there because it is part of the overloaded
155 // function declaration.
156 S->RemoveDecl(FD);
157
158 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
159 // to its list of overloads.
160 Ovl->addOverload(FD);
161
162 // Add this new function declaration to the declaration context.
163 CurContext->addDecl(Context, FD);
164
165 return;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000166 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000167 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000168 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000169
Douglas Gregore267ff32008-12-11 20:41:00 +0000170 // Add scoped declarations into their context, so that they can be
171 // found later. Declarations without a context won't be inserted
172 // into any context.
Douglas Gregor44b43212008-12-11 16:49:14 +0000173 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
174 CurContext->addDecl(Context, SD);
Douglas Gregor44b43212008-12-11 16:49:14 +0000175
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000176 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000177}
178
Steve Naroffb216c882007-10-09 22:01:59 +0000179void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000180 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000181 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
182 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000183
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
185 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000186 Decl *TmpD = static_cast<Decl*>(*I);
187 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000188
Douglas Gregor44b43212008-12-11 16:49:14 +0000189 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
190 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000191
Douglas Gregor44b43212008-12-11 16:49:14 +0000192 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000193
Douglas Gregor44b43212008-12-11 16:49:14 +0000194 // Remove this name from our lexical scope.
195 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000196 }
197}
198
Steve Naroffe8043c32008-04-01 23:04:06 +0000199/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
200/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000201ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000202 // The third "scope" argument is 0 since we aren't enabling lazy built-in
203 // creation from this context.
204 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000205
Steve Naroffb327ce02008-04-02 14:35:35 +0000206 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000207}
208
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000209/// MaybeConstructOverloadSet - Name lookup has determined that the
210/// elements in [I, IEnd) have the name that we are looking for, and
211/// *I is a match for the namespace. This routine returns an
212/// appropriate Decl for name lookup, which may either be *I or an
213/// OverloadeFunctionDecl that represents the overloaded functions in
214/// [I, IEnd).
215///
216/// The existance of this routine is temporary; LookupDecl should
217/// probably be able to return multiple results, to deal with cases of
218/// ambiguity and overloaded functions without needing to create a
219/// Decl node.
220static Decl *
221MaybeConstructOverloadSet(ASTContext &Context, const DeclContext *DC,
222 DeclContext::lookup_const_iterator I,
223 DeclContext::lookup_const_iterator IEnd) {
224 assert(I != IEnd && "Iterator range cannot be empty");
225 assert(!isa<OverloadedFunctionDecl>(*I) &&
226 "Cannot have an overloaded function");
227
228 if (isa<FunctionDecl>(*I)) {
229 // If we found a function, there might be more functions. If
230 // so, collect them into an overload set.
231 DeclContext::lookup_const_iterator Last = I;
232 OverloadedFunctionDecl *Ovl = 0;
233 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
234 if (!Ovl) {
235 // FIXME: We leak this overload set. Eventually, we want to
236 // stop building the declarations for these overload sets, so
237 // there will be nothing to leak.
238 Ovl = OverloadedFunctionDecl::Create(Context,
239 const_cast<DeclContext *>(DC),
240 (*I)->getDeclName());
241 Ovl->addOverload(cast<FunctionDecl>(*I));
242 }
243 Ovl->addOverload(cast<FunctionDecl>(*Last));
244 }
245
246 // If we had more than one function, we built an overload
247 // set. Return it.
248 if (Ovl)
249 return Ovl;
250 }
251
252 return *I;
253}
254
Steve Naroffe8043c32008-04-01 23:04:06 +0000255/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000256/// namespace.
Douglas Gregor2def4832008-11-17 20:34:05 +0000257Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000258 const DeclContext *LookupCtx,
Douglas Gregor44b43212008-12-11 16:49:14 +0000259 bool enableLazyBuiltinCreation,
Douglas Gregor0a59acb2008-12-16 00:38:16 +0000260 bool LookInParent) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000261 if (!Name) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000262 unsigned NS = NSI;
263 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
264 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000265
Douglas Gregore267ff32008-12-11 20:41:00 +0000266 if (LookupCtx == 0 &&
267 (!getLangOptions().CPlusPlus || (NS == Decl::IDNS_Label))) {
268 // Unqualified name lookup in C/Objective-C and name lookup for
269 // labels in C++ is purely lexical, so search in the
270 // declarations attached to the name.
271 assert(!LookupCtx && "Can't perform qualified name lookup here");
272 IdentifierResolver::iterator I
273 = IdResolver.begin(Name, CurContext, LookInParent);
274
275 // Scan up the scope chain looking for a decl that matches this
276 // identifier that is in the appropriate namespace. This search
277 // should not take long, as shadowing of names is uncommon, and
278 // deep shadowing is extremely uncommon.
279 for (; I != IdResolver.end(); ++I)
280 if ((*I)->getIdentifierNamespace() & NS)
281 return *I;
282 } else if (LookupCtx) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000283 // Perform qualified name lookup into the LookupCtx.
284 // FIXME: Will need to look into base classes and such.
Douglas Gregore267ff32008-12-11 20:41:00 +0000285 DeclContext::lookup_const_iterator I, E;
286 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
287 if ((*I)->getIdentifierNamespace() & NS)
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000288 return MaybeConstructOverloadSet(Context, LookupCtx, I, E);
Douglas Gregore267ff32008-12-11 20:41:00 +0000289 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000290 // Name lookup for ordinary names and tag names in C++ requires
291 // looking into scopes that aren't strictly lexical, and
292 // therefore we walk through the context as well as walking
293 // through the scopes.
294 IdentifierResolver::iterator
295 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
296 IEnd = IdResolver.end();
297 for (; S; S = S->getParent()) {
298 // Check whether the IdResolver has anything in this scope.
299 // FIXME: The isDeclScope check could be expensive. Can we do better?
300 for (; I != IEnd && S->isDeclScope(*I); ++I)
301 if ((*I)->getIdentifierNamespace() & NS)
302 return *I;
303
304 // If there is an entity associated with this scope, it's a
305 // DeclContext. We might need to perform qualified lookup into
306 // it.
307 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
308 while (Ctx && Ctx->isFunctionOrMethod())
309 Ctx = Ctx->getParent();
310 while (Ctx && (Ctx->isNamespace() || Ctx->isCXXRecord())) {
311 // Look for declarations of this name in this scope.
Douglas Gregore267ff32008-12-11 20:41:00 +0000312 DeclContext::lookup_const_iterator I, E;
313 for (llvm::tie(I, E) = Ctx->lookup(Context, Name); I != E; ++I) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000314 // FIXME: Cache this result in the IdResolver
Douglas Gregore267ff32008-12-11 20:41:00 +0000315 if ((*I)->getIdentifierNamespace() & NS)
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000316 return MaybeConstructOverloadSet(Context, LookupCtx, I, E);
Douglas Gregor44b43212008-12-11 16:49:14 +0000317 }
318
319 Ctx = Ctx->getParent();
320 }
321
322 if (!LookInParent)
323 return 0;
324 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000325 }
Chris Lattner7f925cc2008-04-11 07:00:53 +0000326
Reid Spencer5f016e22007-07-11 17:01:13 +0000327 // If we didn't find a use of this identifier, and if the identifier
328 // corresponds to a compiler builtin, create the decl object for the builtin
329 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000330 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000331 IdentifierInfo *II = Name.getAsIdentifierInfo();
332 if (enableLazyBuiltinCreation && II &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000333 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000334 // If this is a builtin on this (or all) targets, create the decl.
335 if (unsigned BuiltinID = II->getBuiltinID())
336 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
337 }
Douglas Gregor2def4832008-11-17 20:34:05 +0000338 if (getLangOptions().ObjC1 && II) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000339 // @interface and @compatibility_alias introduce typedef-like names.
340 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000341 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000342 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000343 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
344 if (IDI != ObjCInterfaceDecls.end())
345 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000346 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
347 if (I != ObjCAliasDecls.end())
348 return I->second->getClassInterface();
349 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 }
351 return 0;
352}
353
Chris Lattner95e2c712008-05-05 22:18:14 +0000354void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000355 if (!Context.getBuiltinVaListType().isNull())
356 return;
357
358 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000359 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000360 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000361 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
362}
363
Reid Spencer5f016e22007-07-11 17:01:13 +0000364/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
365/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000366ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
367 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 Builtin::ID BID = (Builtin::ID)bid;
369
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000370 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000371 InitBuiltinVaListType();
372
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000373 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000374 FunctionDecl *New = FunctionDecl::Create(Context,
375 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000376 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000377 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000378
Chris Lattner95e2c712008-05-05 22:18:14 +0000379 // Create Decl objects for each parameter, adding them to the
380 // FunctionDecl.
381 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
382 llvm::SmallVector<ParmVarDecl*, 16> Params;
383 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
384 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
385 FT->getArgType(i), VarDecl::None, 0,
386 0));
387 New->setParams(&Params[0], Params.size());
388 }
389
390
391
Chris Lattner7f925cc2008-04-11 07:00:53 +0000392 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000393 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 return New;
395}
396
Sebastian Redlc42e1182008-11-11 11:37:55 +0000397/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
398/// everything from the standard library is defined.
399NamespaceDecl *Sema::GetStdNamespace() {
400 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000401 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000402 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattner8edea832008-11-20 05:45:14 +0000403 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000404 0, Global, /*enableLazyBuiltinCreation=*/false);
405 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
406 }
407 return StdNamespace;
408}
409
Reid Spencer5f016e22007-07-11 17:01:13 +0000410/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
411/// and scope as a previous declaration 'Old'. Figure out how to resolve this
412/// situation, merging decls or emitting diagnostics as appropriate.
413///
Steve Naroffe8043c32008-04-01 23:04:06 +0000414TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000415 // Allow multiple definitions for ObjC built-in typedefs.
416 // FIXME: Verify the underlying types are equivalent!
417 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000418 const IdentifierInfo *TypeID = New->getIdentifier();
419 switch (TypeID->getLength()) {
420 default: break;
421 case 2:
422 if (!TypeID->isStr("id"))
423 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000424 Context.setObjCIdType(New);
425 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000426 case 5:
427 if (!TypeID->isStr("Class"))
428 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000429 Context.setObjCClassType(New);
430 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000431 case 3:
432 if (!TypeID->isStr("SEL"))
433 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000434 Context.setObjCSelType(New);
435 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000436 case 8:
437 if (!TypeID->isStr("Protocol"))
438 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000439 Context.setObjCProtoType(New->getUnderlyingType());
440 return New;
441 }
442 // Fall through - the typedef name was not a builtin type.
443 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000444 // Verify the old decl was also a typedef.
445 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
446 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000447 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000448 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000449 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 return New;
451 }
452
Chris Lattner99cb9972008-07-25 18:44:27 +0000453 // If the typedef types are not identical, reject them in all languages and
454 // with any extensions enabled.
455 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
456 Context.getCanonicalType(Old->getUnderlyingType()) !=
457 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000458 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000459 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000460 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner99cb9972008-07-25 18:44:27 +0000461 return Old;
462 }
463
Eli Friedman54ecfce2008-06-11 06:20:39 +0000464 if (getLangOptions().Microsoft) return New;
465
Douglas Gregorbbe27432008-11-21 16:29:06 +0000466 // C++ [dcl.typedef]p2:
467 // In a given non-class scope, a typedef specifier can be used to
468 // redefine the name of any type declared in that scope to refer
469 // to the type to which it already refers.
470 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
471 return New;
472
473 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000474 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
475 // *either* declaration is in a system header. The code below implements
476 // this adhoc compatibility rule. FIXME: The following code will not
477 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000478 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
479 SourceManager &SrcMgr = Context.getSourceManager();
480 if (SrcMgr.isInSystemHeader(Old->getLocation()))
481 return New;
482 if (SrcMgr.isInSystemHeader(New->getLocation()))
483 return New;
484 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000485
Chris Lattner08631c52008-11-23 21:45:46 +0000486 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000487 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000488 return New;
489}
490
Chris Lattner6b6b5372008-06-26 18:38:35 +0000491/// DeclhasAttr - returns true if decl Declaration already has the target
492/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000493static bool DeclHasAttr(const Decl *decl, const Attr *target) {
494 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
495 if (attr->getKind() == target->getKind())
496 return true;
497
498 return false;
499}
500
501/// MergeAttributes - append attributes from the Old decl to the New one.
502static void MergeAttributes(Decl *New, Decl *Old) {
503 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
504
Chris Lattnerddee4232008-03-03 03:28:21 +0000505 while (attr) {
506 tmp = attr;
507 attr = attr->getNext();
508
509 if (!DeclHasAttr(New, tmp)) {
510 New->addAttr(tmp);
511 } else {
512 tmp->setNext(0);
513 delete(tmp);
514 }
515 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000516
517 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000518}
519
Chris Lattner04421082008-04-08 04:40:51 +0000520/// MergeFunctionDecl - We just parsed a function 'New' from
521/// declarator D which has the same name and scope as a previous
522/// declaration 'Old'. Figure out how to resolve this situation,
523/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000524/// Redeclaration will be set true if this New is a redeclaration OldD.
525///
526/// In C++, New and Old must be declarations that are not
527/// overloaded. Use IsOverload to determine whether New and Old are
528/// overloaded, and to select the Old declaration that New should be
529/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000530FunctionDecl *
531Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000532 assert(!isa<OverloadedFunctionDecl>(OldD) &&
533 "Cannot merge with an overloaded function declaration");
534
Douglas Gregorf0097952008-04-21 02:02:58 +0000535 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000536 // Verify the old decl was also a function.
537 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
538 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000539 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000540 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000541 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000542 return New;
543 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000544
545 // Determine whether the previous declaration was a definition,
546 // implicit declaration, or a declaration.
547 diag::kind PrevDiag;
548 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000549 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000550 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000551 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000552 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000553 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000554
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000555 QualType OldQType = Context.getCanonicalType(Old->getType());
556 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000557
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000558 if (getLangOptions().CPlusPlus) {
559 // (C++98 13.1p2):
560 // Certain function declarations cannot be overloaded:
561 // -- Function declarations that differ only in the return type
562 // cannot be overloaded.
563 QualType OldReturnType
564 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
565 QualType NewReturnType
566 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
567 if (OldReturnType != NewReturnType) {
568 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
569 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000570 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000571 return New;
572 }
573
574 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
575 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
576 if (OldMethod && NewMethod) {
577 // -- Member function declarations with the same name and the
578 // same parameter types cannot be overloaded if any of them
579 // is a static member function declaration.
580 if (OldMethod->isStatic() || NewMethod->isStatic()) {
581 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
582 Diag(Old->getLocation(), PrevDiag);
583 return New;
584 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000585
586 // C++ [class.mem]p1:
587 // [...] A member shall not be declared twice in the
588 // member-specification, except that a nested class or member
589 // class template can be declared and then later defined.
590 if (OldMethod->getLexicalDeclContext() ==
591 NewMethod->getLexicalDeclContext()) {
592 unsigned NewDiag;
593 if (isa<CXXConstructorDecl>(OldMethod))
594 NewDiag = diag::err_constructor_redeclared;
595 else if (isa<CXXDestructorDecl>(NewMethod))
596 NewDiag = diag::err_destructor_redeclared;
597 else if (isa<CXXConversionDecl>(NewMethod))
598 NewDiag = diag::err_conv_function_redeclared;
599 else
600 NewDiag = diag::err_member_redeclared;
601
602 Diag(New->getLocation(), NewDiag);
603 Diag(Old->getLocation(), PrevDiag);
604 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000605 }
606
607 // (C++98 8.3.5p3):
608 // All declarations for a function shall agree exactly in both the
609 // return type and the parameter-type-list.
610 if (OldQType == NewQType) {
611 // We have a redeclaration.
612 MergeAttributes(New, Old);
613 Redeclaration = true;
614 return MergeCXXFunctionDecl(New, Old);
615 }
616
617 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000618 }
Chris Lattner04421082008-04-08 04:40:51 +0000619
620 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000621 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000622 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000623 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000624 MergeAttributes(New, Old);
625 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000626 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000627 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000628
Steve Naroff837618c2008-01-16 15:01:34 +0000629 // A function that has already been declared has been redeclared or defined
630 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000631
Reid Spencer5f016e22007-07-11 17:01:13 +0000632 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
633 // TODO: This is totally simplistic. It should handle merging functions
634 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000635 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000636 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000637 return New;
638}
639
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000640/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000641static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000642 if (VD->isFileVarDecl())
643 return (!VD->getInit() &&
644 (VD->getStorageClass() == VarDecl::None ||
645 VD->getStorageClass() == VarDecl::Static));
646 return false;
647}
648
649/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
650/// when dealing with C "tentative" external object definitions (C99 6.9.2).
651void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
652 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000653 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000654
655 for (IdentifierResolver::iterator
656 I = IdResolver.begin(VD->getIdentifier(),
657 VD->getDeclContext(), false/*LookInParentCtx*/),
658 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000659 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000660 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
661
Steve Narofff855e6f2008-08-10 15:20:13 +0000662 // Handle the following case:
663 // int a[10];
664 // int a[]; - the code below makes sure we set the correct type.
665 // int a[11]; - this is an error, size isn't 10.
666 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
667 OldDecl->getType()->isConstantArrayType())
668 VD->setType(OldDecl->getType());
669
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000670 // Check for "tentative" definitions. We can't accomplish this in
671 // MergeVarDecl since the initializer hasn't been attached.
672 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
673 continue;
674
675 // Handle __private_extern__ just like extern.
676 if (OldDecl->getStorageClass() != VarDecl::Extern &&
677 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
678 VD->getStorageClass() != VarDecl::Extern &&
679 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000680 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000681 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000682 }
683 }
684 }
685}
686
Reid Spencer5f016e22007-07-11 17:01:13 +0000687/// MergeVarDecl - We just parsed a variable 'New' which has the same name
688/// and scope as a previous declaration 'Old'. Figure out how to resolve this
689/// situation, merging decls or emitting diagnostics as appropriate.
690///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000691/// Tentative definition rules (C99 6.9.2p2) are checked by
692/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
693/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000694///
Steve Naroffe8043c32008-04-01 23:04:06 +0000695VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000696 // Verify the old decl was also a variable.
697 VarDecl *Old = dyn_cast<VarDecl>(OldD);
698 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000699 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000700 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000701 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000702 return New;
703 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000704
705 MergeAttributes(New, Old);
706
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000708 QualType OldCType = Context.getCanonicalType(Old->getType());
709 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000710 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner08631c52008-11-23 21:45:46 +0000711 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000712 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000713 return New;
714 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000715 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
716 if (New->getStorageClass() == VarDecl::Static &&
717 (Old->getStorageClass() == VarDecl::None ||
718 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000719 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000720 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000721 return New;
722 }
723 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
724 if (New->getStorageClass() != VarDecl::Static &&
725 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000726 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000727 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000728 return New;
729 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000730 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
731 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000732 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000733 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 }
735 return New;
736}
737
Chris Lattner04421082008-04-08 04:40:51 +0000738/// CheckParmsForFunctionDef - Check that the parameters of the given
739/// function are appropriate for the definition of a function. This
740/// takes care of any checks that cannot be performed on the
741/// declaration itself, e.g., that the types of each of the function
742/// parameters are complete.
743bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
744 bool HasInvalidParm = false;
745 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
746 ParmVarDecl *Param = FD->getParamDecl(p);
747
748 // C99 6.7.5.3p4: the parameters in a parameter type list in a
749 // function declarator that is part of a function definition of
750 // that function shall not have incomplete type.
751 if (Param->getType()->isIncompleteType() &&
752 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000753 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000754 << Param->getType();
Chris Lattner04421082008-04-08 04:40:51 +0000755 Param->setInvalidDecl();
756 HasInvalidParm = true;
757 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000758
759 // C99 6.9.1p5: If the declarator includes a parameter type list, the
760 // declaration of each parameter shall include an identifier.
761 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
762 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000763 }
764
765 return HasInvalidParm;
766}
767
Reid Spencer5f016e22007-07-11 17:01:13 +0000768/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
769/// no declarator (e.g. "struct foo;") is parsed.
770Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
771 // TODO: emit error on 'int;' or 'const enum foo;'.
772 // TODO: emit error on 'typedef int;'
773 // if (!DS.isMissingDeclaratorOk()) Diag(...);
774
Steve Naroff92199282007-11-17 21:37:36 +0000775 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000776}
777
Steve Naroffd0091aa2008-01-10 22:15:12 +0000778bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000779 // Get the type before calling CheckSingleAssignmentConstraints(), since
780 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000781 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +0000782
783 if (getLangOptions().CPlusPlus)
784 return PerformCopyInitialization(Init, DeclType, "initializing");
785
Chris Lattner5cf216b2008-01-04 18:04:52 +0000786 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
787 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
788 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000789}
790
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000791bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000792 const ArrayType *AT = Context.getAsArrayType(DeclT);
793
794 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000795 // C99 6.7.8p14. We have an array of character type with unknown size
796 // being initialized to a string literal.
797 llvm::APSInt ConstVal(32);
798 ConstVal = strLiteral->getByteLength() + 1;
799 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000800 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000801 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000802 } else {
803 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000804 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000805 // FIXME: Avoid truncation for 64-bit length strings.
806 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000807 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000808 diag::warn_initializer_string_for_char_array_too_long)
809 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000810 }
811 // Set type from "char *" to "constant array of char".
812 strLiteral->setType(DeclT);
813 // For now, we always return false (meaning success).
814 return false;
815}
816
817StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000818 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000819 if (AT && AT->getElementType()->isCharType()) {
820 return dyn_cast<StringLiteral>(Init);
821 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000822 return 0;
823}
824
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000825bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
826 SourceLocation InitLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000827 DeclarationName InitEntity) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +0000828 if (DeclType->isDependentType() || Init->isTypeDependent())
829 return false;
830
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000831 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +0000832 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000833 // (8.3.2), shall be initialized by an object, or function, of
834 // type T or by an object that can be converted into a T.
835 if (DeclType->isReferenceType())
836 return CheckReferenceInit(Init, DeclType);
837
Steve Naroffca107302008-01-21 23:53:58 +0000838 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
839 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000840 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000841 return Diag(InitLoc, diag::err_variable_object_no_init)
842 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +0000843
Steve Naroff2fdc3742007-12-10 22:44:33 +0000844 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
845 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000846 // FIXME: Handle wide strings
847 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
848 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000849
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000850 // C++ [dcl.init]p14:
851 // -- If the destination type is a (possibly cv-qualified) class
852 // type:
853 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
854 QualType DeclTypeC = Context.getCanonicalType(DeclType);
855 QualType InitTypeC = Context.getCanonicalType(Init->getType());
856
857 // -- If the initialization is direct-initialization, or if it is
858 // copy-initialization where the cv-unqualified version of the
859 // source type is the same class as, or a derived class of, the
860 // class of the destination, constructors are considered.
861 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
862 IsDerivedFrom(InitTypeC, DeclTypeC)) {
863 CXXConstructorDecl *Constructor
864 = PerformInitializationByConstructor(DeclType, &Init, 1,
865 InitLoc, Init->getSourceRange(),
866 InitEntity, IK_Copy);
867 return Constructor == 0;
868 }
869
870 // -- Otherwise (i.e., for the remaining copy-initialization
871 // cases), user-defined conversion sequences that can
872 // convert from the source type to the destination type or
873 // (when a conversion function is used) to a derived class
874 // thereof are enumerated as described in 13.3.1.4, and the
875 // best one is chosen through overload resolution
876 // (13.3). If the conversion cannot be done or is
877 // ambiguous, the initialization is ill-formed. The
878 // function selected is called with the initializer
879 // expression as its argument; if the function is a
880 // constructor, the call initializes a temporary of the
881 // destination type.
882 // FIXME: We're pretending to do copy elision here; return to
883 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +0000884 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000885 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000886
887 return Diag(InitLoc, diag::err_typecheck_convert_incompatible)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000888 << DeclType << InitEntity << "initializing"
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000889 << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000890 }
891
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000892 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000893 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000894 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
895 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +0000896
Steve Naroffd0091aa2008-01-10 22:15:12 +0000897 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000898 } else if (getLangOptions().CPlusPlus) {
899 // C++ [dcl.init]p14:
900 // [...] If the class is an aggregate (8.5.1), and the initializer
901 // is a brace-enclosed list, see 8.5.1.
902 //
903 // Note: 8.5.1 is handled below; here, we diagnose the case where
904 // we have an initializer list and a destination type that is not
905 // an aggregate.
906 // FIXME: In C++0x, this is yet another form of initialization.
907 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
908 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
909 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000910 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +0000911 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +0000912 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000913 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000914
Steve Naroff0cca7492008-05-01 22:18:59 +0000915 InitListChecker CheckInitList(this, InitList, DeclType);
916 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000917}
918
Douglas Gregor10bd3682008-11-17 22:58:34 +0000919/// GetNameForDeclarator - Determine the full declaration name for the
920/// given Declarator.
921DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
922 switch (D.getKind()) {
923 case Declarator::DK_Abstract:
924 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
925 return DeclarationName();
926
927 case Declarator::DK_Normal:
928 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
929 return DeclarationName(D.getIdentifier());
930
931 case Declarator::DK_Constructor: {
932 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
933 Ty = Context.getCanonicalType(Ty);
934 return Context.DeclarationNames.getCXXConstructorName(Ty);
935 }
936
937 case Declarator::DK_Destructor: {
938 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
939 Ty = Context.getCanonicalType(Ty);
940 return Context.DeclarationNames.getCXXDestructorName(Ty);
941 }
942
943 case Declarator::DK_Conversion: {
944 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
945 Ty = Context.getCanonicalType(Ty);
946 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
947 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000948
949 case Declarator::DK_Operator:
950 assert(D.getIdentifier() == 0 && "operator names have no identifier");
951 return Context.DeclarationNames.getCXXOperatorName(
952 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000953 }
954
955 assert(false && "Unknown name kind");
956 return DeclarationName();
957}
958
Douglas Gregor584049d2008-12-15 23:53:10 +0000959/// isNearlyMatchingMemberFunction - Determine whether the C++ member
960/// functions Declaration and Definition are "nearly" matching. This
961/// heuristic is used to improve diagnostics in the case where an
962/// out-of-line member function definition doesn't match any
963/// declaration within the class.
964static bool isNearlyMatchingMemberFunction(ASTContext &Context,
965 FunctionDecl *Declaration,
966 FunctionDecl *Definition) {
967 if (Declaration->param_size() != Definition->param_size())
968 return false;
969 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
970 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
971 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
972
973 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
974 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
975 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
976 return false;
977 }
978
979 return true;
980}
981
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000982Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +0000983Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
984 bool IsFunctionDefinition) {
Steve Naroff94745042007-09-13 23:52:58 +0000985 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +0000986 DeclarationName Name = GetNameForDeclarator(D);
987
Chris Lattnere80a59c2007-07-25 00:24:17 +0000988 // All of these full declarators require an identifier. If it doesn't have
989 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +0000990 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +0000991 if (!D.getInvalidType()) // Reject this if we think it is valid.
992 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000993 diag::err_declarator_need_ident)
994 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +0000995 return 0;
996 }
997
Chris Lattner31e05722007-08-26 06:24:45 +0000998 // The scope passed in may not be a decl scope. Zip up the scope tree until
999 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001000 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1001 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001002 S = S->getParent();
1003
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001004 DeclContext *DC;
1005 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +00001006 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001007 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001008
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001009 // See if this is a redefinition of a variable in the same scope.
1010 if (!D.getCXXScopeSpec().isSet()) {
1011 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +00001012 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001013 } else { // Something like "int foo::x;"
1014 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001015 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001016
1017 // C++ 7.3.1.2p2:
1018 // Members (including explicit specializations of templates) of a named
1019 // namespace can also be defined outside that namespace by explicit
1020 // qualification of the name being defined, provided that the entity being
1021 // defined was already declared in the namespace and the definition appears
1022 // after the point of declaration in a namespace that encloses the
1023 // declarations namespace.
1024 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001025 // Note that we only check the context at this point. We don't yet
1026 // have enough information to make sure that PrevDecl is actually
1027 // the declaration we want to match. For example, given:
1028 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001029 // class X {
1030 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001031 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001032 // };
1033 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001034 // void X::f(int) { } // ill-formed
1035 //
1036 // In this case, PrevDecl will point to the overload set
1037 // containing the two f's declared in X, but neither of them
1038 // matches.
1039 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001040 // The qualifying scope doesn't enclose the original declaration.
1041 // Emit diagnostic based on current scope.
1042 SourceLocation L = D.getIdentifierLoc();
1043 SourceRange R = D.getCXXScopeSpec().getRange();
1044 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001045 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001046 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001047 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001048 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001049 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001050 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001051 }
1052 }
1053
Douglas Gregorf57172b2008-12-08 18:40:42 +00001054 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001055 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001056 InvalidDecl = InvalidDecl
1057 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001058 // Just pretend that we didn't see the previous declaration.
1059 PrevDecl = 0;
1060 }
1061
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001062 // In C++, the previous declaration we find might be a tag type
1063 // (class or enum). In this case, the new declaration will hide the
1064 // tag type.
1065 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1066 PrevDecl = 0;
1067
Chris Lattner41af0932007-11-14 06:34:38 +00001068 QualType R = GetTypeForDeclarator(D, S);
1069 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1070
Reid Spencer5f016e22007-07-11 17:01:13 +00001071 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001072 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1073 if (D.getCXXScopeSpec().isSet()) {
1074 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1075 << D.getCXXScopeSpec().getRange();
1076 InvalidDecl = true;
1077 // Pretend we didn't see the scope specifier.
1078 DC = 0;
1079 }
1080
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001081 // Check that there are no default arguments (C++ only).
1082 if (getLangOptions().CPlusPlus)
1083 CheckExtraCXXDefaultArguments(D);
1084
Chris Lattner41af0932007-11-14 06:34:38 +00001085 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +00001086 if (!NewTD) return 0;
1087
1088 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001089 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +00001090 // Merge the decl with the existing one if appropriate. If the decl is
1091 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001092 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001093 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1094 if (NewTD == 0) return 0;
1095 }
1096 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001097 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001098 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1099 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +00001100 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001101 if (NewTD->getUnderlyingType()->isVariableArrayType())
1102 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1103 else
1104 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1105
Steve Naroffd7444aa2007-08-31 17:20:07 +00001106 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 }
1108 }
Chris Lattner41af0932007-11-14 06:34:38 +00001109 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +00001110 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +00001111 switch (D.getDeclSpec().getStorageClassSpec()) {
1112 default: assert(0 && "Unknown storage class!");
1113 case DeclSpec::SCS_auto:
1114 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +00001115 case DeclSpec::SCS_mutable:
Chris Lattnerd1625842008-11-24 06:25:27 +00001116 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroff5912a352007-08-28 20:14:24 +00001117 InvalidDecl = true;
1118 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001119 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1120 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1121 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +00001122 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001123 }
1124
Chris Lattnera98e58d2008-03-15 21:24:04 +00001125 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001126 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +00001127 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1128
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001129 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001130 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +00001131 // This is a C++ constructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001132 assert(DC->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +00001133 "Constructors can only be declared in a member context");
1134
Douglas Gregor42a552f2008-11-05 20:51:48 +00001135 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001136
1137 // Create the new declaration
1138 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001139 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001140 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +00001141 isExplicit, isInline,
1142 /*isImplicitlyDeclared=*/false);
1143
Douglas Gregor42a552f2008-11-05 20:51:48 +00001144 if (isInvalidDecl)
1145 NewFD->setInvalidDecl();
1146 } else if (D.getKind() == Declarator::DK_Destructor) {
1147 // This is a C++ destructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001148 if (DC->isCXXRecord()) {
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001149 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001150
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001151 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001152 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001153 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001154 isInline,
1155 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001156
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001157 if (isInvalidDecl)
1158 NewFD->setInvalidDecl();
1159 } else {
1160 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1161 // Create a FunctionDecl to satisfy the function definition parsing
1162 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001163 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001164 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001165 // FIXME: Move to DeclGroup...
1166 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001167 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001168 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001169 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001170 if (!DC->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001171 Diag(D.getIdentifierLoc(),
1172 diag::err_conv_function_not_member);
1173 return 0;
1174 } else {
1175 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
1176
1177 NewFD = CXXConversionDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001178 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001179 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001180 isInline, isExplicit);
1181
1182 if (isInvalidDecl)
1183 NewFD->setInvalidDecl();
1184 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001185 } else if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001186 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001187 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001188 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001189 (SC == FunctionDecl::Static), isInline,
1190 LastDeclarator);
1191 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001192 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001193 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001194 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001195 // FIXME: Move to DeclGroup...
1196 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001197 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001198
Ted Kremenekf5c93c12008-02-27 22:18:07 +00001199 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +00001200 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +00001201
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001202 // Set the lexical context. If the declarator has a C++
1203 // scope specifier, the lexical context will be different
1204 // from the semantic context.
1205 NewFD->setLexicalDeclContext(CurContext);
1206
Daniel Dunbara80f8742008-08-05 01:35:17 +00001207 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +00001208 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +00001209 // The parser guarantees this is a string.
1210 StringLiteral *SE = cast<StringLiteral>(E);
1211 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1212 SE->getByteLength())));
1213 }
1214
Chris Lattner04421082008-04-08 04:40:51 +00001215 // Copy the parameter declarations from the declarator D to
1216 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001217 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001218 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1219
1220 // Create Decl objects for each parameter, adding them to the
1221 // FunctionDecl.
1222 llvm::SmallVector<ParmVarDecl*, 16> Params;
1223
1224 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1225 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001226 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001227 // We let through "const void" here because Sema::GetTypeForDeclarator
1228 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001229 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1230 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001231 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1232 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001233 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1234
Chris Lattnerdef026a2008-04-10 02:26:16 +00001235 // In C++, the empty parameter-type-list must be spelled "void"; a
1236 // typedef of void is not permitted.
1237 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001238 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001239 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1240 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001241 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001242 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1243 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1244 }
1245
1246 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001247 } else if (R->getAsTypedefType()) {
1248 // When we're declaring a function with a typedef, as in the
1249 // following example, we'll need to synthesize (unnamed)
1250 // parameters for use in the declaration.
1251 //
1252 // @code
1253 // typedef void fn(int);
1254 // fn f;
1255 // @endcode
1256 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1257 if (!FT) {
1258 // This is a typedef of a function with no prototype, so we
1259 // don't need to do anything.
1260 } else if ((FT->getNumArgs() == 0) ||
1261 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1262 FT->getArgType(0)->isVoidType())) {
1263 // This is a zero-argument function. We don't need to do anything.
1264 } else {
1265 // Synthesize a parameter for each argument type.
1266 llvm::SmallVector<ParmVarDecl*, 16> Params;
1267 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1268 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001269 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001270 SourceLocation(), 0,
1271 *ArgType, VarDecl::None,
1272 0, 0));
1273 }
1274
1275 NewFD->setParams(&Params[0], Params.size());
1276 }
Chris Lattner04421082008-04-08 04:40:51 +00001277 }
1278
Douglas Gregor72b505b2008-12-16 21:30:33 +00001279 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1280 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001281 else if (isa<CXXDestructorDecl>(NewFD))
1282 cast<CXXRecordDecl>(NewFD->getParent())->setUserDeclaredDestructor(true);
1283 else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
Douglas Gregor2def4832008-11-17 20:34:05 +00001284 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001285
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001286 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1287 if (NewFD->isOverloadedOperator() &&
1288 CheckOverloadedOperatorDeclaration(NewFD))
1289 NewFD->setInvalidDecl();
1290
Steve Naroffffce4d52008-01-09 23:34:55 +00001291 // Merge the decl with the existing one if appropriate. Since C functions
1292 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001293 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001294 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001295 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001296
1297 // If C++, determine whether NewFD is an overload of PrevDecl or
1298 // a declaration that requires merging. If it's an overload,
1299 // there's no more work to do here; we'll just add the new
1300 // function to the scope.
1301 OverloadedFunctionDecl::function_iterator MatchedDecl;
1302 if (!getLangOptions().CPlusPlus ||
1303 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1304 Decl *OldDecl = PrevDecl;
1305
1306 // If PrevDecl was an overloaded function, extract the
1307 // FunctionDecl that matched.
1308 if (isa<OverloadedFunctionDecl>(PrevDecl))
1309 OldDecl = *MatchedDecl;
1310
1311 // NewFD and PrevDecl represent declarations that need to be
1312 // merged.
1313 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1314
1315 if (NewFD == 0) return 0;
1316 if (Redeclaration) {
1317 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1318
1319 if (OldDecl == PrevDecl) {
1320 // Remove the name binding for the previous
Douglas Gregor44b43212008-12-11 16:49:14 +00001321 // declaration.
1322 if (S->isDeclScope(PrevDecl)) {
1323 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1324 S->RemoveDecl(PrevDecl);
1325 }
1326
1327 // Introduce the new binding for this declaration.
1328 IdResolver.AddDecl(NewFD);
1329 if (getLangOptions().CPlusPlus && NewFD->getParent())
1330 NewFD->getParent()->insert(Context, NewFD);
1331
1332 // Add the redeclaration to the current scope, since we'll
1333 // be skipping PushOnScopeChains.
1334 S->AddDecl(NewFD);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001335 } else {
1336 // We need to update the OverloadedFunctionDecl with the
1337 // latest declaration of this function, so that name
1338 // lookup will always refer to the latest declaration of
1339 // this function.
1340 *MatchedDecl = NewFD;
Douglas Gregor44b43212008-12-11 16:49:14 +00001341 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001342
Douglas Gregor44b43212008-12-11 16:49:14 +00001343 if (getLangOptions().CPlusPlus) {
1344 // Add this declaration to the current context.
1345 CurContext->addDecl(Context, NewFD, false);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001346
Douglas Gregor44b43212008-12-11 16:49:14 +00001347 // Check default arguments now that we have merged decls.
1348 CheckCXXDefaultArguments(NewFD);
Douglas Gregor584049d2008-12-15 23:53:10 +00001349
1350 // An out-of-line member function declaration must also be a
1351 // definition (C++ [dcl.meaning]p1).
1352 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1353 !InvalidDecl) {
1354 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1355 << D.getCXXScopeSpec().getRange();
1356 NewFD->setInvalidDecl();
1357 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001358 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001359
Douglas Gregor44b43212008-12-11 16:49:14 +00001360 return NewFD;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001361 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001362 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001363
1364 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1365 // The user tried to provide an out-of-line definition for a
1366 // member function, but there was no such member function
1367 // declared (C++ [class.mfct]p2). For example:
1368 //
1369 // class X {
1370 // void f() const;
1371 // };
1372 //
1373 // void X::f() { } // ill-formed
1374 //
1375 // Complain about this problem, and attempt to suggest close
1376 // matches (e.g., those that differ only in cv-qualifiers and
1377 // whether the parameter types are references).
1378 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1379 << cast<CXXRecordDecl>(DC)->getDeclName()
1380 << D.getCXXScopeSpec().getRange();
1381 InvalidDecl = true;
1382
1383 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1384 if (!PrevDecl) {
1385 // Nothing to suggest.
1386 } else if (OverloadedFunctionDecl *Ovl
1387 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1388 for (OverloadedFunctionDecl::function_iterator
1389 Func = Ovl->function_begin(),
1390 FuncEnd = Ovl->function_end();
1391 Func != FuncEnd; ++Func) {
1392 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1393 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1394
1395 }
1396 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1397 // Suggest this no matter how mismatched it is; it's the only
1398 // thing we have.
1399 unsigned diag;
1400 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1401 diag = diag::note_member_def_close_match;
1402 else if (Method->getBody())
1403 diag = diag::note_previous_definition;
1404 else
1405 diag = diag::note_previous_declaration;
1406 Diag(Method->getLocation(), diag);
1407 }
1408
1409 PrevDecl = 0;
1410 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 }
1412 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001413
Douglas Gregor584049d2008-12-15 23:53:10 +00001414 if (getLangOptions().CPlusPlus) {
1415 // In C++, check default arguments now that we have merged decls.
Chris Lattner04421082008-04-08 04:40:51 +00001416 CheckCXXDefaultArguments(NewFD);
Douglas Gregor584049d2008-12-15 23:53:10 +00001417
1418 // An out-of-line member function declaration must also be a
1419 // definition (C++ [dcl.meaning]p1).
1420 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet()) {
1421 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1422 << D.getCXXScopeSpec().getRange();
1423 InvalidDecl = true;
1424 }
1425 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001427 // Check that there are no default arguments (C++ only).
1428 if (getLangOptions().CPlusPlus)
1429 CheckExtraCXXDefaultArguments(D);
1430
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001431 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001432 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1433 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001434 InvalidDecl = true;
1435 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001436
1437 VarDecl *NewVD;
1438 VarDecl::StorageClass SC;
1439 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001440 default: assert(0 && "Unknown storage class!");
1441 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1442 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1443 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1444 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1445 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1446 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001447 case DeclSpec::SCS_mutable:
1448 // mutable can only appear on non-static class members, so it's always
1449 // an error here
1450 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1451 InvalidDecl = true;
Douglas Gregore89b0282008-12-01 22:46:22 +00001452 SC = VarDecl::None;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001453 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001454 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001455
1456 IdentifierInfo *II = Name.getAsIdentifierInfo();
1457 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001458 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1459 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001460 return 0;
1461 }
1462
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001463 if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001464 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001465 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001466 D.getIdentifierLoc(), II,
1467 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001468 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001469 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001470 if (S->getFnParent() == 0) {
1471 // C99 6.9p2: The storage-class specifiers auto and register shall not
1472 // appear in the declaration specifiers in an external declaration.
1473 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerd1625842008-11-24 06:25:27 +00001474 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001475 InvalidDecl = true;
1476 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001477 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001478 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1479 II, R, SC, LastDeclarator,
1480 // FIXME: Move to DeclGroup...
1481 D.getDeclSpec().getSourceRange().getBegin());
1482 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001483 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001485 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001486
Daniel Dunbara735ad82008-08-06 00:03:29 +00001487 // Handle GNU asm-label extension (encoded as an attribute).
1488 if (Expr *E = (Expr*) D.getAsmLabel()) {
1489 // The parser guarantees this is a string.
1490 StringLiteral *SE = cast<StringLiteral>(E);
1491 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1492 SE->getByteLength())));
1493 }
1494
Nate Begemanc8e89a82008-03-14 18:07:10 +00001495 // Emit an error if an address space was applied to decl with local storage.
1496 // This includes arrays of objects with address space qualifiers, but not
1497 // automatic variables that point to other address spaces.
1498 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001499 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1500 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1501 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001502 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001503 // Merge the decl with the existing one if appropriate. If the decl is
1504 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001505 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001506 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1507 // The user tried to define a non-static data member
1508 // out-of-line (C++ [dcl.meaning]p1).
1509 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1510 << D.getCXXScopeSpec().getRange();
1511 NewVD->Destroy(Context);
1512 return 0;
1513 }
1514
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 NewVD = MergeVarDecl(NewVD, PrevDecl);
1516 if (NewVD == 0) return 0;
Douglas Gregor584049d2008-12-15 23:53:10 +00001517
1518 if (D.getCXXScopeSpec().isSet()) {
1519 // No previous declaration in the qualifying scope.
1520 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1521 << Name << D.getCXXScopeSpec().getRange();
1522 InvalidDecl = true;
1523 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 New = NewVD;
1526 }
1527
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001528 // Set the lexical context. If the declarator has a C++ scope specifier, the
1529 // lexical context will be different from the semantic context.
1530 New->setLexicalDeclContext(CurContext);
1531
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001533 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001534 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001535 // If any semantic error occurred, mark the decl as invalid.
1536 if (D.getInvalidType() || InvalidDecl)
1537 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001538
1539 return New;
1540}
1541
Steve Naroff6594a702008-10-27 11:34:16 +00001542void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001543 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1544 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001545}
1546
Eli Friedmanc594b322008-05-20 13:48:25 +00001547bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1548 switch (Init->getStmtClass()) {
1549 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001550 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001551 return true;
1552 case Expr::ParenExprClass: {
1553 const ParenExpr* PE = cast<ParenExpr>(Init);
1554 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1555 }
1556 case Expr::CompoundLiteralExprClass:
1557 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1558 case Expr::DeclRefExprClass: {
1559 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001560 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1561 if (VD->hasGlobalStorage())
1562 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001563 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001564 return true;
1565 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001566 if (isa<FunctionDecl>(D))
1567 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001568 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001569 return true;
1570 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001571 case Expr::MemberExprClass: {
1572 const MemberExpr *M = cast<MemberExpr>(Init);
1573 if (M->isArrow())
1574 return CheckAddressConstantExpression(M->getBase());
1575 return CheckAddressConstantExpressionLValue(M->getBase());
1576 }
1577 case Expr::ArraySubscriptExprClass: {
1578 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1579 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1580 return CheckAddressConstantExpression(ASE->getBase()) ||
1581 CheckArithmeticConstantExpression(ASE->getIdx());
1582 }
1583 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001584 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001585 return false;
1586 case Expr::UnaryOperatorClass: {
1587 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1588
1589 // C99 6.6p9
1590 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001591 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001592
Steve Naroff6594a702008-10-27 11:34:16 +00001593 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001594 return true;
1595 }
1596 }
1597}
1598
1599bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1600 switch (Init->getStmtClass()) {
1601 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001602 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001603 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001604 case Expr::ParenExprClass:
1605 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001606 case Expr::StringLiteralClass:
1607 case Expr::ObjCStringLiteralClass:
1608 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001609 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001610 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001611 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1612 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1613 Builtin::BI__builtin___CFStringMakeConstantString)
1614 return false;
1615
Steve Naroff6594a702008-10-27 11:34:16 +00001616 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001617 return true;
1618
Eli Friedmanc594b322008-05-20 13:48:25 +00001619 case Expr::UnaryOperatorClass: {
1620 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1621
1622 // C99 6.6p9
1623 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1624 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1625
1626 if (Exp->getOpcode() == UnaryOperator::Extension)
1627 return CheckAddressConstantExpression(Exp->getSubExpr());
1628
Steve Naroff6594a702008-10-27 11:34:16 +00001629 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001630 return true;
1631 }
1632 case Expr::BinaryOperatorClass: {
1633 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1634 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1635
1636 Expr *PExp = Exp->getLHS();
1637 Expr *IExp = Exp->getRHS();
1638 if (IExp->getType()->isPointerType())
1639 std::swap(PExp, IExp);
1640
1641 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1642 return CheckAddressConstantExpression(PExp) ||
1643 CheckArithmeticConstantExpression(IExp);
1644 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001645 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001646 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001647 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001648 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1649 // Check for implicit promotion
1650 if (SubExpr->getType()->isFunctionType() ||
1651 SubExpr->getType()->isArrayType())
1652 return CheckAddressConstantExpressionLValue(SubExpr);
1653 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001654
1655 // Check for pointer->pointer cast
1656 if (SubExpr->getType()->isPointerType())
1657 return CheckAddressConstantExpression(SubExpr);
1658
Eli Friedmanc3f07642008-08-25 20:46:57 +00001659 if (SubExpr->getType()->isIntegralType()) {
1660 // Check for the special-case of a pointer->int->pointer cast;
1661 // this isn't standard, but some code requires it. See
1662 // PR2720 for an example.
1663 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1664 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1665 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1666 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1667 if (IntWidth >= PointerWidth) {
1668 return CheckAddressConstantExpression(SubCast->getSubExpr());
1669 }
1670 }
1671 }
1672 }
1673 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001674 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001675 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001676
Steve Naroff6594a702008-10-27 11:34:16 +00001677 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001678 return true;
1679 }
1680 case Expr::ConditionalOperatorClass: {
1681 // FIXME: Should we pedwarn here?
1682 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1683 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001684 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001685 return true;
1686 }
1687 if (CheckArithmeticConstantExpression(Exp->getCond()))
1688 return true;
1689 if (Exp->getLHS() &&
1690 CheckAddressConstantExpression(Exp->getLHS()))
1691 return true;
1692 return CheckAddressConstantExpression(Exp->getRHS());
1693 }
1694 case Expr::AddrLabelExprClass:
1695 return false;
1696 }
1697}
1698
Eli Friedman4caf0552008-06-09 05:05:07 +00001699static const Expr* FindExpressionBaseAddress(const Expr* E);
1700
1701static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1702 switch (E->getStmtClass()) {
1703 default:
1704 return E;
1705 case Expr::ParenExprClass: {
1706 const ParenExpr* PE = cast<ParenExpr>(E);
1707 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1708 }
1709 case Expr::MemberExprClass: {
1710 const MemberExpr *M = cast<MemberExpr>(E);
1711 if (M->isArrow())
1712 return FindExpressionBaseAddress(M->getBase());
1713 return FindExpressionBaseAddressLValue(M->getBase());
1714 }
1715 case Expr::ArraySubscriptExprClass: {
1716 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1717 return FindExpressionBaseAddress(ASE->getBase());
1718 }
1719 case Expr::UnaryOperatorClass: {
1720 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1721
1722 if (Exp->getOpcode() == UnaryOperator::Deref)
1723 return FindExpressionBaseAddress(Exp->getSubExpr());
1724
1725 return E;
1726 }
1727 }
1728}
1729
1730static const Expr* FindExpressionBaseAddress(const Expr* E) {
1731 switch (E->getStmtClass()) {
1732 default:
1733 return E;
1734 case Expr::ParenExprClass: {
1735 const ParenExpr* PE = cast<ParenExpr>(E);
1736 return FindExpressionBaseAddress(PE->getSubExpr());
1737 }
1738 case Expr::UnaryOperatorClass: {
1739 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1740
1741 // C99 6.6p9
1742 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1743 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1744
1745 if (Exp->getOpcode() == UnaryOperator::Extension)
1746 return FindExpressionBaseAddress(Exp->getSubExpr());
1747
1748 return E;
1749 }
1750 case Expr::BinaryOperatorClass: {
1751 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1752
1753 Expr *PExp = Exp->getLHS();
1754 Expr *IExp = Exp->getRHS();
1755 if (IExp->getType()->isPointerType())
1756 std::swap(PExp, IExp);
1757
1758 return FindExpressionBaseAddress(PExp);
1759 }
1760 case Expr::ImplicitCastExprClass: {
1761 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1762
1763 // Check for implicit promotion
1764 if (SubExpr->getType()->isFunctionType() ||
1765 SubExpr->getType()->isArrayType())
1766 return FindExpressionBaseAddressLValue(SubExpr);
1767
1768 // Check for pointer->pointer cast
1769 if (SubExpr->getType()->isPointerType())
1770 return FindExpressionBaseAddress(SubExpr);
1771
1772 // We assume that we have an arithmetic expression here;
1773 // if we don't, we'll figure it out later
1774 return 0;
1775 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001776 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001777 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1778
1779 // Check for pointer->pointer cast
1780 if (SubExpr->getType()->isPointerType())
1781 return FindExpressionBaseAddress(SubExpr);
1782
1783 // We assume that we have an arithmetic expression here;
1784 // if we don't, we'll figure it out later
1785 return 0;
1786 }
1787 }
1788}
1789
Anders Carlsson51fe9962008-11-22 21:04:56 +00001790bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001791 switch (Init->getStmtClass()) {
1792 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001793 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001794 return true;
1795 case Expr::ParenExprClass: {
1796 const ParenExpr* PE = cast<ParenExpr>(Init);
1797 return CheckArithmeticConstantExpression(PE->getSubExpr());
1798 }
1799 case Expr::FloatingLiteralClass:
1800 case Expr::IntegerLiteralClass:
1801 case Expr::CharacterLiteralClass:
1802 case Expr::ImaginaryLiteralClass:
1803 case Expr::TypesCompatibleExprClass:
1804 case Expr::CXXBoolLiteralExprClass:
1805 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001806 case Expr::CallExprClass:
1807 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001808 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001809
1810 // Allow any constant foldable calls to builtins.
1811 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001812 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001813
Steve Naroff6594a702008-10-27 11:34:16 +00001814 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001815 return true;
1816 }
1817 case Expr::DeclRefExprClass: {
1818 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1819 if (isa<EnumConstantDecl>(D))
1820 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001821 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001822 return true;
1823 }
1824 case Expr::CompoundLiteralExprClass:
1825 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1826 // but vectors are allowed to be magic.
1827 if (Init->getType()->isVectorType())
1828 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001829 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001830 return true;
1831 case Expr::UnaryOperatorClass: {
1832 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1833
1834 switch (Exp->getOpcode()) {
1835 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1836 // See C99 6.6p3.
1837 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001838 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001839 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001840 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00001841 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1842 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001843 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001844 return true;
1845 case UnaryOperator::Extension:
1846 case UnaryOperator::LNot:
1847 case UnaryOperator::Plus:
1848 case UnaryOperator::Minus:
1849 case UnaryOperator::Not:
1850 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1851 }
1852 }
Sebastian Redl05189992008-11-11 17:56:53 +00001853 case Expr::SizeOfAlignOfExprClass: {
1854 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001855 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00001856 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00001857 return false;
1858 // alignof always evaluates to a constant.
1859 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00001860 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001861 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001862 return true;
1863 }
1864 return false;
1865 }
1866 case Expr::BinaryOperatorClass: {
1867 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1868
1869 if (Exp->getLHS()->getType()->isArithmeticType() &&
1870 Exp->getRHS()->getType()->isArithmeticType()) {
1871 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1872 CheckArithmeticConstantExpression(Exp->getRHS());
1873 }
1874
Eli Friedman4caf0552008-06-09 05:05:07 +00001875 if (Exp->getLHS()->getType()->isPointerType() &&
1876 Exp->getRHS()->getType()->isPointerType()) {
1877 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1878 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1879
1880 // Only allow a null (constant integer) base; we could
1881 // allow some additional cases if necessary, but this
1882 // is sufficient to cover offsetof-like constructs.
1883 if (!LHSBase && !RHSBase) {
1884 return CheckAddressConstantExpression(Exp->getLHS()) ||
1885 CheckAddressConstantExpression(Exp->getRHS());
1886 }
1887 }
1888
Steve Naroff6594a702008-10-27 11:34:16 +00001889 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001890 return true;
1891 }
1892 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001893 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001894 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001895 if (SubExpr->getType()->isArithmeticType())
1896 return CheckArithmeticConstantExpression(SubExpr);
1897
Eli Friedmanb529d832008-09-02 09:37:00 +00001898 if (SubExpr->getType()->isPointerType()) {
1899 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1900 // If the pointer has a null base, this is an offsetof-like construct
1901 if (!Base)
1902 return CheckAddressConstantExpression(SubExpr);
1903 }
1904
Steve Naroff6594a702008-10-27 11:34:16 +00001905 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001906 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001907 }
1908 case Expr::ConditionalOperatorClass: {
1909 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001910
1911 // If GNU extensions are disabled, we require all operands to be arithmetic
1912 // constant expressions.
1913 if (getLangOptions().NoExtensions) {
1914 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1915 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1916 CheckArithmeticConstantExpression(Exp->getRHS());
1917 }
1918
1919 // Otherwise, we have to emulate some of the behavior of fold here.
1920 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1921 // because it can constant fold things away. To retain compatibility with
1922 // GCC code, we see if we can fold the condition to a constant (which we
1923 // should always be able to do in theory). If so, we only require the
1924 // specified arm of the conditional to be a constant. This is a horrible
1925 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001926 Expr::EvalResult EvalResult;
1927 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
1928 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001929 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00001930 // won't be able to either. Use it to emit the diagnostic though.
1931 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001932 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00001933 return Res;
1934 }
1935
1936 // Verify that the side following the condition is also a constant.
1937 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001938 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00001939 std::swap(TrueSide, FalseSide);
1940
1941 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001942 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001943
1944 // Okay, the evaluated side evaluates to a constant, so we accept this.
1945 // Check to see if the other side is obviously not a constant. If so,
1946 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001947 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001948 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001949 diag::ext_typecheck_expression_not_constant_but_accepted)
1950 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00001951 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001952 }
1953 }
1954}
1955
1956bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001957 Expr::EvalResult Result;
1958
Nuno Lopes9a979c32008-07-07 16:46:50 +00001959 Init = Init->IgnoreParens();
1960
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001961 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
1962 return false;
1963
Eli Friedmanc594b322008-05-20 13:48:25 +00001964 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1965 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1966 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1967
Nuno Lopes9a979c32008-07-07 16:46:50 +00001968 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1969 return CheckForConstantInitializer(e->getInitializer(), DclT);
1970
Eli Friedmanc594b322008-05-20 13:48:25 +00001971 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1972 unsigned numInits = Exp->getNumInits();
1973 for (unsigned i = 0; i < numInits; i++) {
1974 // FIXME: Need to get the type of the declaration for C++,
1975 // because it could be a reference?
1976 if (CheckForConstantInitializer(Exp->getInit(i),
1977 Exp->getInit(i)->getType()))
1978 return true;
1979 }
1980 return false;
1981 }
1982
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001983 // FIXME: We can probably remove some of this code below, now that
1984 // Expr::Evaluate is doing the heavy lifting for scalars.
1985
Eli Friedmanc594b322008-05-20 13:48:25 +00001986 if (Init->isNullPointerConstant(Context))
1987 return false;
1988 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001989 QualType InitTy = Context.getCanonicalType(Init->getType())
1990 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001991 if (InitTy == Context.BoolTy) {
1992 // Special handling for pointers implicitly cast to bool;
1993 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1994 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1995 Expr* SubE = ICE->getSubExpr();
1996 if (SubE->getType()->isPointerType() ||
1997 SubE->getType()->isArrayType() ||
1998 SubE->getType()->isFunctionType()) {
1999 return CheckAddressConstantExpression(Init);
2000 }
2001 }
2002 } else if (InitTy->isIntegralType()) {
2003 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002004 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002005 SubE = CE->getSubExpr();
2006 // Special check for pointer cast to int; we allow as an extension
2007 // an address constant cast to an integer if the integer
2008 // is of an appropriate width (this sort of code is apparently used
2009 // in some places).
2010 // FIXME: Add pedwarn?
2011 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2012 if (SubE && (SubE->getType()->isPointerType() ||
2013 SubE->getType()->isArrayType() ||
2014 SubE->getType()->isFunctionType())) {
2015 unsigned IntWidth = Context.getTypeSize(Init->getType());
2016 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2017 if (IntWidth >= PointerWidth)
2018 return CheckAddressConstantExpression(Init);
2019 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002020 }
2021
2022 return CheckArithmeticConstantExpression(Init);
2023 }
2024
2025 if (Init->getType()->isPointerType())
2026 return CheckAddressConstantExpression(Init);
2027
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002028 // An array type at the top level that isn't an init-list must
2029 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002030 if (Init->getType()->isArrayType())
2031 return false;
2032
Nuno Lopes73419bf2008-09-01 18:42:41 +00002033 if (Init->getType()->isFunctionType())
2034 return false;
2035
Steve Naroff8af6a452008-10-02 17:12:56 +00002036 // Allow block exprs at top level.
2037 if (Init->getType()->isBlockPointerType())
2038 return false;
2039
Steve Naroff6594a702008-10-27 11:34:16 +00002040 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002041 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002042}
2043
Sebastian Redl798d1192008-12-13 16:23:55 +00002044void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002045 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002046 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002047 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002048
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002049 // If there is no declaration, there was an error parsing it. Just ignore
2050 // the initializer.
2051 if (RealDecl == 0) {
2052 delete Init;
2053 return;
2054 }
Steve Naroffbb204692007-09-12 14:07:44 +00002055
Steve Naroff410e3e22007-09-12 20:13:48 +00002056 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2057 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00002058 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2059 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002060 RealDecl->setInvalidDecl();
2061 return;
2062 }
Steve Naroffbb204692007-09-12 14:07:44 +00002063 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002064 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002065 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002066 if (VDecl->isBlockVarDecl()) {
2067 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002068 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002069 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002070 VDecl->setInvalidDecl();
2071 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002072 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002073 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002074 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002075
2076 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2077 if (!getLangOptions().CPlusPlus) {
2078 if (SC == VarDecl::Static) // C99 6.7.8p4.
2079 CheckForConstantInitializer(Init, DclT);
2080 }
Steve Naroffbb204692007-09-12 14:07:44 +00002081 }
Steve Naroff248a7532008-04-15 22:42:06 +00002082 } else if (VDecl->isFileVarDecl()) {
2083 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002084 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002085 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002086 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002087 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002088 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002089
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002090 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2091 if (!getLangOptions().CPlusPlus) {
2092 // C99 6.7.8p4. All file scoped initializers need to be constant.
2093 CheckForConstantInitializer(Init, DclT);
2094 }
Steve Naroffbb204692007-09-12 14:07:44 +00002095 }
2096 // If the type changed, it means we had an incomplete type that was
2097 // completed by the initializer. For example:
2098 // int ary[] = { 1, 3, 5 };
2099 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002100 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002101 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002102 Init->setType(DclT);
2103 }
Steve Naroffbb204692007-09-12 14:07:44 +00002104
2105 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002106 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002107 return;
2108}
2109
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002110void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2111 Decl *RealDecl = static_cast<Decl *>(dcl);
2112
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002113 // If there is no declaration, there was an error parsing it. Just ignore it.
2114 if (RealDecl == 0)
2115 return;
2116
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002117 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2118 QualType Type = Var->getType();
2119 // C++ [dcl.init.ref]p3:
2120 // The initializer can be omitted for a reference only in a
2121 // parameter declaration (8.3.5), in the declaration of a
2122 // function return type, in the declaration of a class member
2123 // within its class declaration (9.2), and where the extern
2124 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002125 if (Type->isReferenceType() &&
2126 Var->getStorageClass() != VarDecl::Extern &&
2127 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002128 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002129 << Var->getDeclName()
2130 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002131 Var->setInvalidDecl();
2132 return;
2133 }
2134
2135 // C++ [dcl.init]p9:
2136 //
2137 // If no initializer is specified for an object, and the object
2138 // is of (possibly cv-qualified) non-POD class type (or array
2139 // thereof), the object shall be default-initialized; if the
2140 // object is of const-qualified type, the underlying class type
2141 // shall have a user-declared default constructor.
2142 if (getLangOptions().CPlusPlus) {
2143 QualType InitType = Type;
2144 if (const ArrayType *Array = Context.getAsArrayType(Type))
2145 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002146 if (Var->getStorageClass() != VarDecl::Extern &&
2147 Var->getStorageClass() != VarDecl::PrivateExtern &&
2148 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002149 const CXXConstructorDecl *Constructor
2150 = PerformInitializationByConstructor(InitType, 0, 0,
2151 Var->getLocation(),
2152 SourceRange(Var->getLocation(),
2153 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002154 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002155 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002156 if (!Constructor)
2157 Var->setInvalidDecl();
2158 }
2159 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002160
Douglas Gregor818ce482008-10-29 13:50:18 +00002161#if 0
2162 // FIXME: Temporarily disabled because we are not properly parsing
2163 // linkage specifications on declarations, e.g.,
2164 //
2165 // extern "C" const CGPoint CGPointerZero;
2166 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002167 // C++ [dcl.init]p9:
2168 //
2169 // If no initializer is specified for an object, and the
2170 // object is of (possibly cv-qualified) non-POD class type (or
2171 // array thereof), the object shall be default-initialized; if
2172 // the object is of const-qualified type, the underlying class
2173 // type shall have a user-declared default
2174 // constructor. Otherwise, if no initializer is specified for
2175 // an object, the object and its subobjects, if any, have an
2176 // indeterminate initial value; if the object or any of its
2177 // subobjects are of const-qualified type, the program is
2178 // ill-formed.
2179 //
2180 // This isn't technically an error in C, so we don't diagnose it.
2181 //
2182 // FIXME: Actually perform the POD/user-defined default
2183 // constructor check.
2184 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002185 Context.getCanonicalType(Type).isConstQualified() &&
2186 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002187 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2188 << Var->getName()
2189 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002190#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002191 }
2192}
2193
Reid Spencer5f016e22007-07-11 17:01:13 +00002194/// The declarators are chained together backwards, reverse the list.
2195Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2196 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002197 Decl *GroupDecl = static_cast<Decl*>(group);
2198 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002199 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002200
2201 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2202 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002203 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002204 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002205 else { // reverse the list.
2206 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00002207 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002208 Group->setNextDeclarator(NewGroup);
2209 NewGroup = Group;
2210 Group = Next;
2211 }
2212 }
2213 // Perform semantic analysis that depends on having fully processed both
2214 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00002215 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002216 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2217 if (!IDecl)
2218 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002219 QualType T = IDecl->getType();
2220
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002221 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002222 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002223
2224 // FIXME: This won't give the correct result for
2225 // int a[10][n];
2226 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002227 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002228 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2229 SizeRange;
2230
Eli Friedmanc5773c42008-02-15 18:16:39 +00002231 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002232 } else {
2233 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2234 // static storage duration, it shall not have a variable length array.
2235 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002236 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2237 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002238 IDecl->setInvalidDecl();
2239 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002240 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2241 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002242 IDecl->setInvalidDecl();
2243 }
2244 }
2245 } else if (T->isVariablyModifiedType()) {
2246 if (IDecl->isFileVarDecl()) {
2247 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2248 IDecl->setInvalidDecl();
2249 } else {
2250 if (IDecl->getStorageClass() == VarDecl::Extern) {
2251 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2252 IDecl->setInvalidDecl();
2253 }
Steve Naroffbb204692007-09-12 14:07:44 +00002254 }
2255 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002256
Steve Naroffbb204692007-09-12 14:07:44 +00002257 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2258 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002259 if (IDecl->isBlockVarDecl() &&
2260 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002261 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002262 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002263 IDecl->setInvalidDecl();
2264 }
2265 }
2266 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2267 // object that has file scope without an initializer, and without a
2268 // storage-class specifier or with the storage-class specifier "static",
2269 // constitutes a tentative definition. Note: A tentative definition with
2270 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002271 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002272 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002273 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2274 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002275 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002276 // C99 6.9.2p3: If the declaration of an identifier for an object is
2277 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2278 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002279 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002280 IDecl->setInvalidDecl();
2281 }
2282 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002283 if (IDecl->isFileVarDecl())
2284 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002285 }
2286 return NewGroup;
2287}
Steve Naroffe1223f72007-08-28 03:03:08 +00002288
Chris Lattner04421082008-04-08 04:40:51 +00002289/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2290/// to introduce parameters into function prototype scope.
2291Sema::DeclTy *
2292Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002293 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002294
Chris Lattner04421082008-04-08 04:40:51 +00002295 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002296 VarDecl::StorageClass StorageClass = VarDecl::None;
2297 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2298 StorageClass = VarDecl::Register;
2299 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002300 Diag(DS.getStorageClassSpecLoc(),
2301 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002302 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002303 }
2304 if (DS.isThreadSpecified()) {
2305 Diag(DS.getThreadSpecLoc(),
2306 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002307 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002308 }
2309
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002310 // Check that there are no default arguments inside the type of this
2311 // parameter (C++ only).
2312 if (getLangOptions().CPlusPlus)
2313 CheckExtraCXXDefaultArguments(D);
2314
Chris Lattner04421082008-04-08 04:40:51 +00002315 // In this context, we *do not* check D.getInvalidType(). If the declarator
2316 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2317 // though it will not reflect the user specified type.
2318 QualType parmDeclType = GetTypeForDeclarator(D, S);
2319
2320 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2321
Reid Spencer5f016e22007-07-11 17:01:13 +00002322 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2323 // Can this happen for params? We already checked that they don't conflict
2324 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002325 IdentifierInfo *II = D.getIdentifier();
2326 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregorf57172b2008-12-08 18:40:42 +00002327 if (PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002328 // Maybe we will complain about the shadowed template parameter.
2329 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2330 // Just pretend that we didn't see the previous declaration.
2331 PrevDecl = 0;
2332 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002333 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002334
2335 // Recover by removing the name
2336 II = 0;
2337 D.SetIdentifier(0, D.getIdentifierLoc());
2338 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002339 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002340
2341 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2342 // Doing the promotion here has a win and a loss. The win is the type for
2343 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2344 // code generator). The loss is the orginal type isn't preserved. For example:
2345 //
2346 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2347 // int blockvardecl[5];
2348 // sizeof(parmvardecl); // size == 4
2349 // sizeof(blockvardecl); // size == 20
2350 // }
2351 //
2352 // For expressions, all implicit conversions are captured using the
2353 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2354 //
2355 // FIXME: If a source translation tool needs to see the original type, then
2356 // we need to consider storing both types (in ParmVarDecl)...
2357 //
Chris Lattnere6327742008-04-02 05:18:44 +00002358 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002359 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002360 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002361 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002362 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002363
Chris Lattner04421082008-04-08 04:40:51 +00002364 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2365 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002366 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002367 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002368
Chris Lattner04421082008-04-08 04:40:51 +00002369 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002370 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002371
Douglas Gregor584049d2008-12-15 23:53:10 +00002372 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2373 if (D.getCXXScopeSpec().isSet()) {
2374 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2375 << D.getCXXScopeSpec().getRange();
2376 New->setInvalidDecl();
2377 }
2378
Douglas Gregor44b43212008-12-11 16:49:14 +00002379 // Add the parameter declaration into this scope.
2380 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002381 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002382 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002383
Chris Lattner3ff30c82008-06-29 00:02:00 +00002384 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002385 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002386
Reid Spencer5f016e22007-07-11 17:01:13 +00002387}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002388
Chris Lattnerb652cea2007-10-09 17:14:05 +00002389Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002390 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002391 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2392 "Not a function declarator!");
2393 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002394
Reid Spencer5f016e22007-07-11 17:01:13 +00002395 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2396 // for a K&R function.
2397 if (!FTI.hasPrototype) {
2398 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002399 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002400 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2401 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002402 // Implicitly declare the argument as type 'int' for lack of a better
2403 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002404 DeclSpec DS;
2405 const char* PrevSpec; // unused
2406 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2407 PrevSpec);
2408 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2409 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2410 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002411 }
2412 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002413 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002414 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002415 }
2416
Douglas Gregor584049d2008-12-15 23:53:10 +00002417 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002418
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002419 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002420 ActOnDeclarator(ParentScope, D, 0,
2421 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002422}
2423
2424Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2425 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002426 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002427
2428 // See if this is a redefinition.
2429 const FunctionDecl *Definition;
2430 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002431 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002432 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002433 }
2434
Douglas Gregor44b43212008-12-11 16:49:14 +00002435 PushDeclContext(FnBodyScope, FD);
Chris Lattner04421082008-04-08 04:40:51 +00002436
2437 // Check the validity of our function parameters
2438 CheckParmsForFunctionDef(FD);
2439
2440 // Introduce our parameters into the function scope
2441 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2442 ParmVarDecl *Param = FD->getParamDecl(p);
2443 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002444 if (Param->getIdentifier())
2445 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002446 }
Chris Lattner04421082008-04-08 04:40:51 +00002447
Reid Spencer5f016e22007-07-11 17:01:13 +00002448 return FD;
2449}
2450
Sebastian Redl798d1192008-12-13 16:23:55 +00002451Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002452 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002453 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002454 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002455 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002456 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002457 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002458 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002459 } else
2460 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002461 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002462 // Verify and clean out per-function state.
2463
2464 // Check goto/label use.
2465 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2466 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2467 // Verify that we have no forward references left. If so, there was a goto
2468 // or address of a label taken, but no definition of it. Label fwd
2469 // definitions are indicated with a null substmt.
2470 if (I->second->getSubStmt() == 0) {
2471 LabelStmt *L = I->second;
2472 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002473 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002474
2475 // At this point, we have gotos that use the bogus label. Stitch it into
2476 // the function body so that they aren't leaked and that the AST is well
2477 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002478 if (Body) {
2479 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002480 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002481 } else {
2482 // The whole function wasn't parsed correctly, just delete this.
2483 delete L;
2484 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002485 }
2486 }
2487 LabelMap.clear();
2488
Steve Naroffd6d054d2007-11-11 23:20:51 +00002489 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002490}
2491
Reid Spencer5f016e22007-07-11 17:01:13 +00002492/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2493/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002494ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2495 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002496 // Extension in C99. Legal in C90, but warn about it.
2497 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002498 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002499 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002500 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002501
2502 // FIXME: handle stuff like:
2503 // void foo() { extern float X(); }
2504 // void bar() { X(); } <-- implicit decl for X in another scope.
2505
2506 // Set a Declarator for the implicit definition: int foo();
2507 const char *Dummy;
2508 DeclSpec DS;
2509 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2510 Error = Error; // Silence warning.
2511 assert(!Error && "Error setting up implicit decl!");
2512 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002513 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002514 D.SetIdentifier(&II, Loc);
2515
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002516 // Insert this function into translation-unit scope.
2517
2518 DeclContext *PrevDC = CurContext;
2519 CurContext = Context.getTranslationUnitDecl();
2520
Steve Naroffe2ef8152008-04-04 14:32:09 +00002521 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002522 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002523 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002524
2525 CurContext = PrevDC;
2526
Steve Naroffe2ef8152008-04-04 14:32:09 +00002527 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002528}
2529
2530
Chris Lattner41af0932007-11-14 06:34:38 +00002531TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002532 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002533 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002534 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002535
2536 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002537 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2538 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002539 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002540 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002541 if (D.getInvalidType())
2542 NewTD->setInvalidDecl();
2543 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002544}
2545
Steve Naroff08d92e42007-09-15 18:49:24 +00002546/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002547/// former case, Name will be non-null. In the later case, Name will be null.
2548/// TagType indicates what kind of tag this is. TK indicates whether this is a
2549/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002550Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002551 SourceLocation KWLoc, const CXXScopeSpec &SS,
2552 IdentifierInfo *Name, SourceLocation NameLoc,
2553 AttributeList *Attr) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002554 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002555 assert((Name != 0 || TK == TK_Definition) &&
2556 "Nameless record must be a definition!");
2557
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002558 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002559 switch (TagType) {
2560 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002561 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2562 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2563 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2564 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002565 }
2566
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002567 DeclContext *DC = CurContext;
2568 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002569
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002570 if (Name && SS.isNotEmpty()) {
2571 // We have a nested-name tag ('struct foo::bar').
2572
2573 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002574 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002575 Name = 0;
2576 goto CreateNewDecl;
2577 }
2578
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002579 DC = static_cast<DeclContext*>(SS.getScopeRep());
2580 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002581 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2582
2583 // A tag 'foo::bar' must already exist.
2584 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002585 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002586 Name = 0;
2587 goto CreateNewDecl;
2588 }
2589 } else {
2590 // If this is a named struct, check to see if there was a previous forward
2591 // declaration or definition.
2592 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2593 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2594 }
2595
Douglas Gregorf57172b2008-12-08 18:40:42 +00002596 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002597 // Maybe we will complain about the shadowed template parameter.
2598 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2599 // Just pretend that we didn't see the previous declaration.
2600 PrevDecl = 0;
2601 }
2602
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002603 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002604 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2605 "unexpected Decl type");
2606 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002607 // If this is a use of a previous tag, or if the tag is already declared
2608 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002609 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002610 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002611 // Make sure that this wasn't declared as an enum and now used as a
2612 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002613 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002614 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002615 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002616 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002617 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002618 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002619 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002620 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002621
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002622 // FIXME: In the future, return a variant or some other clue
2623 // for the consumer of this Decl to know it doesn't own it.
2624 // For our current ASTs this shouldn't be a problem, but will
2625 // need to be changed with DeclGroups.
2626 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002627 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002628
2629 // Diagnose attempts to redefine a tag.
2630 if (TK == TK_Definition) {
2631 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2632 Diag(NameLoc, diag::err_redefinition) << Name;
2633 Diag(Def->getLocation(), diag::note_previous_definition);
2634 // If this is a redefinition, recover by making this struct be
2635 // anonymous, which will make any later references get the previous
2636 // definition.
2637 Name = 0;
2638 PrevDecl = 0;
2639 }
2640 // Okay, this is definition of a previously declared or referenced
2641 // tag PrevDecl. We're going to create a new Decl for it.
2642 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002643 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002644 // If we get here we have (another) forward declaration or we
2645 // have a definition. Just create a new decl.
2646 } else {
2647 // If we get here, this is a definition of a new tag type in a nested
2648 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2649 // new decl/type. We set PrevDecl to NULL so that the entities
2650 // have distinct types.
2651 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002652 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002653 // If we get here, we're going to create a new Decl. If PrevDecl
2654 // is non-NULL, it's a definition of the tag declared by
2655 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002656 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002657 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002658 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002659 // The tag name clashes with a namespace name, issue an error and
2660 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002661 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002662 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002663 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002664 PrevDecl = 0;
2665 } else {
2666 // The existing declaration isn't relevant to us; we're in a
2667 // new scope, so clear out the previous declaration.
2668 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002669 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002670 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002672
Chris Lattnercc98eac2008-12-17 07:13:27 +00002673CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002674
2675 // If there is an identifier, use the location of the identifier as the
2676 // location of the decl, otherwise use the location of the struct/union
2677 // keyword.
2678 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2679
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002680 // Otherwise, create a new declaration. If there is a previous
2681 // declaration of the same entity, the two will be linked via
2682 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00002683 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002684 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002685 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2686 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002687 New = EnumDecl::Create(Context, DC, Loc, Name,
2688 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002689 // If this is an undefined enum, warn.
2690 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002691 } else {
2692 // struct/union/class
2693
Reid Spencer5f016e22007-07-11 17:01:13 +00002694 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2695 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002696 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002697 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002698 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2699 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002700 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002701 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2702 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002703 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002704
2705 if (Kind != TagDecl::TK_enum) {
2706 // Handle #pragma pack: if the #pragma pack stack has non-default
2707 // alignment, make up a packed attribute for this decl. These
2708 // attributes are checked when the ASTContext lays out the
2709 // structure.
2710 //
2711 // It is important for implementing the correct semantics that this
2712 // happen here (in act on tag decl). The #pragma pack stack is
2713 // maintained as a result of parser callbacks which can occur at
2714 // many points during the parsing of a struct declaration (because
2715 // the #pragma tokens are effectively skipped over during the
2716 // parsing of the struct).
2717 if (unsigned Alignment = PackContext.getAlignment())
2718 New->addAttr(new PackedAttr(Alignment * 8));
2719 }
2720
2721 if (Attr)
2722 ProcessDeclAttributeList(New, Attr);
2723
2724 // Set the lexical context. If the tag has a C++ scope specifier, the
2725 // lexical context will be different from the semantic context.
2726 New->setLexicalDeclContext(CurContext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002727
2728 // If this has an identifier, add it to the scope stack.
2729 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002730 // The scope passed in may not be a decl scope. Zip up the scope tree until
2731 // we find one that is.
2732 while ((S->getFlags() & Scope::DeclScope) == 0)
2733 S = S->getParent();
2734
2735 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002736 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002738
Reid Spencer5f016e22007-07-11 17:01:13 +00002739 return New;
2740}
2741
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002742
Chris Lattner1d353ba2008-11-12 21:17:48 +00002743/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2744/// types into constant array types in certain situations which would otherwise
2745/// be errors (for GCC compatibility).
2746static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2747 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002748 // This method tries to turn a variable array into a constant
2749 // array even when the size isn't an ICE. This is necessary
2750 // for compatibility with code that depends on gcc's buggy
2751 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00002752 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2753 if (!VLATy) return QualType();
2754
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002755 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00002756 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002757 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00002758 return QualType();
2759
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002760 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
2761 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00002762 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2763 return Context.getConstantArrayType(VLATy->getElementType(),
2764 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002765 return QualType();
2766}
2767
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002768bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00002769 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002770 // FIXME: 6.7.2.1p4 - verify the field type.
2771
2772 llvm::APSInt Value;
2773 if (VerifyIntegerConstantExpression(BitWidth, &Value))
2774 return true;
2775
Chris Lattnercd087072008-12-12 04:56:04 +00002776 // Zero-width bitfield is ok for anonymous field.
2777 if (Value == 0 && FieldName)
2778 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
2779
2780 if (Value.isNegative())
2781 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002782
2783 uint64_t TypeSize = Context.getTypeSize(FieldTy);
2784 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00002785 if (TypeSize && Value.getZExtValue() > TypeSize)
2786 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
2787 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002788
2789 return false;
2790}
2791
Steve Naroff08d92e42007-09-15 18:49:24 +00002792/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002793/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00002794Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00002795 SourceLocation DeclStart,
2796 Declarator &D, ExprTy *BitfieldWidth) {
2797 IdentifierInfo *II = D.getIdentifier();
2798 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002799 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00002800 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002801 if (II) Loc = D.getIdentifierLoc();
2802
2803 // FIXME: Unnamed fields can be handled in various different ways, for
2804 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00002805
Reid Spencer5f016e22007-07-11 17:01:13 +00002806 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002807 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2808 bool InvalidDecl = false;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002809
Reid Spencer5f016e22007-07-11 17:01:13 +00002810 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2811 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002812 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00002813 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002814 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002815 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002816 T = FixedTy;
2817 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002818 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00002819 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002820 InvalidDecl = true;
2821 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002822 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002823
2824 if (BitWidth) {
2825 if (VerifyBitField(Loc, II, T, BitWidth))
2826 InvalidDecl = true;
2827 } else {
2828 // Not a bitfield.
2829
2830 // validate II.
2831
2832 }
2833
Reid Spencer5f016e22007-07-11 17:01:13 +00002834 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002835 FieldDecl *NewFD;
2836
Douglas Gregor44b43212008-12-11 16:49:14 +00002837 // FIXME: We don't want CurContext for C, do we? No, we'll need some
2838 // other way to determine the current RecordDecl.
2839 NewFD = FieldDecl::Create(Context, Record,
2840 Loc, II, T, BitWidth,
2841 D.getDeclSpec().getStorageClassSpec() ==
2842 DeclSpec::SCS_mutable,
2843 /*PrevDecl=*/0);
2844
Douglas Gregor72b505b2008-12-16 21:30:33 +00002845 if (getLangOptions().CPlusPlus)
2846 CheckExtraCXXDefaultArguments(D);
2847
Chris Lattner3ff30c82008-06-29 00:02:00 +00002848 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002849
Steve Naroff5912a352007-08-28 20:14:24 +00002850 if (D.getInvalidType() || InvalidDecl)
2851 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002852
2853 if (II && getLangOptions().CPlusPlus)
2854 PushOnScopeChains(NewFD, S);
2855 else
2856 Record->addDecl(Context, NewFD);
2857
Steve Naroff5912a352007-08-28 20:14:24 +00002858 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002859}
2860
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002861/// TranslateIvarVisibility - Translate visibility from a token ID to an
2862/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002863static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002864TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002865 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002866 default: assert(0 && "Unknown visitibility kind");
2867 case tok::objc_private: return ObjCIvarDecl::Private;
2868 case tok::objc_public: return ObjCIvarDecl::Public;
2869 case tok::objc_protected: return ObjCIvarDecl::Protected;
2870 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002871 }
2872}
2873
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002874/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2875/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002876Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002877 SourceLocation DeclStart,
2878 Declarator &D, ExprTy *BitfieldWidth,
2879 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002880 IdentifierInfo *II = D.getIdentifier();
2881 Expr *BitWidth = (Expr*)BitfieldWidth;
2882 SourceLocation Loc = DeclStart;
2883 if (II) Loc = D.getIdentifierLoc();
2884
2885 // FIXME: Unnamed fields can be handled in various different ways, for
2886 // example, unnamed unions inject all members into the struct namespace!
2887
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002888 QualType T = GetTypeForDeclarator(D, S);
2889 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2890 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002891
2892 if (BitWidth) {
2893 // TODO: Validate.
2894 //printf("WARNING: BITFIELDS IGNORED!\n");
2895
2896 // 6.7.2.1p3
2897 // 6.7.2.1p4
2898
2899 } else {
2900 // Not a bitfield.
2901
2902 // validate II.
2903
2904 }
2905
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002906 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2907 // than a variably modified type.
2908 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002909 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002910 InvalidDecl = true;
2911 }
2912
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002913 // Get the visibility (access control) for this ivar.
2914 ObjCIvarDecl::AccessControl ac =
2915 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2916 : ObjCIvarDecl::None;
2917
2918 // Construct the decl.
2919 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002920 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002921
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002922 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002923 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002924
2925 if (D.getInvalidType() || InvalidDecl)
2926 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002927
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002928 return NewID;
2929}
2930
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002931void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002932 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002933 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002934 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002935 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002936 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2937 assert(EnclosingDecl && "missing record or interface decl");
2938 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2939
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002940 if (Record)
2941 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2942 // Diagnose code like:
2943 // struct S { struct S {} X; };
2944 // We discover this when we complete the outer S. Reject and ignore the
2945 // outer S.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002946 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002947 << DefRecord->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002948 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002949 Record->setInvalidDecl();
2950 return;
2951 }
2952
Reid Spencer5f016e22007-07-11 17:01:13 +00002953 // Verify that all the fields are okay.
2954 unsigned NumNamedMembers = 0;
2955 llvm::SmallVector<FieldDecl*, 32> RecFields;
2956 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002957
Reid Spencer5f016e22007-07-11 17:01:13 +00002958 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002959
Steve Naroff74216642007-09-14 22:20:54 +00002960 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2961 assert(FD && "missing field decl");
2962
2963 // Remember all fields.
2964 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002965
2966 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002967 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002968
Reid Spencer5f016e22007-07-11 17:01:13 +00002969 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002970 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002971 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002972 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002973 FD->setInvalidDecl();
2974 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002975 continue;
2976 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002977 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2978 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002979 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002980 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002981 FD->setInvalidDecl();
2982 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002983 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002984 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002985 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002986 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002987 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002988 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002989 FD->setInvalidDecl();
2990 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002991 continue;
2992 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002993 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002994 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002995 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002996 FD->setInvalidDecl();
2997 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002998 continue;
2999 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003000 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003001 if (Record)
3002 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003003 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003004 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3005 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003006 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003007 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3008 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003009 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003010 Record->setHasFlexibleArrayMember(true);
3011 } else {
3012 // If this is a struct/class and this is not the last element, reject
3013 // it. Note that GCC supports variable sized arrays in the middle of
3014 // structures.
3015 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003016 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003017 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003018 FD->setInvalidDecl();
3019 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003020 continue;
3021 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003022 // We support flexible arrays at the end of structs in other structs
3023 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003024 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003025 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003026 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003027 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003028 }
3029 }
3030 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003031 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003032 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003033 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003034 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003035 FD->setInvalidDecl();
3036 EnclosingDecl->setInvalidDecl();
3037 continue;
3038 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003039 // Keep track of the number of named members.
3040 if (IdentifierInfo *II = FD->getIdentifier()) {
3041 // Detect duplicate member names.
3042 if (!FieldIDs.insert(II)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00003043 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Reid Spencer5f016e22007-07-11 17:01:13 +00003044 // Find the previous decl.
3045 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00003046 for (unsigned i = 0; ; ++i) {
3047 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00003048 if (RecFields[i]->getIdentifier() == II) {
3049 PrevLoc = RecFields[i]->getLocation();
3050 break;
3051 }
3052 }
Chris Lattner5f4a6822008-11-23 23:12:31 +00003053 Diag(PrevLoc, diag::note_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00003054 FD->setInvalidDecl();
3055 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003056 continue;
3057 }
3058 ++NumNamedMembers;
3059 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003060 }
3061
Reid Spencer5f016e22007-07-11 17:01:13 +00003062 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003063 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003064 Record->completeDefinition(Context);
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00003065 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
3066 // Sema::ActOnFinishCXXClassDef.
3067 if (!isa<CXXRecordDecl>(Record))
3068 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00003069 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003070 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003071 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003072 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003073 // Must enforce the rule that ivars in the base classes may not be
3074 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003075 if (ID->getSuperClass()) {
3076 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3077 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3078 ObjCIvarDecl* Ivar = (*IVI);
3079 IdentifierInfo *II = Ivar->getIdentifier();
3080 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3081 if (prevIvar) {
3082 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3083 Diag(prevIvar->getLocation(), diag::note_previous_definition);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003084 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003085 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003086 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003087 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003088 else if (ObjCImplementationDecl *IMPDecl =
3089 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003090 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3091 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003092 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003093 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003094 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003095
3096 if (Attr)
3097 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003098}
3099
Steve Naroff08d92e42007-09-15 18:49:24 +00003100Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003101 DeclTy *lastEnumConst,
3102 SourceLocation IdLoc, IdentifierInfo *Id,
3103 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003104 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003105 EnumConstantDecl *LastEnumConst =
3106 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3107 Expr *Val = static_cast<Expr*>(val);
3108
Chris Lattner31e05722007-08-26 06:24:45 +00003109 // The scope passed in may not be a decl scope. Zip up the scope tree until
3110 // we find one that is.
3111 while ((S->getFlags() & Scope::DeclScope) == 0)
3112 S = S->getParent();
3113
Reid Spencer5f016e22007-07-11 17:01:13 +00003114 // Verify that there isn't already something declared with this name in this
3115 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003116 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003117 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003118 // Maybe we will complain about the shadowed template parameter.
3119 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3120 // Just pretend that we didn't see the previous declaration.
3121 PrevDecl = 0;
3122 }
3123
3124 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003125 // When in C++, we may get a TagDecl with the same name; in this case the
3126 // enum constant will 'hide' the tag.
3127 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3128 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003129 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003130 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003131 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003132 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003133 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003134 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003135 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003136 return 0;
3137 }
3138 }
3139
3140 llvm::APSInt EnumVal(32);
3141 QualType EltTy;
3142 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003143 // Make sure to promote the operand type to int.
3144 UsualUnaryConversions(Val);
3145
Reid Spencer5f016e22007-07-11 17:01:13 +00003146 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3147 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003148 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003149 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003150 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003151 } else {
3152 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003153 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003154 }
3155
3156 if (!Val) {
3157 if (LastEnumConst) {
3158 // Assign the last value + 1.
3159 EnumVal = LastEnumConst->getInitVal();
3160 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003161
3162 // Check for overflow on increment.
3163 if (EnumVal < LastEnumConst->getInitVal())
3164 Diag(IdLoc, diag::warn_enum_value_overflow);
3165
Chris Lattnerb7416f92007-08-27 17:37:24 +00003166 EltTy = LastEnumConst->getType();
3167 } else {
3168 // First value, set to zero.
3169 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003170 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003171 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003172 }
3173
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003174 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003175 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3176 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003177 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003178
3179 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003180 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003181
3182 // Add this enumerator into the enum itself.
3183 // FIXME: This means that the enumerator is stored in two
3184 // DeclContexts. This is not a long-term solution.
3185 New->setLexicalDeclContext(TheEnumDecl);
3186 TheEnumDecl->addDecl(Context, New, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003187 return New;
3188}
3189
Steve Naroff02408c62008-08-07 14:08:16 +00003190// FIXME: For consistency with ActOnFields(), we should have the parser
3191// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003192void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003193 DeclTy **Elements, unsigned NumElements) {
3194 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00003195
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003196 if (Enum) {
3197 if (EnumDecl *Def = cast_or_null<EnumDecl>(Enum->getDefinition(Context))) {
3198 // Diagnose code like:
3199 // enum e0 {
3200 // E0 = sizeof(enum e0 { E1 })
3201 // };
3202 Diag(Def->getLocation(), diag::err_nested_redefinition)
3203 << Enum->getDeclName();
3204 Diag(Enum->getLocation(), diag::note_previous_definition);
3205 Enum->setInvalidDecl();
3206 return;
3207 }
Steve Naroff02408c62008-08-07 14:08:16 +00003208 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00003209 // TODO: If the result value doesn't fit in an int, it must be a long or long
3210 // long value. ISO C does not support this, but GCC does as an extension,
3211 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003212 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003213
Chris Lattnerac609682007-08-28 06:15:15 +00003214 // Verify that all the values are okay, compute the size of the values, and
3215 // reverse the list.
3216 unsigned NumNegativeBits = 0;
3217 unsigned NumPositiveBits = 0;
3218
3219 // Keep track of whether all elements have type int.
3220 bool AllElementsInt = true;
3221
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003222 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003223 EnumConstantDecl *EltList = 0;
3224 for (unsigned i = 0; i != NumElements; ++i) {
3225 EnumConstantDecl *ECD =
3226 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3227 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003228
3229 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003230 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003231 assert(InitVal.getBitWidth() >= IntWidth &&
3232 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003233 if (InitVal.getBitWidth() > IntWidth) {
3234 llvm::APSInt V(InitVal);
3235 V.trunc(IntWidth);
3236 V.extend(InitVal.getBitWidth());
3237 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003238 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3239 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003240 }
Chris Lattnerac609682007-08-28 06:15:15 +00003241
3242 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003243 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003244 NumPositiveBits = std::max(NumPositiveBits,
3245 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003246 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003247 NumNegativeBits = std::max(NumNegativeBits,
3248 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003249
Chris Lattnerac609682007-08-28 06:15:15 +00003250 // Keep track of whether every enum element has type int (very commmon).
3251 if (AllElementsInt)
3252 AllElementsInt = ECD->getType() == Context.IntTy;
3253
Reid Spencer5f016e22007-07-11 17:01:13 +00003254 ECD->setNextDeclarator(EltList);
3255 EltList = ECD;
3256 }
3257
Chris Lattnerac609682007-08-28 06:15:15 +00003258 // Figure out the type that should be used for this enum.
3259 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3260 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003261 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003262
3263 if (NumNegativeBits) {
3264 // If there is a negative value, figure out the smallest integer type (of
3265 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003266 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003267 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003268 BestWidth = IntWidth;
3269 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003270 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003271
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003272 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003273 BestType = Context.LongTy;
3274 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003275 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003276
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003277 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003278 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3279 BestType = Context.LongLongTy;
3280 }
3281 }
3282 } else {
3283 // If there is no negative value, figure out which of uint, ulong, ulonglong
3284 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003285 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003286 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003287 BestWidth = IntWidth;
3288 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003289 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003290 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003291 } else {
3292 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003293 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003294 "How could an initializer get larger than ULL?");
3295 BestType = Context.UnsignedLongLongTy;
3296 }
3297 }
3298
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003299 // Loop over all of the enumerator constants, changing their types to match
3300 // the type of the enum if needed.
3301 for (unsigned i = 0; i != NumElements; ++i) {
3302 EnumConstantDecl *ECD =
3303 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3304 if (!ECD) continue; // Already issued a diagnostic.
3305
3306 // Standard C says the enumerators have int type, but we allow, as an
3307 // extension, the enumerators to be larger than int size. If each
3308 // enumerator value fits in an int, type it as an int, otherwise type it the
3309 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3310 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003311 if (ECD->getType() == Context.IntTy) {
3312 // Make sure the init value is signed.
3313 llvm::APSInt IV = ECD->getInitVal();
3314 IV.setIsSigned(true);
3315 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003316
3317 if (getLangOptions().CPlusPlus)
3318 // C++ [dcl.enum]p4: Following the closing brace of an
3319 // enum-specifier, each enumerator has the type of its
3320 // enumeration.
3321 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003322 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003323 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003324
3325 // Determine whether the value fits into an int.
3326 llvm::APSInt InitVal = ECD->getInitVal();
3327 bool FitsInInt;
3328 if (InitVal.isUnsigned() || !InitVal.isNegative())
3329 FitsInInt = InitVal.getActiveBits() < IntWidth;
3330 else
3331 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3332
3333 // If it fits into an integer type, force it. Otherwise force it to match
3334 // the enum decl type.
3335 QualType NewTy;
3336 unsigned NewWidth;
3337 bool NewSign;
3338 if (FitsInInt) {
3339 NewTy = Context.IntTy;
3340 NewWidth = IntWidth;
3341 NewSign = true;
3342 } else if (ECD->getType() == BestType) {
3343 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003344 if (getLangOptions().CPlusPlus)
3345 // C++ [dcl.enum]p4: Following the closing brace of an
3346 // enum-specifier, each enumerator has the type of its
3347 // enumeration.
3348 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003349 continue;
3350 } else {
3351 NewTy = BestType;
3352 NewWidth = BestWidth;
3353 NewSign = BestType->isSignedIntegerType();
3354 }
3355
3356 // Adjust the APSInt value.
3357 InitVal.extOrTrunc(NewWidth);
3358 InitVal.setIsSigned(NewSign);
3359 ECD->setInitVal(InitVal);
3360
3361 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003362 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3363 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003364 if (getLangOptions().CPlusPlus)
3365 // C++ [dcl.enum]p4: Following the closing brace of an
3366 // enum-specifier, each enumerator has the type of its
3367 // enumeration.
3368 ECD->setType(EnumType);
3369 else
3370 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003371 }
Chris Lattnerac609682007-08-28 06:15:15 +00003372
Douglas Gregor44b43212008-12-11 16:49:14 +00003373 Enum->completeDefinition(Context, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003374 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003375}
3376
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003377Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003378 ExprArg expr) {
3379 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3380
Chris Lattner8e25d862008-03-16 00:16:02 +00003381 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003382}
3383
Douglas Gregorf44515a2008-12-16 22:23:02 +00003384
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003385void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3386 ExprTy *alignment, SourceLocation PragmaLoc,
3387 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3388 Expr *Alignment = static_cast<Expr *>(alignment);
3389
3390 // If specified then alignment must be a "small" power of two.
3391 unsigned AlignmentVal = 0;
3392 if (Alignment) {
3393 llvm::APSInt Val;
3394 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3395 !Val.isPowerOf2() ||
3396 Val.getZExtValue() > 16) {
3397 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3398 delete Alignment;
3399 return; // Ignore
3400 }
3401
3402 AlignmentVal = (unsigned) Val.getZExtValue();
3403 }
3404
3405 switch (Kind) {
3406 case Action::PPK_Default: // pack([n])
3407 PackContext.setAlignment(AlignmentVal);
3408 break;
3409
3410 case Action::PPK_Show: // pack(show)
3411 // Show the current alignment, making sure to show the right value
3412 // for the default.
3413 AlignmentVal = PackContext.getAlignment();
3414 // FIXME: This should come from the target.
3415 if (AlignmentVal == 0)
3416 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003417 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003418 break;
3419
3420 case Action::PPK_Push: // pack(push [, id] [, [n])
3421 PackContext.push(Name);
3422 // Set the new alignment if specified.
3423 if (Alignment)
3424 PackContext.setAlignment(AlignmentVal);
3425 break;
3426
3427 case Action::PPK_Pop: // pack(pop [, id] [, n])
3428 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3429 // "#pragma pack(pop, identifier, n) is undefined"
3430 if (Alignment && Name)
3431 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3432
3433 // Do the pop.
3434 if (!PackContext.pop(Name)) {
3435 // If a name was specified then failure indicates the name
3436 // wasn't found. Otherwise failure indicates the stack was
3437 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003438 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3439 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003440
3441 // FIXME: Warn about popping named records as MSVC does.
3442 } else {
3443 // Pop succeeded, set the new alignment if specified.
3444 if (Alignment)
3445 PackContext.setAlignment(AlignmentVal);
3446 }
3447 break;
3448
3449 default:
3450 assert(0 && "Invalid #pragma pack kind.");
3451 }
3452}
3453
3454bool PragmaPackStack::pop(IdentifierInfo *Name) {
3455 if (Stack.empty())
3456 return false;
3457
3458 // If name is empty just pop top.
3459 if (!Name) {
3460 Alignment = Stack.back().first;
3461 Stack.pop_back();
3462 return true;
3463 }
3464
3465 // Otherwise, find the named record.
3466 for (unsigned i = Stack.size(); i != 0; ) {
3467 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003468 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003469 // Found it, pop up to and including this record.
3470 Alignment = Stack[i].first;
3471 Stack.erase(Stack.begin() + i, Stack.end());
3472 return true;
3473 }
3474 }
3475
3476 return false;
3477}