blob: 1f6cbc4f32ccfb06b6cea74346691d2852485d81 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregore267ff32008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Douglas Gregore267ff32008-12-11 20:41:00 +000031
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
Douglas Gregor2def4832008-11-17 20:34:05 +000034Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000035 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000036 DeclContext *DC = 0;
37 if (SS) {
38 if (SS->isInvalid())
39 return 0;
40 DC = static_cast<DeclContext*>(SS->getScopeRep());
41 }
42 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroffb327ce02008-04-02 14:35:35 +000043
Douglas Gregor2ce52f32008-04-13 21:07:44 +000044 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
45 isa<ObjCInterfaceDecl>(IIDecl) ||
Douglas Gregor72c3f312008-12-05 18:15:24 +000046 isa<TagDecl>(IIDecl) ||
47 isa<TemplateTypeParmDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000048 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000049 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000050}
51
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000052DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000053 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000054 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000055 if (MD->isOutOfLineDefinition())
56 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000057
58 // A C++ inline method is parsed *after* the topmost class it was declared in
59 // is fully parsed (it's "complete").
60 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000061 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000062 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
63 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000064 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000065 DC = RD;
66
67 // Return the declaration context of the topmost class the inline method is
68 // declared in.
69 return DC;
70 }
71
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000072 if (isa<ObjCMethodDecl>(DC))
73 return Context.getTranslationUnitDecl();
74
75 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
76 return SD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000077
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000078 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000079}
80
Douglas Gregor44b43212008-12-11 16:49:14 +000081void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000082 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +000083 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000084 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +000085 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +000086}
87
Chris Lattnerb048c982008-04-06 04:47:34 +000088void Sema::PopDeclContext() {
89 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +000090
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000091 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000092}
93
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000094/// Add this decl to the scope shadowed decl chains.
95void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000096 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000097
Douglas Gregor6ed40e32008-12-23 21:05:05 +000098 // Add scoped declarations into their context, so that they can be
99 // found later. Declarations without a context won't be inserted
100 // into any context.
101 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
102 CurContext->addDecl(Context, SD);
103
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000104 // C++ [basic.scope]p4:
105 // -- exactly one declaration shall declare a class name or
106 // enumeration name that is not a typedef name and the other
107 // declarations shall all refer to the same object or
108 // enumerator, or all refer to functions and function templates;
109 // in this case the class name or enumeration name is hidden.
110 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
111 // We are pushing the name of a tag (enum or class).
Douglas Gregor44b43212008-12-11 16:49:14 +0000112 if (CurContext == TD->getDeclContext()) {
113 // We're pushing the tag into the current context, which might
114 // require some reshuffling in the identifier resolver.
115 IdentifierResolver::iterator
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000116 I = IdResolver.begin(TD->getDeclName(), CurContext,
117 false/*LookInParentCtx*/),
118 IEnd = IdResolver.end();
119 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
120 NamedDecl *PrevDecl = *I;
121 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
122 PrevDecl = *I, ++I) {
123 if (TD->declarationReplaces(*I)) {
124 // This is a redeclaration. Remove it from the chain and
125 // break out, so that we'll add in the shadowed
126 // declaration.
127 S->RemoveDecl(*I);
128 if (PrevDecl == *I) {
129 IdResolver.RemoveDecl(*I);
130 IdResolver.AddDecl(TD);
131 return;
132 } else {
133 IdResolver.RemoveDecl(*I);
134 break;
135 }
136 }
137 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000138
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000139 // There is already a declaration with the same name in the same
140 // scope, which is not a tag declaration. It must be found
141 // before we find the new declaration, so insert the new
142 // declaration at the end of the chain.
143 IdResolver.AddShadowedDecl(TD, PrevDecl);
144
145 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000146 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000147 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000148 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000149 // We are pushing the name of a function, which might be an
150 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000151 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000152 IdentifierResolver::iterator Redecl
153 = std::find_if(IdResolver.begin(FD->getDeclName(), CurContext,
154 false/*LookInParentCtx*/),
155 IdResolver.end(),
156 std::bind1st(std::mem_fun(&ScopedDecl::declarationReplaces),
157 FD));
158 if (Redecl != IdResolver.end()) {
159 // There is already a declaration of a function on our
160 // IdResolver chain. Replace it with this declaration.
161 S->RemoveDecl(*Redecl);
162 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000163 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000164 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000165
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000166 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000167}
168
Steve Naroffb216c882007-10-09 22:01:59 +0000169void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000170 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000171 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
172 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000173
Reid Spencer5f016e22007-07-11 17:01:13 +0000174 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
175 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000176 Decl *TmpD = static_cast<Decl*>(*I);
177 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000178
Douglas Gregor44b43212008-12-11 16:49:14 +0000179 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
180 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000181
Douglas Gregor44b43212008-12-11 16:49:14 +0000182 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000183
Douglas Gregor44b43212008-12-11 16:49:14 +0000184 // Remove this name from our lexical scope.
185 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 }
187}
188
Steve Naroffe8043c32008-04-01 23:04:06 +0000189/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
190/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000191ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000192 // The third "scope" argument is 0 since we aren't enabling lazy built-in
193 // creation from this context.
194 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000195
Steve Naroffb327ce02008-04-02 14:35:35 +0000196 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000197}
198
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000199/// MaybeConstructOverloadSet - Name lookup has determined that the
200/// elements in [I, IEnd) have the name that we are looking for, and
201/// *I is a match for the namespace. This routine returns an
202/// appropriate Decl for name lookup, which may either be *I or an
203/// OverloadeFunctionDecl that represents the overloaded functions in
204/// [I, IEnd).
205///
206/// The existance of this routine is temporary; LookupDecl should
207/// probably be able to return multiple results, to deal with cases of
208/// ambiguity and overloaded functions without needing to create a
209/// Decl node.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000210template<typename DeclIterator>
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000211static Decl *
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000212MaybeConstructOverloadSet(ASTContext &Context,
213 DeclIterator I, DeclIterator IEnd) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000214 assert(I != IEnd && "Iterator range cannot be empty");
215 assert(!isa<OverloadedFunctionDecl>(*I) &&
216 "Cannot have an overloaded function");
217
218 if (isa<FunctionDecl>(*I)) {
219 // If we found a function, there might be more functions. If
220 // so, collect them into an overload set.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000221 DeclIterator Last = I;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000222 OverloadedFunctionDecl *Ovl = 0;
223 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
224 if (!Ovl) {
225 // FIXME: We leak this overload set. Eventually, we want to
226 // stop building the declarations for these overload sets, so
227 // there will be nothing to leak.
228 Ovl = OverloadedFunctionDecl::Create(Context,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000229 cast<ScopedDecl>(*I)->getDeclContext(),
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000230 (*I)->getDeclName());
231 Ovl->addOverload(cast<FunctionDecl>(*I));
232 }
233 Ovl->addOverload(cast<FunctionDecl>(*Last));
234 }
235
236 // If we had more than one function, we built an overload
237 // set. Return it.
238 if (Ovl)
239 return Ovl;
240 }
241
242 return *I;
243}
244
Steve Naroffe8043c32008-04-01 23:04:06 +0000245/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000246/// namespace.
Douglas Gregor2def4832008-11-17 20:34:05 +0000247Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000248 const DeclContext *LookupCtx,
Douglas Gregor44b43212008-12-11 16:49:14 +0000249 bool enableLazyBuiltinCreation,
Douglas Gregor0a59acb2008-12-16 00:38:16 +0000250 bool LookInParent) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000251 if (!Name) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000252 unsigned NS = NSI;
253 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
254 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000255
Douglas Gregore267ff32008-12-11 20:41:00 +0000256 if (LookupCtx == 0 &&
257 (!getLangOptions().CPlusPlus || (NS == Decl::IDNS_Label))) {
258 // Unqualified name lookup in C/Objective-C and name lookup for
259 // labels in C++ is purely lexical, so search in the
260 // declarations attached to the name.
261 assert(!LookupCtx && "Can't perform qualified name lookup here");
262 IdentifierResolver::iterator I
263 = IdResolver.begin(Name, CurContext, LookInParent);
264
265 // Scan up the scope chain looking for a decl that matches this
266 // identifier that is in the appropriate namespace. This search
267 // should not take long, as shadowing of names is uncommon, and
268 // deep shadowing is extremely uncommon.
269 for (; I != IdResolver.end(); ++I)
270 if ((*I)->getIdentifierNamespace() & NS)
271 return *I;
272 } else if (LookupCtx) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000273 // Perform qualified name lookup into the LookupCtx.
274 // FIXME: Will need to look into base classes and such.
Douglas Gregore267ff32008-12-11 20:41:00 +0000275 DeclContext::lookup_const_iterator I, E;
276 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
277 if ((*I)->getIdentifierNamespace() & NS)
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000278 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregore267ff32008-12-11 20:41:00 +0000279 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000280 // Name lookup for ordinary names and tag names in C++ requires
281 // looking into scopes that aren't strictly lexical, and
282 // therefore we walk through the context as well as walking
283 // through the scopes.
284 IdentifierResolver::iterator
285 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
286 IEnd = IdResolver.end();
287 for (; S; S = S->getParent()) {
288 // Check whether the IdResolver has anything in this scope.
289 // FIXME: The isDeclScope check could be expensive. Can we do better?
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000290 for (; I != IEnd && S->isDeclScope(*I); ++I) {
291 if ((*I)->getIdentifierNamespace() & NS) {
292 // We found something. Look for anything else in our scope
293 // with this same name and in an acceptable identifier
294 // namespace, so that we can construct an overload set if we
295 // need to.
296 IdentifierResolver::iterator LastI = I;
297 for (++LastI; LastI != IEnd; ++LastI) {
298 if (((*LastI)->getIdentifierNamespace() & NS) == 0 ||
299 !S->isDeclScope(*LastI))
300 break;
301 }
302 return MaybeConstructOverloadSet(Context, I, LastI);
303 }
304 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000305
306 // If there is an entity associated with this scope, it's a
307 // DeclContext. We might need to perform qualified lookup into
308 // it.
309 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
310 while (Ctx && Ctx->isFunctionOrMethod())
311 Ctx = Ctx->getParent();
312 while (Ctx && (Ctx->isNamespace() || Ctx->isCXXRecord())) {
313 // Look for declarations of this name in this scope.
Douglas Gregore267ff32008-12-11 20:41:00 +0000314 DeclContext::lookup_const_iterator I, E;
315 for (llvm::tie(I, E) = Ctx->lookup(Context, Name); I != E; ++I) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000316 // FIXME: Cache this result in the IdResolver
Douglas Gregore267ff32008-12-11 20:41:00 +0000317 if ((*I)->getIdentifierNamespace() & NS)
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000318 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregor44b43212008-12-11 16:49:14 +0000319 }
320
321 Ctx = Ctx->getParent();
322 }
323
324 if (!LookInParent)
325 return 0;
326 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000327 }
Chris Lattner7f925cc2008-04-11 07:00:53 +0000328
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 // If we didn't find a use of this identifier, and if the identifier
330 // corresponds to a compiler builtin, create the decl object for the builtin
331 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000332 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000333 IdentifierInfo *II = Name.getAsIdentifierInfo();
334 if (enableLazyBuiltinCreation && II &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000335 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000336 // If this is a builtin on this (or all) targets, create the decl.
337 if (unsigned BuiltinID = II->getBuiltinID())
338 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
339 }
Douglas Gregor2def4832008-11-17 20:34:05 +0000340 if (getLangOptions().ObjC1 && II) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000341 // @interface and @compatibility_alias introduce typedef-like names.
342 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000343 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000344 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000345 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
346 if (IDI != ObjCInterfaceDecls.end())
347 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000348 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
349 if (I != ObjCAliasDecls.end())
350 return I->second->getClassInterface();
351 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 }
353 return 0;
354}
355
Chris Lattner95e2c712008-05-05 22:18:14 +0000356void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000357 if (!Context.getBuiltinVaListType().isNull())
358 return;
359
360 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000361 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000362 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000363 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
364}
365
Reid Spencer5f016e22007-07-11 17:01:13 +0000366/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
367/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000368ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
369 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 Builtin::ID BID = (Builtin::ID)bid;
371
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000372 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000373 InitBuiltinVaListType();
374
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000375 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000376 FunctionDecl *New = FunctionDecl::Create(Context,
377 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000378 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000379 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000380
Chris Lattner95e2c712008-05-05 22:18:14 +0000381 // Create Decl objects for each parameter, adding them to the
382 // FunctionDecl.
383 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
384 llvm::SmallVector<ParmVarDecl*, 16> Params;
385 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
386 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
387 FT->getArgType(i), VarDecl::None, 0,
388 0));
389 New->setParams(&Params[0], Params.size());
390 }
391
392
393
Chris Lattner7f925cc2008-04-11 07:00:53 +0000394 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000395 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 return New;
397}
398
Sebastian Redlc42e1182008-11-11 11:37:55 +0000399/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
400/// everything from the standard library is defined.
401NamespaceDecl *Sema::GetStdNamespace() {
402 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000403 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000404 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattner8edea832008-11-20 05:45:14 +0000405 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000406 0, Global, /*enableLazyBuiltinCreation=*/false);
407 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
408 }
409 return StdNamespace;
410}
411
Reid Spencer5f016e22007-07-11 17:01:13 +0000412/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
413/// and scope as a previous declaration 'Old'. Figure out how to resolve this
414/// situation, merging decls or emitting diagnostics as appropriate.
415///
Steve Naroffe8043c32008-04-01 23:04:06 +0000416TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000417 // Allow multiple definitions for ObjC built-in typedefs.
418 // FIXME: Verify the underlying types are equivalent!
419 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000420 const IdentifierInfo *TypeID = New->getIdentifier();
421 switch (TypeID->getLength()) {
422 default: break;
423 case 2:
424 if (!TypeID->isStr("id"))
425 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000426 Context.setObjCIdType(New);
427 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000428 case 5:
429 if (!TypeID->isStr("Class"))
430 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000431 Context.setObjCClassType(New);
432 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000433 case 3:
434 if (!TypeID->isStr("SEL"))
435 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000436 Context.setObjCSelType(New);
437 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000438 case 8:
439 if (!TypeID->isStr("Protocol"))
440 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000441 Context.setObjCProtoType(New->getUnderlyingType());
442 return New;
443 }
444 // Fall through - the typedef name was not a builtin type.
445 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000446 // Verify the old decl was also a typedef.
447 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
448 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000449 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000450 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000451 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000452 return New;
453 }
454
Chris Lattner99cb9972008-07-25 18:44:27 +0000455 // If the typedef types are not identical, reject them in all languages and
456 // with any extensions enabled.
457 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
458 Context.getCanonicalType(Old->getUnderlyingType()) !=
459 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000460 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000461 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000462 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner99cb9972008-07-25 18:44:27 +0000463 return Old;
464 }
465
Eli Friedman54ecfce2008-06-11 06:20:39 +0000466 if (getLangOptions().Microsoft) return New;
467
Douglas Gregorbbe27432008-11-21 16:29:06 +0000468 // C++ [dcl.typedef]p2:
469 // In a given non-class scope, a typedef specifier can be used to
470 // redefine the name of any type declared in that scope to refer
471 // to the type to which it already refers.
472 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
473 return New;
474
475 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000476 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
477 // *either* declaration is in a system header. The code below implements
478 // this adhoc compatibility rule. FIXME: The following code will not
479 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000480 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
481 SourceManager &SrcMgr = Context.getSourceManager();
482 if (SrcMgr.isInSystemHeader(Old->getLocation()))
483 return New;
484 if (SrcMgr.isInSystemHeader(New->getLocation()))
485 return New;
486 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000487
Chris Lattner08631c52008-11-23 21:45:46 +0000488 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000489 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 return New;
491}
492
Chris Lattner6b6b5372008-06-26 18:38:35 +0000493/// DeclhasAttr - returns true if decl Declaration already has the target
494/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000495static bool DeclHasAttr(const Decl *decl, const Attr *target) {
496 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
497 if (attr->getKind() == target->getKind())
498 return true;
499
500 return false;
501}
502
503/// MergeAttributes - append attributes from the Old decl to the New one.
504static void MergeAttributes(Decl *New, Decl *Old) {
505 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
506
Chris Lattnerddee4232008-03-03 03:28:21 +0000507 while (attr) {
508 tmp = attr;
509 attr = attr->getNext();
510
511 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000512 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000513 New->addAttr(tmp);
514 } else {
515 tmp->setNext(0);
516 delete(tmp);
517 }
518 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000519
520 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000521}
522
Chris Lattner04421082008-04-08 04:40:51 +0000523/// MergeFunctionDecl - We just parsed a function 'New' from
524/// declarator D which has the same name and scope as a previous
525/// declaration 'Old'. Figure out how to resolve this situation,
526/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000527/// Redeclaration will be set true if this New is a redeclaration OldD.
528///
529/// In C++, New and Old must be declarations that are not
530/// overloaded. Use IsOverload to determine whether New and Old are
531/// overloaded, and to select the Old declaration that New should be
532/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000533FunctionDecl *
534Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000535 assert(!isa<OverloadedFunctionDecl>(OldD) &&
536 "Cannot merge with an overloaded function declaration");
537
Douglas Gregorf0097952008-04-21 02:02:58 +0000538 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 // Verify the old decl was also a function.
540 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
541 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000542 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000543 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000544 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 return New;
546 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000547
548 // Determine whether the previous declaration was a definition,
549 // implicit declaration, or a declaration.
550 diag::kind PrevDiag;
551 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000552 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000553 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000554 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000555 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000556 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000557
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000558 QualType OldQType = Context.getCanonicalType(Old->getType());
559 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000560
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000561 if (getLangOptions().CPlusPlus) {
562 // (C++98 13.1p2):
563 // Certain function declarations cannot be overloaded:
564 // -- Function declarations that differ only in the return type
565 // cannot be overloaded.
566 QualType OldReturnType
567 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
568 QualType NewReturnType
569 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
570 if (OldReturnType != NewReturnType) {
571 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
572 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000573 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000574 return New;
575 }
576
577 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
578 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
579 if (OldMethod && NewMethod) {
580 // -- Member function declarations with the same name and the
581 // same parameter types cannot be overloaded if any of them
582 // is a static member function declaration.
583 if (OldMethod->isStatic() || NewMethod->isStatic()) {
584 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
585 Diag(Old->getLocation(), PrevDiag);
586 return New;
587 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000588
589 // C++ [class.mem]p1:
590 // [...] A member shall not be declared twice in the
591 // member-specification, except that a nested class or member
592 // class template can be declared and then later defined.
593 if (OldMethod->getLexicalDeclContext() ==
594 NewMethod->getLexicalDeclContext()) {
595 unsigned NewDiag;
596 if (isa<CXXConstructorDecl>(OldMethod))
597 NewDiag = diag::err_constructor_redeclared;
598 else if (isa<CXXDestructorDecl>(NewMethod))
599 NewDiag = diag::err_destructor_redeclared;
600 else if (isa<CXXConversionDecl>(NewMethod))
601 NewDiag = diag::err_conv_function_redeclared;
602 else
603 NewDiag = diag::err_member_redeclared;
604
605 Diag(New->getLocation(), NewDiag);
606 Diag(Old->getLocation(), PrevDiag);
607 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000608 }
609
610 // (C++98 8.3.5p3):
611 // All declarations for a function shall agree exactly in both the
612 // return type and the parameter-type-list.
613 if (OldQType == NewQType) {
614 // We have a redeclaration.
615 MergeAttributes(New, Old);
616 Redeclaration = true;
617 return MergeCXXFunctionDecl(New, Old);
618 }
619
620 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000621 }
Chris Lattner04421082008-04-08 04:40:51 +0000622
623 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000624 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000625 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000626 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000627 MergeAttributes(New, Old);
628 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000629 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000630 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000631
Steve Naroff837618c2008-01-16 15:01:34 +0000632 // A function that has already been declared has been redeclared or defined
633 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000634
Reid Spencer5f016e22007-07-11 17:01:13 +0000635 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
636 // TODO: This is totally simplistic. It should handle merging functions
637 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000638 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000639 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 return New;
641}
642
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000643/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000644static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000645 if (VD->isFileVarDecl())
646 return (!VD->getInit() &&
647 (VD->getStorageClass() == VarDecl::None ||
648 VD->getStorageClass() == VarDecl::Static));
649 return false;
650}
651
652/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
653/// when dealing with C "tentative" external object definitions (C99 6.9.2).
654void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
655 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000656 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000657
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000658 // FIXME: I don't this will actually see all of the
659 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000660 for (IdentifierResolver::iterator
661 I = IdResolver.begin(VD->getIdentifier(),
662 VD->getDeclContext(), false/*LookInParentCtx*/),
663 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000664 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000665 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
666
Steve Narofff855e6f2008-08-10 15:20:13 +0000667 // Handle the following case:
668 // int a[10];
669 // int a[]; - the code below makes sure we set the correct type.
670 // int a[11]; - this is an error, size isn't 10.
671 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
672 OldDecl->getType()->isConstantArrayType())
673 VD->setType(OldDecl->getType());
674
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000675 // Check for "tentative" definitions. We can't accomplish this in
676 // MergeVarDecl since the initializer hasn't been attached.
677 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
678 continue;
679
680 // Handle __private_extern__ just like extern.
681 if (OldDecl->getStorageClass() != VarDecl::Extern &&
682 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
683 VD->getStorageClass() != VarDecl::Extern &&
684 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000685 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000686 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000687 }
688 }
689 }
690}
691
Reid Spencer5f016e22007-07-11 17:01:13 +0000692/// MergeVarDecl - We just parsed a variable 'New' which has the same name
693/// and scope as a previous declaration 'Old'. Figure out how to resolve this
694/// situation, merging decls or emitting diagnostics as appropriate.
695///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000696/// Tentative definition rules (C99 6.9.2p2) are checked by
697/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
698/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000699///
Steve Naroffe8043c32008-04-01 23:04:06 +0000700VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 // Verify the old decl was also a variable.
702 VarDecl *Old = dyn_cast<VarDecl>(OldD);
703 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000704 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000705 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000706 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 return New;
708 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000709
710 MergeAttributes(New, Old);
711
Reid Spencer5f016e22007-07-11 17:01:13 +0000712 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000713 QualType OldCType = Context.getCanonicalType(Old->getType());
714 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000715 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner08631c52008-11-23 21:45:46 +0000716 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000717 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000718 return New;
719 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000720 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
721 if (New->getStorageClass() == VarDecl::Static &&
722 (Old->getStorageClass() == VarDecl::None ||
723 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000724 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000725 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000726 return New;
727 }
728 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
729 if (New->getStorageClass() != VarDecl::Static &&
730 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000731 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000732 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000733 return New;
734 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000735 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
736 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000737 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000738 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000739 }
740 return New;
741}
742
Chris Lattner04421082008-04-08 04:40:51 +0000743/// CheckParmsForFunctionDef - Check that the parameters of the given
744/// function are appropriate for the definition of a function. This
745/// takes care of any checks that cannot be performed on the
746/// declaration itself, e.g., that the types of each of the function
747/// parameters are complete.
748bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
749 bool HasInvalidParm = false;
750 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
751 ParmVarDecl *Param = FD->getParamDecl(p);
752
753 // C99 6.7.5.3p4: the parameters in a parameter type list in a
754 // function declarator that is part of a function definition of
755 // that function shall not have incomplete type.
756 if (Param->getType()->isIncompleteType() &&
757 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000758 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000759 << Param->getType();
Chris Lattner04421082008-04-08 04:40:51 +0000760 Param->setInvalidDecl();
761 HasInvalidParm = true;
762 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000763
764 // C99 6.9.1p5: If the declarator includes a parameter type list, the
765 // declaration of each parameter shall include an identifier.
766 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
767 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000768 }
769
770 return HasInvalidParm;
771}
772
Reid Spencer5f016e22007-07-11 17:01:13 +0000773/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
774/// no declarator (e.g. "struct foo;") is parsed.
775Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
776 // TODO: emit error on 'int;' or 'const enum foo;'.
777 // TODO: emit error on 'typedef int;'
778 // if (!DS.isMissingDeclaratorOk()) Diag(...);
779
Steve Naroff92199282007-11-17 21:37:36 +0000780 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000781}
782
Steve Naroffd0091aa2008-01-10 22:15:12 +0000783bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000784 // Get the type before calling CheckSingleAssignmentConstraints(), since
785 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000786 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +0000787
788 if (getLangOptions().CPlusPlus)
789 return PerformCopyInitialization(Init, DeclType, "initializing");
790
Chris Lattner5cf216b2008-01-04 18:04:52 +0000791 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
792 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
793 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000794}
795
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000796bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000797 const ArrayType *AT = Context.getAsArrayType(DeclT);
798
799 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000800 // C99 6.7.8p14. We have an array of character type with unknown size
801 // being initialized to a string literal.
802 llvm::APSInt ConstVal(32);
803 ConstVal = strLiteral->getByteLength() + 1;
804 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000805 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000806 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000807 } else {
808 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000809 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000810 // FIXME: Avoid truncation for 64-bit length strings.
811 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000812 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000813 diag::warn_initializer_string_for_char_array_too_long)
814 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000815 }
816 // Set type from "char *" to "constant array of char".
817 strLiteral->setType(DeclT);
818 // For now, we always return false (meaning success).
819 return false;
820}
821
822StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000823 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000824 if (AT && AT->getElementType()->isCharType()) {
825 return dyn_cast<StringLiteral>(Init);
826 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000827 return 0;
828}
829
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000830bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
831 SourceLocation InitLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000832 DeclarationName InitEntity) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +0000833 if (DeclType->isDependentType() || Init->isTypeDependent())
834 return false;
835
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000836 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +0000837 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000838 // (8.3.2), shall be initialized by an object, or function, of
839 // type T or by an object that can be converted into a T.
840 if (DeclType->isReferenceType())
841 return CheckReferenceInit(Init, DeclType);
842
Steve Naroffca107302008-01-21 23:53:58 +0000843 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
844 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000845 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000846 return Diag(InitLoc, diag::err_variable_object_no_init)
847 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +0000848
Steve Naroff2fdc3742007-12-10 22:44:33 +0000849 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
850 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000851 // FIXME: Handle wide strings
852 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
853 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000854
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000855 // C++ [dcl.init]p14:
856 // -- If the destination type is a (possibly cv-qualified) class
857 // type:
858 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
859 QualType DeclTypeC = Context.getCanonicalType(DeclType);
860 QualType InitTypeC = Context.getCanonicalType(Init->getType());
861
862 // -- If the initialization is direct-initialization, or if it is
863 // copy-initialization where the cv-unqualified version of the
864 // source type is the same class as, or a derived class of, the
865 // class of the destination, constructors are considered.
866 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
867 IsDerivedFrom(InitTypeC, DeclTypeC)) {
868 CXXConstructorDecl *Constructor
869 = PerformInitializationByConstructor(DeclType, &Init, 1,
870 InitLoc, Init->getSourceRange(),
871 InitEntity, IK_Copy);
872 return Constructor == 0;
873 }
874
875 // -- Otherwise (i.e., for the remaining copy-initialization
876 // cases), user-defined conversion sequences that can
877 // convert from the source type to the destination type or
878 // (when a conversion function is used) to a derived class
879 // thereof are enumerated as described in 13.3.1.4, and the
880 // best one is chosen through overload resolution
881 // (13.3). If the conversion cannot be done or is
882 // ambiguous, the initialization is ill-formed. The
883 // function selected is called with the initializer
884 // expression as its argument; if the function is a
885 // constructor, the call initializes a temporary of the
886 // destination type.
887 // FIXME: We're pretending to do copy elision here; return to
888 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +0000889 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000890 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000891
Douglas Gregor61366e92008-12-24 00:01:03 +0000892 if (InitEntity)
893 return Diag(InitLoc, diag::err_cannot_initialize_decl)
894 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
895 << Init->getType() << Init->getSourceRange();
896 else
897 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
898 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
899 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000900 }
901
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000902 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000903 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000904 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
905 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +0000906
Steve Naroffd0091aa2008-01-10 22:15:12 +0000907 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000908 } else if (getLangOptions().CPlusPlus) {
909 // C++ [dcl.init]p14:
910 // [...] If the class is an aggregate (8.5.1), and the initializer
911 // is a brace-enclosed list, see 8.5.1.
912 //
913 // Note: 8.5.1 is handled below; here, we diagnose the case where
914 // we have an initializer list and a destination type that is not
915 // an aggregate.
916 // FIXME: In C++0x, this is yet another form of initialization.
917 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
918 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
919 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000920 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +0000921 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +0000922 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000923 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000924
Steve Naroff0cca7492008-05-01 22:18:59 +0000925 InitListChecker CheckInitList(this, InitList, DeclType);
926 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000927}
928
Douglas Gregor10bd3682008-11-17 22:58:34 +0000929/// GetNameForDeclarator - Determine the full declaration name for the
930/// given Declarator.
931DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
932 switch (D.getKind()) {
933 case Declarator::DK_Abstract:
934 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
935 return DeclarationName();
936
937 case Declarator::DK_Normal:
938 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
939 return DeclarationName(D.getIdentifier());
940
941 case Declarator::DK_Constructor: {
942 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
943 Ty = Context.getCanonicalType(Ty);
944 return Context.DeclarationNames.getCXXConstructorName(Ty);
945 }
946
947 case Declarator::DK_Destructor: {
948 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
949 Ty = Context.getCanonicalType(Ty);
950 return Context.DeclarationNames.getCXXDestructorName(Ty);
951 }
952
953 case Declarator::DK_Conversion: {
954 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
955 Ty = Context.getCanonicalType(Ty);
956 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
957 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000958
959 case Declarator::DK_Operator:
960 assert(D.getIdentifier() == 0 && "operator names have no identifier");
961 return Context.DeclarationNames.getCXXOperatorName(
962 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000963 }
964
965 assert(false && "Unknown name kind");
966 return DeclarationName();
967}
968
Douglas Gregor584049d2008-12-15 23:53:10 +0000969/// isNearlyMatchingMemberFunction - Determine whether the C++ member
970/// functions Declaration and Definition are "nearly" matching. This
971/// heuristic is used to improve diagnostics in the case where an
972/// out-of-line member function definition doesn't match any
973/// declaration within the class.
974static bool isNearlyMatchingMemberFunction(ASTContext &Context,
975 FunctionDecl *Declaration,
976 FunctionDecl *Definition) {
977 if (Declaration->param_size() != Definition->param_size())
978 return false;
979 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
980 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
981 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
982
983 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
984 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
985 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
986 return false;
987 }
988
989 return true;
990}
991
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000992Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +0000993Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
994 bool IsFunctionDefinition) {
Steve Naroff94745042007-09-13 23:52:58 +0000995 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +0000996 DeclarationName Name = GetNameForDeclarator(D);
997
Chris Lattnere80a59c2007-07-25 00:24:17 +0000998 // All of these full declarators require an identifier. If it doesn't have
999 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001000 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001001 if (!D.getInvalidType()) // Reject this if we think it is valid.
1002 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001003 diag::err_declarator_need_ident)
1004 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001005 return 0;
1006 }
1007
Chris Lattner31e05722007-08-26 06:24:45 +00001008 // The scope passed in may not be a decl scope. Zip up the scope tree until
1009 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001010 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1011 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001012 S = S->getParent();
1013
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001014 DeclContext *DC;
1015 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +00001016 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001017 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001018
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001019 // See if this is a redefinition of a variable in the same scope.
1020 if (!D.getCXXScopeSpec().isSet()) {
1021 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +00001022 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001023 } else { // Something like "int foo::x;"
1024 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001025 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001026
1027 // C++ 7.3.1.2p2:
1028 // Members (including explicit specializations of templates) of a named
1029 // namespace can also be defined outside that namespace by explicit
1030 // qualification of the name being defined, provided that the entity being
1031 // defined was already declared in the namespace and the definition appears
1032 // after the point of declaration in a namespace that encloses the
1033 // declarations namespace.
1034 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001035 // Note that we only check the context at this point. We don't yet
1036 // have enough information to make sure that PrevDecl is actually
1037 // the declaration we want to match. For example, given:
1038 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001039 // class X {
1040 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001041 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001042 // };
1043 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001044 // void X::f(int) { } // ill-formed
1045 //
1046 // In this case, PrevDecl will point to the overload set
1047 // containing the two f's declared in X, but neither of them
1048 // matches.
1049 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001050 // The qualifying scope doesn't enclose the original declaration.
1051 // Emit diagnostic based on current scope.
1052 SourceLocation L = D.getIdentifierLoc();
1053 SourceRange R = D.getCXXScopeSpec().getRange();
1054 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001055 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001056 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001057 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001058 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001059 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001060 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001061 }
1062 }
1063
Douglas Gregorf57172b2008-12-08 18:40:42 +00001064 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001065 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001066 InvalidDecl = InvalidDecl
1067 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001068 // Just pretend that we didn't see the previous declaration.
1069 PrevDecl = 0;
1070 }
1071
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001072 // In C++, the previous declaration we find might be a tag type
1073 // (class or enum). In this case, the new declaration will hide the
1074 // tag type.
1075 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1076 PrevDecl = 0;
1077
Chris Lattner41af0932007-11-14 06:34:38 +00001078 QualType R = GetTypeForDeclarator(D, S);
1079 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1080
Reid Spencer5f016e22007-07-11 17:01:13 +00001081 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001082 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1083 if (D.getCXXScopeSpec().isSet()) {
1084 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1085 << D.getCXXScopeSpec().getRange();
1086 InvalidDecl = true;
1087 // Pretend we didn't see the scope specifier.
1088 DC = 0;
1089 }
1090
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001091 // Check that there are no default arguments (C++ only).
1092 if (getLangOptions().CPlusPlus)
1093 CheckExtraCXXDefaultArguments(D);
1094
Chris Lattner41af0932007-11-14 06:34:38 +00001095 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +00001096 if (!NewTD) return 0;
1097
1098 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001099 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +00001100 // Merge the decl with the existing one if appropriate. If the decl is
1101 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001102 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001103 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1104 if (NewTD == 0) return 0;
1105 }
1106 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001107 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001108 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1109 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +00001110 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001111 if (NewTD->getUnderlyingType()->isVariableArrayType())
1112 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1113 else
1114 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1115
Steve Naroffd7444aa2007-08-31 17:20:07 +00001116 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 }
1118 }
Chris Lattner41af0932007-11-14 06:34:38 +00001119 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +00001120 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +00001121 switch (D.getDeclSpec().getStorageClassSpec()) {
1122 default: assert(0 && "Unknown storage class!");
1123 case DeclSpec::SCS_auto:
1124 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +00001125 case DeclSpec::SCS_mutable:
Chris Lattnerd1625842008-11-24 06:25:27 +00001126 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroff5912a352007-08-28 20:14:24 +00001127 InvalidDecl = true;
1128 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1130 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1131 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +00001132 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001133 }
1134
Chris Lattnera98e58d2008-03-15 21:24:04 +00001135 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001136 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +00001137 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1138
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001139 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001140 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +00001141 // This is a C++ constructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001142 assert(DC->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +00001143 "Constructors can only be declared in a member context");
1144
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001145 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001146
1147 // Create the new declaration
1148 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001149 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001150 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +00001151 isExplicit, isInline,
1152 /*isImplicitlyDeclared=*/false);
1153
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001154 if (InvalidDecl)
Douglas Gregor42a552f2008-11-05 20:51:48 +00001155 NewFD->setInvalidDecl();
1156 } else if (D.getKind() == Declarator::DK_Destructor) {
1157 // This is a C++ destructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001158 if (DC->isCXXRecord()) {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001159 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001160
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001161 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001162 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001163 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001164 isInline,
1165 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001166
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001167 if (InvalidDecl)
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001168 NewFD->setInvalidDecl();
1169 } else {
1170 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001171
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001172 // Create a FunctionDecl to satisfy the function definition parsing
1173 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001174 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001175 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001176 // FIXME: Move to DeclGroup...
1177 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001178 InvalidDecl = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001179 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001180 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001181 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001182 if (!DC->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001183 Diag(D.getIdentifierLoc(),
1184 diag::err_conv_function_not_member);
1185 return 0;
1186 } else {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001187 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001188
Douglas Gregor70316a02008-12-26 15:00:45 +00001189 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001190 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001191 isInline, isExplicit);
1192
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001193 if (InvalidDecl)
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001194 NewFD->setInvalidDecl();
1195 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001196 } else if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001197 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001198 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001199 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001200 (SC == FunctionDecl::Static), isInline,
1201 LastDeclarator);
1202 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001203 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001204 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001205 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001206 // FIXME: Move to DeclGroup...
1207 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001208 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001209
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001210 // Set the lexical context. If the declarator has a C++
1211 // scope specifier, the lexical context will be different
1212 // from the semantic context.
1213 NewFD->setLexicalDeclContext(CurContext);
1214
Daniel Dunbara80f8742008-08-05 01:35:17 +00001215 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +00001216 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +00001217 // The parser guarantees this is a string.
1218 StringLiteral *SE = cast<StringLiteral>(E);
1219 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1220 SE->getByteLength())));
1221 }
1222
Chris Lattner04421082008-04-08 04:40:51 +00001223 // Copy the parameter declarations from the declarator D to
1224 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001225 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001226 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1227
1228 // Create Decl objects for each parameter, adding them to the
1229 // FunctionDecl.
1230 llvm::SmallVector<ParmVarDecl*, 16> Params;
1231
1232 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1233 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001234 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001235 // We let through "const void" here because Sema::GetTypeForDeclarator
1236 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001237 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1238 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001239 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1240 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001241 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1242
Chris Lattnerdef026a2008-04-10 02:26:16 +00001243 // In C++, the empty parameter-type-list must be spelled "void"; a
1244 // typedef of void is not permitted.
1245 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001246 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001247 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1248 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001249 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001250 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1251 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1252 }
1253
1254 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001255 } else if (R->getAsTypedefType()) {
1256 // When we're declaring a function with a typedef, as in the
1257 // following example, we'll need to synthesize (unnamed)
1258 // parameters for use in the declaration.
1259 //
1260 // @code
1261 // typedef void fn(int);
1262 // fn f;
1263 // @endcode
1264 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1265 if (!FT) {
1266 // This is a typedef of a function with no prototype, so we
1267 // don't need to do anything.
1268 } else if ((FT->getNumArgs() == 0) ||
1269 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1270 FT->getArgType(0)->isVoidType())) {
1271 // This is a zero-argument function. We don't need to do anything.
1272 } else {
1273 // Synthesize a parameter for each argument type.
1274 llvm::SmallVector<ParmVarDecl*, 16> Params;
1275 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1276 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001277 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001278 SourceLocation(), 0,
1279 *ArgType, VarDecl::None,
1280 0, 0));
1281 }
1282
1283 NewFD->setParams(&Params[0], Params.size());
1284 }
Chris Lattner04421082008-04-08 04:40:51 +00001285 }
1286
Douglas Gregor72b505b2008-12-16 21:30:33 +00001287 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1288 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001289 else if (isa<CXXDestructorDecl>(NewFD))
1290 cast<CXXRecordDecl>(NewFD->getParent())->setUserDeclaredDestructor(true);
1291 else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
Douglas Gregor2def4832008-11-17 20:34:05 +00001292 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001293
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001294 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1295 if (NewFD->isOverloadedOperator() &&
1296 CheckOverloadedOperatorDeclaration(NewFD))
1297 NewFD->setInvalidDecl();
1298
Steve Naroffffce4d52008-01-09 23:34:55 +00001299 // Merge the decl with the existing one if appropriate. Since C functions
1300 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001301 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001302 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001303 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001304
1305 // If C++, determine whether NewFD is an overload of PrevDecl or
1306 // a declaration that requires merging. If it's an overload,
1307 // there's no more work to do here; we'll just add the new
1308 // function to the scope.
1309 OverloadedFunctionDecl::function_iterator MatchedDecl;
1310 if (!getLangOptions().CPlusPlus ||
1311 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1312 Decl *OldDecl = PrevDecl;
1313
1314 // If PrevDecl was an overloaded function, extract the
1315 // FunctionDecl that matched.
1316 if (isa<OverloadedFunctionDecl>(PrevDecl))
1317 OldDecl = *MatchedDecl;
1318
1319 // NewFD and PrevDecl represent declarations that need to be
1320 // merged.
1321 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1322
1323 if (NewFD == 0) return 0;
1324 if (Redeclaration) {
1325 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1326
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001327 // An out-of-line member function declaration must also be a
1328 // definition (C++ [dcl.meaning]p1).
1329 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1330 !InvalidDecl) {
1331 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1332 << D.getCXXScopeSpec().getRange();
1333 NewFD->setInvalidDecl();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001334 }
1335 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001336 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001337
1338 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1339 // The user tried to provide an out-of-line definition for a
1340 // member function, but there was no such member function
1341 // declared (C++ [class.mfct]p2). For example:
1342 //
1343 // class X {
1344 // void f() const;
1345 // };
1346 //
1347 // void X::f() { } // ill-formed
1348 //
1349 // Complain about this problem, and attempt to suggest close
1350 // matches (e.g., those that differ only in cv-qualifiers and
1351 // whether the parameter types are references).
1352 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1353 << cast<CXXRecordDecl>(DC)->getDeclName()
1354 << D.getCXXScopeSpec().getRange();
1355 InvalidDecl = true;
1356
1357 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1358 if (!PrevDecl) {
1359 // Nothing to suggest.
1360 } else if (OverloadedFunctionDecl *Ovl
1361 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1362 for (OverloadedFunctionDecl::function_iterator
1363 Func = Ovl->function_begin(),
1364 FuncEnd = Ovl->function_end();
1365 Func != FuncEnd; ++Func) {
1366 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1367 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1368
1369 }
1370 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1371 // Suggest this no matter how mismatched it is; it's the only
1372 // thing we have.
1373 unsigned diag;
1374 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1375 diag = diag::note_member_def_close_match;
1376 else if (Method->getBody())
1377 diag = diag::note_previous_definition;
1378 else
1379 diag = diag::note_previous_declaration;
1380 Diag(Method->getLocation(), diag);
1381 }
1382
1383 PrevDecl = 0;
1384 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001385 }
Anton Korobeynikov2f402702008-12-26 00:52:02 +00001386 // Handle attributes. We need to have merged decls when handling attributes
1387 // (for example to check for conflicts, etc).
1388 ProcessDeclAttributes(NewFD, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001390
Douglas Gregor584049d2008-12-15 23:53:10 +00001391 if (getLangOptions().CPlusPlus) {
1392 // In C++, check default arguments now that we have merged decls.
Chris Lattner04421082008-04-08 04:40:51 +00001393 CheckCXXDefaultArguments(NewFD);
Douglas Gregor584049d2008-12-15 23:53:10 +00001394
1395 // An out-of-line member function declaration must also be a
1396 // definition (C++ [dcl.meaning]p1).
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001397 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001398 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1399 << D.getCXXScopeSpec().getRange();
1400 InvalidDecl = true;
1401 }
1402 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001404 // Check that there are no default arguments (C++ only).
1405 if (getLangOptions().CPlusPlus)
1406 CheckExtraCXXDefaultArguments(D);
1407
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001408 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001409 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1410 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001411 InvalidDecl = true;
1412 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001413
1414 VarDecl *NewVD;
1415 VarDecl::StorageClass SC;
1416 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001417 default: assert(0 && "Unknown storage class!");
1418 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1419 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1420 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1421 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1422 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1423 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001424 case DeclSpec::SCS_mutable:
1425 // mutable can only appear on non-static class members, so it's always
1426 // an error here
1427 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1428 InvalidDecl = true;
Douglas Gregore89b0282008-12-01 22:46:22 +00001429 SC = VarDecl::None;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001430 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001431 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001432
1433 IdentifierInfo *II = Name.getAsIdentifierInfo();
1434 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001435 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1436 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001437 return 0;
1438 }
1439
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001440 if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001441 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001442 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001443 D.getIdentifierLoc(), II,
1444 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001445 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001446 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001447 if (S->getFnParent() == 0) {
1448 // C99 6.9p2: The storage-class specifiers auto and register shall not
1449 // appear in the declaration specifiers in an external declaration.
1450 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerd1625842008-11-24 06:25:27 +00001451 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001452 InvalidDecl = true;
1453 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001454 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001455 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1456 II, R, SC, LastDeclarator,
1457 // FIXME: Move to DeclGroup...
1458 D.getDeclSpec().getSourceRange().getBegin());
1459 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001460 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001461 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001462 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001463
Daniel Dunbara735ad82008-08-06 00:03:29 +00001464 // Handle GNU asm-label extension (encoded as an attribute).
1465 if (Expr *E = (Expr*) D.getAsmLabel()) {
1466 // The parser guarantees this is a string.
1467 StringLiteral *SE = cast<StringLiteral>(E);
1468 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1469 SE->getByteLength())));
1470 }
1471
Nate Begemanc8e89a82008-03-14 18:07:10 +00001472 // Emit an error if an address space was applied to decl with local storage.
1473 // This includes arrays of objects with address space qualifiers, but not
1474 // automatic variables that point to other address spaces.
1475 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001476 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1477 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1478 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001479 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001480 // Merge the decl with the existing one if appropriate. If the decl is
1481 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001482 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001483 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1484 // The user tried to define a non-static data member
1485 // out-of-line (C++ [dcl.meaning]p1).
1486 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1487 << D.getCXXScopeSpec().getRange();
1488 NewVD->Destroy(Context);
1489 return 0;
1490 }
1491
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 NewVD = MergeVarDecl(NewVD, PrevDecl);
1493 if (NewVD == 0) return 0;
Douglas Gregor584049d2008-12-15 23:53:10 +00001494
1495 if (D.getCXXScopeSpec().isSet()) {
1496 // No previous declaration in the qualifying scope.
1497 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1498 << Name << D.getCXXScopeSpec().getRange();
1499 InvalidDecl = true;
1500 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 New = NewVD;
1503 }
1504
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001505 // Set the lexical context. If the declarator has a C++ scope specifier, the
1506 // lexical context will be different from the semantic context.
1507 New->setLexicalDeclContext(CurContext);
1508
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001510 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001511 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001512 // If any semantic error occurred, mark the decl as invalid.
1513 if (D.getInvalidType() || InvalidDecl)
1514 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001515
1516 return New;
1517}
1518
Steve Naroff6594a702008-10-27 11:34:16 +00001519void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001520 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1521 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001522}
1523
Eli Friedmanc594b322008-05-20 13:48:25 +00001524bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1525 switch (Init->getStmtClass()) {
1526 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001527 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001528 return true;
1529 case Expr::ParenExprClass: {
1530 const ParenExpr* PE = cast<ParenExpr>(Init);
1531 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1532 }
1533 case Expr::CompoundLiteralExprClass:
1534 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1535 case Expr::DeclRefExprClass: {
1536 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001537 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1538 if (VD->hasGlobalStorage())
1539 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001540 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001541 return true;
1542 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001543 if (isa<FunctionDecl>(D))
1544 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001545 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001546 return true;
1547 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001548 case Expr::MemberExprClass: {
1549 const MemberExpr *M = cast<MemberExpr>(Init);
1550 if (M->isArrow())
1551 return CheckAddressConstantExpression(M->getBase());
1552 return CheckAddressConstantExpressionLValue(M->getBase());
1553 }
1554 case Expr::ArraySubscriptExprClass: {
1555 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1556 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1557 return CheckAddressConstantExpression(ASE->getBase()) ||
1558 CheckArithmeticConstantExpression(ASE->getIdx());
1559 }
1560 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001561 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001562 return false;
1563 case Expr::UnaryOperatorClass: {
1564 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1565
1566 // C99 6.6p9
1567 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001568 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001569
Steve Naroff6594a702008-10-27 11:34:16 +00001570 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001571 return true;
1572 }
1573 }
1574}
1575
1576bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1577 switch (Init->getStmtClass()) {
1578 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001579 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001580 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001581 case Expr::ParenExprClass:
1582 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001583 case Expr::StringLiteralClass:
1584 case Expr::ObjCStringLiteralClass:
1585 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001586 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001587 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001588 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1589 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1590 Builtin::BI__builtin___CFStringMakeConstantString)
1591 return false;
1592
Steve Naroff6594a702008-10-27 11:34:16 +00001593 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001594 return true;
1595
Eli Friedmanc594b322008-05-20 13:48:25 +00001596 case Expr::UnaryOperatorClass: {
1597 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1598
1599 // C99 6.6p9
1600 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1601 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1602
1603 if (Exp->getOpcode() == UnaryOperator::Extension)
1604 return CheckAddressConstantExpression(Exp->getSubExpr());
1605
Steve Naroff6594a702008-10-27 11:34:16 +00001606 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001607 return true;
1608 }
1609 case Expr::BinaryOperatorClass: {
1610 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1611 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1612
1613 Expr *PExp = Exp->getLHS();
1614 Expr *IExp = Exp->getRHS();
1615 if (IExp->getType()->isPointerType())
1616 std::swap(PExp, IExp);
1617
1618 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1619 return CheckAddressConstantExpression(PExp) ||
1620 CheckArithmeticConstantExpression(IExp);
1621 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001622 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001623 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001624 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001625 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1626 // Check for implicit promotion
1627 if (SubExpr->getType()->isFunctionType() ||
1628 SubExpr->getType()->isArrayType())
1629 return CheckAddressConstantExpressionLValue(SubExpr);
1630 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001631
1632 // Check for pointer->pointer cast
1633 if (SubExpr->getType()->isPointerType())
1634 return CheckAddressConstantExpression(SubExpr);
1635
Eli Friedmanc3f07642008-08-25 20:46:57 +00001636 if (SubExpr->getType()->isIntegralType()) {
1637 // Check for the special-case of a pointer->int->pointer cast;
1638 // this isn't standard, but some code requires it. See
1639 // PR2720 for an example.
1640 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1641 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1642 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1643 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1644 if (IntWidth >= PointerWidth) {
1645 return CheckAddressConstantExpression(SubCast->getSubExpr());
1646 }
1647 }
1648 }
1649 }
1650 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001651 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001652 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001653
Steve Naroff6594a702008-10-27 11:34:16 +00001654 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001655 return true;
1656 }
1657 case Expr::ConditionalOperatorClass: {
1658 // FIXME: Should we pedwarn here?
1659 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1660 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001661 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001662 return true;
1663 }
1664 if (CheckArithmeticConstantExpression(Exp->getCond()))
1665 return true;
1666 if (Exp->getLHS() &&
1667 CheckAddressConstantExpression(Exp->getLHS()))
1668 return true;
1669 return CheckAddressConstantExpression(Exp->getRHS());
1670 }
1671 case Expr::AddrLabelExprClass:
1672 return false;
1673 }
1674}
1675
Eli Friedman4caf0552008-06-09 05:05:07 +00001676static const Expr* FindExpressionBaseAddress(const Expr* E);
1677
1678static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1679 switch (E->getStmtClass()) {
1680 default:
1681 return E;
1682 case Expr::ParenExprClass: {
1683 const ParenExpr* PE = cast<ParenExpr>(E);
1684 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1685 }
1686 case Expr::MemberExprClass: {
1687 const MemberExpr *M = cast<MemberExpr>(E);
1688 if (M->isArrow())
1689 return FindExpressionBaseAddress(M->getBase());
1690 return FindExpressionBaseAddressLValue(M->getBase());
1691 }
1692 case Expr::ArraySubscriptExprClass: {
1693 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1694 return FindExpressionBaseAddress(ASE->getBase());
1695 }
1696 case Expr::UnaryOperatorClass: {
1697 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1698
1699 if (Exp->getOpcode() == UnaryOperator::Deref)
1700 return FindExpressionBaseAddress(Exp->getSubExpr());
1701
1702 return E;
1703 }
1704 }
1705}
1706
1707static const Expr* FindExpressionBaseAddress(const Expr* E) {
1708 switch (E->getStmtClass()) {
1709 default:
1710 return E;
1711 case Expr::ParenExprClass: {
1712 const ParenExpr* PE = cast<ParenExpr>(E);
1713 return FindExpressionBaseAddress(PE->getSubExpr());
1714 }
1715 case Expr::UnaryOperatorClass: {
1716 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1717
1718 // C99 6.6p9
1719 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1720 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1721
1722 if (Exp->getOpcode() == UnaryOperator::Extension)
1723 return FindExpressionBaseAddress(Exp->getSubExpr());
1724
1725 return E;
1726 }
1727 case Expr::BinaryOperatorClass: {
1728 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1729
1730 Expr *PExp = Exp->getLHS();
1731 Expr *IExp = Exp->getRHS();
1732 if (IExp->getType()->isPointerType())
1733 std::swap(PExp, IExp);
1734
1735 return FindExpressionBaseAddress(PExp);
1736 }
1737 case Expr::ImplicitCastExprClass: {
1738 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1739
1740 // Check for implicit promotion
1741 if (SubExpr->getType()->isFunctionType() ||
1742 SubExpr->getType()->isArrayType())
1743 return FindExpressionBaseAddressLValue(SubExpr);
1744
1745 // Check for pointer->pointer cast
1746 if (SubExpr->getType()->isPointerType())
1747 return FindExpressionBaseAddress(SubExpr);
1748
1749 // We assume that we have an arithmetic expression here;
1750 // if we don't, we'll figure it out later
1751 return 0;
1752 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001753 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001754 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1755
1756 // Check for pointer->pointer cast
1757 if (SubExpr->getType()->isPointerType())
1758 return FindExpressionBaseAddress(SubExpr);
1759
1760 // We assume that we have an arithmetic expression here;
1761 // if we don't, we'll figure it out later
1762 return 0;
1763 }
1764 }
1765}
1766
Anders Carlsson51fe9962008-11-22 21:04:56 +00001767bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001768 switch (Init->getStmtClass()) {
1769 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001770 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001771 return true;
1772 case Expr::ParenExprClass: {
1773 const ParenExpr* PE = cast<ParenExpr>(Init);
1774 return CheckArithmeticConstantExpression(PE->getSubExpr());
1775 }
1776 case Expr::FloatingLiteralClass:
1777 case Expr::IntegerLiteralClass:
1778 case Expr::CharacterLiteralClass:
1779 case Expr::ImaginaryLiteralClass:
1780 case Expr::TypesCompatibleExprClass:
1781 case Expr::CXXBoolLiteralExprClass:
1782 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001783 case Expr::CallExprClass:
1784 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001785 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001786
1787 // Allow any constant foldable calls to builtins.
1788 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001789 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001790
Steve Naroff6594a702008-10-27 11:34:16 +00001791 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001792 return true;
1793 }
1794 case Expr::DeclRefExprClass: {
1795 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1796 if (isa<EnumConstantDecl>(D))
1797 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001798 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001799 return true;
1800 }
1801 case Expr::CompoundLiteralExprClass:
1802 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1803 // but vectors are allowed to be magic.
1804 if (Init->getType()->isVectorType())
1805 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001806 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001807 return true;
1808 case Expr::UnaryOperatorClass: {
1809 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1810
1811 switch (Exp->getOpcode()) {
1812 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1813 // See C99 6.6p3.
1814 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001815 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001816 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001817 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00001818 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1819 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001820 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001821 return true;
1822 case UnaryOperator::Extension:
1823 case UnaryOperator::LNot:
1824 case UnaryOperator::Plus:
1825 case UnaryOperator::Minus:
1826 case UnaryOperator::Not:
1827 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1828 }
1829 }
Sebastian Redl05189992008-11-11 17:56:53 +00001830 case Expr::SizeOfAlignOfExprClass: {
1831 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001832 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00001833 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00001834 return false;
1835 // alignof always evaluates to a constant.
1836 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00001837 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001838 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001839 return true;
1840 }
1841 return false;
1842 }
1843 case Expr::BinaryOperatorClass: {
1844 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1845
1846 if (Exp->getLHS()->getType()->isArithmeticType() &&
1847 Exp->getRHS()->getType()->isArithmeticType()) {
1848 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1849 CheckArithmeticConstantExpression(Exp->getRHS());
1850 }
1851
Eli Friedman4caf0552008-06-09 05:05:07 +00001852 if (Exp->getLHS()->getType()->isPointerType() &&
1853 Exp->getRHS()->getType()->isPointerType()) {
1854 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1855 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1856
1857 // Only allow a null (constant integer) base; we could
1858 // allow some additional cases if necessary, but this
1859 // is sufficient to cover offsetof-like constructs.
1860 if (!LHSBase && !RHSBase) {
1861 return CheckAddressConstantExpression(Exp->getLHS()) ||
1862 CheckAddressConstantExpression(Exp->getRHS());
1863 }
1864 }
1865
Steve Naroff6594a702008-10-27 11:34:16 +00001866 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001867 return true;
1868 }
1869 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001870 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001871 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001872 if (SubExpr->getType()->isArithmeticType())
1873 return CheckArithmeticConstantExpression(SubExpr);
1874
Eli Friedmanb529d832008-09-02 09:37:00 +00001875 if (SubExpr->getType()->isPointerType()) {
1876 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1877 // If the pointer has a null base, this is an offsetof-like construct
1878 if (!Base)
1879 return CheckAddressConstantExpression(SubExpr);
1880 }
1881
Steve Naroff6594a702008-10-27 11:34:16 +00001882 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001883 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001884 }
1885 case Expr::ConditionalOperatorClass: {
1886 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001887
1888 // If GNU extensions are disabled, we require all operands to be arithmetic
1889 // constant expressions.
1890 if (getLangOptions().NoExtensions) {
1891 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1892 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1893 CheckArithmeticConstantExpression(Exp->getRHS());
1894 }
1895
1896 // Otherwise, we have to emulate some of the behavior of fold here.
1897 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1898 // because it can constant fold things away. To retain compatibility with
1899 // GCC code, we see if we can fold the condition to a constant (which we
1900 // should always be able to do in theory). If so, we only require the
1901 // specified arm of the conditional to be a constant. This is a horrible
1902 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001903 Expr::EvalResult EvalResult;
1904 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
1905 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001906 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00001907 // won't be able to either. Use it to emit the diagnostic though.
1908 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001909 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00001910 return Res;
1911 }
1912
1913 // Verify that the side following the condition is also a constant.
1914 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001915 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00001916 std::swap(TrueSide, FalseSide);
1917
1918 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001919 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001920
1921 // Okay, the evaluated side evaluates to a constant, so we accept this.
1922 // Check to see if the other side is obviously not a constant. If so,
1923 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001924 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001925 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001926 diag::ext_typecheck_expression_not_constant_but_accepted)
1927 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00001928 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001929 }
1930 }
1931}
1932
1933bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001934 Expr::EvalResult Result;
1935
Nuno Lopes9a979c32008-07-07 16:46:50 +00001936 Init = Init->IgnoreParens();
1937
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001938 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
1939 return false;
1940
Eli Friedmanc594b322008-05-20 13:48:25 +00001941 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1942 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1943 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1944
Nuno Lopes9a979c32008-07-07 16:46:50 +00001945 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1946 return CheckForConstantInitializer(e->getInitializer(), DclT);
1947
Eli Friedmanc594b322008-05-20 13:48:25 +00001948 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1949 unsigned numInits = Exp->getNumInits();
1950 for (unsigned i = 0; i < numInits; i++) {
1951 // FIXME: Need to get the type of the declaration for C++,
1952 // because it could be a reference?
1953 if (CheckForConstantInitializer(Exp->getInit(i),
1954 Exp->getInit(i)->getType()))
1955 return true;
1956 }
1957 return false;
1958 }
1959
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001960 // FIXME: We can probably remove some of this code below, now that
1961 // Expr::Evaluate is doing the heavy lifting for scalars.
1962
Eli Friedmanc594b322008-05-20 13:48:25 +00001963 if (Init->isNullPointerConstant(Context))
1964 return false;
1965 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001966 QualType InitTy = Context.getCanonicalType(Init->getType())
1967 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001968 if (InitTy == Context.BoolTy) {
1969 // Special handling for pointers implicitly cast to bool;
1970 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1971 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1972 Expr* SubE = ICE->getSubExpr();
1973 if (SubE->getType()->isPointerType() ||
1974 SubE->getType()->isArrayType() ||
1975 SubE->getType()->isFunctionType()) {
1976 return CheckAddressConstantExpression(Init);
1977 }
1978 }
1979 } else if (InitTy->isIntegralType()) {
1980 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001981 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001982 SubE = CE->getSubExpr();
1983 // Special check for pointer cast to int; we allow as an extension
1984 // an address constant cast to an integer if the integer
1985 // is of an appropriate width (this sort of code is apparently used
1986 // in some places).
1987 // FIXME: Add pedwarn?
1988 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1989 if (SubE && (SubE->getType()->isPointerType() ||
1990 SubE->getType()->isArrayType() ||
1991 SubE->getType()->isFunctionType())) {
1992 unsigned IntWidth = Context.getTypeSize(Init->getType());
1993 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1994 if (IntWidth >= PointerWidth)
1995 return CheckAddressConstantExpression(Init);
1996 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001997 }
1998
1999 return CheckArithmeticConstantExpression(Init);
2000 }
2001
2002 if (Init->getType()->isPointerType())
2003 return CheckAddressConstantExpression(Init);
2004
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002005 // An array type at the top level that isn't an init-list must
2006 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002007 if (Init->getType()->isArrayType())
2008 return false;
2009
Nuno Lopes73419bf2008-09-01 18:42:41 +00002010 if (Init->getType()->isFunctionType())
2011 return false;
2012
Steve Naroff8af6a452008-10-02 17:12:56 +00002013 // Allow block exprs at top level.
2014 if (Init->getType()->isBlockPointerType())
2015 return false;
2016
Steve Naroff6594a702008-10-27 11:34:16 +00002017 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002018 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002019}
2020
Sebastian Redl798d1192008-12-13 16:23:55 +00002021void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002022 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002023 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002024 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002025
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002026 // If there is no declaration, there was an error parsing it. Just ignore
2027 // the initializer.
2028 if (RealDecl == 0) {
2029 delete Init;
2030 return;
2031 }
Steve Naroffbb204692007-09-12 14:07:44 +00002032
Steve Naroff410e3e22007-09-12 20:13:48 +00002033 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2034 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00002035 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2036 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002037 RealDecl->setInvalidDecl();
2038 return;
2039 }
Steve Naroffbb204692007-09-12 14:07:44 +00002040 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002041 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002042 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002043 if (VDecl->isBlockVarDecl()) {
2044 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002045 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002046 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002047 VDecl->setInvalidDecl();
2048 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002049 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002050 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002051 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002052
2053 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2054 if (!getLangOptions().CPlusPlus) {
2055 if (SC == VarDecl::Static) // C99 6.7.8p4.
2056 CheckForConstantInitializer(Init, DclT);
2057 }
Steve Naroffbb204692007-09-12 14:07:44 +00002058 }
Steve Naroff248a7532008-04-15 22:42:06 +00002059 } else if (VDecl->isFileVarDecl()) {
2060 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002061 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002062 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002063 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002064 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002065 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002066
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002067 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2068 if (!getLangOptions().CPlusPlus) {
2069 // C99 6.7.8p4. All file scoped initializers need to be constant.
2070 CheckForConstantInitializer(Init, DclT);
2071 }
Steve Naroffbb204692007-09-12 14:07:44 +00002072 }
2073 // If the type changed, it means we had an incomplete type that was
2074 // completed by the initializer. For example:
2075 // int ary[] = { 1, 3, 5 };
2076 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002077 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002078 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002079 Init->setType(DclT);
2080 }
Steve Naroffbb204692007-09-12 14:07:44 +00002081
2082 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002083 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002084 return;
2085}
2086
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002087void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2088 Decl *RealDecl = static_cast<Decl *>(dcl);
2089
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002090 // If there is no declaration, there was an error parsing it. Just ignore it.
2091 if (RealDecl == 0)
2092 return;
2093
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002094 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2095 QualType Type = Var->getType();
2096 // C++ [dcl.init.ref]p3:
2097 // The initializer can be omitted for a reference only in a
2098 // parameter declaration (8.3.5), in the declaration of a
2099 // function return type, in the declaration of a class member
2100 // within its class declaration (9.2), and where the extern
2101 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002102 if (Type->isReferenceType() &&
2103 Var->getStorageClass() != VarDecl::Extern &&
2104 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002105 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002106 << Var->getDeclName()
2107 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002108 Var->setInvalidDecl();
2109 return;
2110 }
2111
2112 // C++ [dcl.init]p9:
2113 //
2114 // If no initializer is specified for an object, and the object
2115 // is of (possibly cv-qualified) non-POD class type (or array
2116 // thereof), the object shall be default-initialized; if the
2117 // object is of const-qualified type, the underlying class type
2118 // shall have a user-declared default constructor.
2119 if (getLangOptions().CPlusPlus) {
2120 QualType InitType = Type;
2121 if (const ArrayType *Array = Context.getAsArrayType(Type))
2122 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002123 if (Var->getStorageClass() != VarDecl::Extern &&
2124 Var->getStorageClass() != VarDecl::PrivateExtern &&
2125 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002126 const CXXConstructorDecl *Constructor
2127 = PerformInitializationByConstructor(InitType, 0, 0,
2128 Var->getLocation(),
2129 SourceRange(Var->getLocation(),
2130 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002131 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002132 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002133 if (!Constructor)
2134 Var->setInvalidDecl();
2135 }
2136 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002137
Douglas Gregor818ce482008-10-29 13:50:18 +00002138#if 0
2139 // FIXME: Temporarily disabled because we are not properly parsing
2140 // linkage specifications on declarations, e.g.,
2141 //
2142 // extern "C" const CGPoint CGPointerZero;
2143 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002144 // C++ [dcl.init]p9:
2145 //
2146 // If no initializer is specified for an object, and the
2147 // object is of (possibly cv-qualified) non-POD class type (or
2148 // array thereof), the object shall be default-initialized; if
2149 // the object is of const-qualified type, the underlying class
2150 // type shall have a user-declared default
2151 // constructor. Otherwise, if no initializer is specified for
2152 // an object, the object and its subobjects, if any, have an
2153 // indeterminate initial value; if the object or any of its
2154 // subobjects are of const-qualified type, the program is
2155 // ill-formed.
2156 //
2157 // This isn't technically an error in C, so we don't diagnose it.
2158 //
2159 // FIXME: Actually perform the POD/user-defined default
2160 // constructor check.
2161 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002162 Context.getCanonicalType(Type).isConstQualified() &&
2163 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002164 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2165 << Var->getName()
2166 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002167#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002168 }
2169}
2170
Reid Spencer5f016e22007-07-11 17:01:13 +00002171/// The declarators are chained together backwards, reverse the list.
2172Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2173 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002174 Decl *GroupDecl = static_cast<Decl*>(group);
2175 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002176 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002177
2178 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2179 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002180 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002181 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002182 else { // reverse the list.
2183 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00002184 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002185 Group->setNextDeclarator(NewGroup);
2186 NewGroup = Group;
2187 Group = Next;
2188 }
2189 }
2190 // Perform semantic analysis that depends on having fully processed both
2191 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00002192 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002193 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2194 if (!IDecl)
2195 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002196 QualType T = IDecl->getType();
2197
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002198 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002199 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002200
2201 // FIXME: This won't give the correct result for
2202 // int a[10][n];
2203 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002204 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002205 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2206 SizeRange;
2207
Eli Friedmanc5773c42008-02-15 18:16:39 +00002208 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002209 } else {
2210 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2211 // static storage duration, it shall not have a variable length array.
2212 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002213 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2214 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002215 IDecl->setInvalidDecl();
2216 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002217 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2218 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002219 IDecl->setInvalidDecl();
2220 }
2221 }
2222 } else if (T->isVariablyModifiedType()) {
2223 if (IDecl->isFileVarDecl()) {
2224 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2225 IDecl->setInvalidDecl();
2226 } else {
2227 if (IDecl->getStorageClass() == VarDecl::Extern) {
2228 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2229 IDecl->setInvalidDecl();
2230 }
Steve Naroffbb204692007-09-12 14:07:44 +00002231 }
2232 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002233
Steve Naroffbb204692007-09-12 14:07:44 +00002234 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2235 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002236 if (IDecl->isBlockVarDecl() &&
2237 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002238 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002239 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002240 IDecl->setInvalidDecl();
2241 }
2242 }
2243 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2244 // object that has file scope without an initializer, and without a
2245 // storage-class specifier or with the storage-class specifier "static",
2246 // constitutes a tentative definition. Note: A tentative definition with
2247 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002248 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002249 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002250 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2251 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002252 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002253 // C99 6.9.2p3: If the declaration of an identifier for an object is
2254 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2255 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002256 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002257 IDecl->setInvalidDecl();
2258 }
2259 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002260 if (IDecl->isFileVarDecl())
2261 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002262 }
2263 return NewGroup;
2264}
Steve Naroffe1223f72007-08-28 03:03:08 +00002265
Chris Lattner04421082008-04-08 04:40:51 +00002266/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2267/// to introduce parameters into function prototype scope.
2268Sema::DeclTy *
2269Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002270 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002271
Chris Lattner04421082008-04-08 04:40:51 +00002272 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002273 VarDecl::StorageClass StorageClass = VarDecl::None;
2274 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2275 StorageClass = VarDecl::Register;
2276 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002277 Diag(DS.getStorageClassSpecLoc(),
2278 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002279 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002280 }
2281 if (DS.isThreadSpecified()) {
2282 Diag(DS.getThreadSpecLoc(),
2283 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002284 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002285 }
2286
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002287 // Check that there are no default arguments inside the type of this
2288 // parameter (C++ only).
2289 if (getLangOptions().CPlusPlus)
2290 CheckExtraCXXDefaultArguments(D);
2291
Chris Lattner04421082008-04-08 04:40:51 +00002292 // In this context, we *do not* check D.getInvalidType(). If the declarator
2293 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2294 // though it will not reflect the user specified type.
2295 QualType parmDeclType = GetTypeForDeclarator(D, S);
2296
2297 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2298
Reid Spencer5f016e22007-07-11 17:01:13 +00002299 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2300 // Can this happen for params? We already checked that they don't conflict
2301 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002302 IdentifierInfo *II = D.getIdentifier();
2303 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregorf57172b2008-12-08 18:40:42 +00002304 if (PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002305 // Maybe we will complain about the shadowed template parameter.
2306 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2307 // Just pretend that we didn't see the previous declaration.
2308 PrevDecl = 0;
2309 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002310 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002311
2312 // Recover by removing the name
2313 II = 0;
2314 D.SetIdentifier(0, D.getIdentifierLoc());
2315 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002316 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002317
2318 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2319 // Doing the promotion here has a win and a loss. The win is the type for
2320 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2321 // code generator). The loss is the orginal type isn't preserved. For example:
2322 //
2323 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2324 // int blockvardecl[5];
2325 // sizeof(parmvardecl); // size == 4
2326 // sizeof(blockvardecl); // size == 20
2327 // }
2328 //
2329 // For expressions, all implicit conversions are captured using the
2330 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2331 //
2332 // FIXME: If a source translation tool needs to see the original type, then
2333 // we need to consider storing both types (in ParmVarDecl)...
2334 //
Chris Lattnere6327742008-04-02 05:18:44 +00002335 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002336 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002337 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002338 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002339 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002340
Chris Lattner04421082008-04-08 04:40:51 +00002341 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2342 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002343 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002344 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002345
Chris Lattner04421082008-04-08 04:40:51 +00002346 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002347 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002348
Douglas Gregor584049d2008-12-15 23:53:10 +00002349 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2350 if (D.getCXXScopeSpec().isSet()) {
2351 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2352 << D.getCXXScopeSpec().getRange();
2353 New->setInvalidDecl();
2354 }
2355
Douglas Gregor44b43212008-12-11 16:49:14 +00002356 // Add the parameter declaration into this scope.
2357 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002358 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002359 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002360
Chris Lattner3ff30c82008-06-29 00:02:00 +00002361 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002362 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002363
Reid Spencer5f016e22007-07-11 17:01:13 +00002364}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002365
Chris Lattnerb652cea2007-10-09 17:14:05 +00002366Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002367 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002368 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2369 "Not a function declarator!");
2370 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002371
Reid Spencer5f016e22007-07-11 17:01:13 +00002372 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2373 // for a K&R function.
2374 if (!FTI.hasPrototype) {
2375 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002376 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002377 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2378 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002379 // Implicitly declare the argument as type 'int' for lack of a better
2380 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002381 DeclSpec DS;
2382 const char* PrevSpec; // unused
2383 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2384 PrevSpec);
2385 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2386 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2387 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002388 }
2389 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002390 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002391 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002392 }
2393
Douglas Gregor584049d2008-12-15 23:53:10 +00002394 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002395
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002396 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002397 ActOnDeclarator(ParentScope, D, 0,
2398 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002399}
2400
2401Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2402 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002403 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002404
2405 // See if this is a redefinition.
2406 const FunctionDecl *Definition;
2407 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002408 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002409 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002410 }
2411
Douglas Gregor44b43212008-12-11 16:49:14 +00002412 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002413
Chris Lattner04421082008-04-08 04:40:51 +00002414 // Check the validity of our function parameters
2415 CheckParmsForFunctionDef(FD);
2416
2417 // Introduce our parameters into the function scope
2418 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2419 ParmVarDecl *Param = FD->getParamDecl(p);
2420 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002421 if (Param->getIdentifier())
2422 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002423 }
Chris Lattner04421082008-04-08 04:40:51 +00002424
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002425 // Checking attributes of current function definition
2426 // dllimport attribute.
2427 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2428 // dllimport attribute cannot be applied to definition.
2429 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2430 Diag(FD->getLocation(),
2431 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2432 << "dllimport";
2433 FD->setInvalidDecl();
2434 return FD;
2435 } else {
2436 // If a symbol previously declared dllimport is later defined, the
2437 // attribute is ignored in subsequent references, and a warning is
2438 // emitted.
2439 Diag(FD->getLocation(),
2440 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2441 << FD->getNameAsCString() << "dllimport";
2442 }
2443 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002444 return FD;
2445}
2446
Sebastian Redl798d1192008-12-13 16:23:55 +00002447Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002448 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002449 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002450 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002451 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002452 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002453 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002454 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002455 } else
2456 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002457 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002458 // Verify and clean out per-function state.
2459
2460 // Check goto/label use.
2461 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2462 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2463 // Verify that we have no forward references left. If so, there was a goto
2464 // or address of a label taken, but no definition of it. Label fwd
2465 // definitions are indicated with a null substmt.
2466 if (I->second->getSubStmt() == 0) {
2467 LabelStmt *L = I->second;
2468 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002469 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002470
2471 // At this point, we have gotos that use the bogus label. Stitch it into
2472 // the function body so that they aren't leaked and that the AST is well
2473 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002474 if (Body) {
2475 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002476 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002477 } else {
2478 // The whole function wasn't parsed correctly, just delete this.
2479 delete L;
2480 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002481 }
2482 }
2483 LabelMap.clear();
2484
Steve Naroffd6d054d2007-11-11 23:20:51 +00002485 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002486}
2487
Reid Spencer5f016e22007-07-11 17:01:13 +00002488/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2489/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002490ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2491 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002492 // Extension in C99. Legal in C90, but warn about it.
2493 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002494 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002495 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002496 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002497
2498 // FIXME: handle stuff like:
2499 // void foo() { extern float X(); }
2500 // void bar() { X(); } <-- implicit decl for X in another scope.
2501
2502 // Set a Declarator for the implicit definition: int foo();
2503 const char *Dummy;
2504 DeclSpec DS;
2505 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2506 Error = Error; // Silence warning.
2507 assert(!Error && "Error setting up implicit decl!");
2508 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002509 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002510 D.SetIdentifier(&II, Loc);
2511
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002512 // Insert this function into translation-unit scope.
2513
2514 DeclContext *PrevDC = CurContext;
2515 CurContext = Context.getTranslationUnitDecl();
2516
Steve Naroffe2ef8152008-04-04 14:32:09 +00002517 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002518 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002519 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002520
2521 CurContext = PrevDC;
2522
Steve Naroffe2ef8152008-04-04 14:32:09 +00002523 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002524}
2525
2526
Chris Lattner41af0932007-11-14 06:34:38 +00002527TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002528 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002529 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002530 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002531
2532 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002533 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2534 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002535 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002536 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002537 if (D.getInvalidType())
2538 NewTD->setInvalidDecl();
2539 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002540}
2541
Steve Naroff08d92e42007-09-15 18:49:24 +00002542/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002543/// former case, Name will be non-null. In the later case, Name will be null.
2544/// TagType indicates what kind of tag this is. TK indicates whether this is a
2545/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002546Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002547 SourceLocation KWLoc, const CXXScopeSpec &SS,
2548 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +00002549 AttributeList *Attr,
2550 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002551 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002552 assert((Name != 0 || TK == TK_Definition) &&
2553 "Nameless record must be a definition!");
2554
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002555 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002556 switch (TagType) {
2557 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002558 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2559 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2560 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2561 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002562 }
2563
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002564 DeclContext *DC = CurContext;
2565 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002566
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002567 if (Name && SS.isNotEmpty()) {
2568 // We have a nested-name tag ('struct foo::bar').
2569
2570 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002571 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002572 Name = 0;
2573 goto CreateNewDecl;
2574 }
2575
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002576 DC = static_cast<DeclContext*>(SS.getScopeRep());
2577 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002578 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2579
2580 // A tag 'foo::bar' must already exist.
2581 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002582 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002583 Name = 0;
2584 goto CreateNewDecl;
2585 }
2586 } else {
2587 // If this is a named struct, check to see if there was a previous forward
2588 // declaration or definition.
2589 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2590 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2591 }
2592
Douglas Gregorf57172b2008-12-08 18:40:42 +00002593 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002594 // Maybe we will complain about the shadowed template parameter.
2595 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2596 // Just pretend that we didn't see the previous declaration.
2597 PrevDecl = 0;
2598 }
2599
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002600 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002601 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2602 "unexpected Decl type");
2603 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002604 // If this is a use of a previous tag, or if the tag is already declared
2605 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002606 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002607 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002608 // Make sure that this wasn't declared as an enum and now used as a
2609 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002610 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002611 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002612 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002613 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002614 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002615 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002616 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002617 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002618
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002619 // FIXME: In the future, return a variant or some other clue
2620 // for the consumer of this Decl to know it doesn't own it.
2621 // For our current ASTs this shouldn't be a problem, but will
2622 // need to be changed with DeclGroups.
2623 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002624 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002625
2626 // Diagnose attempts to redefine a tag.
2627 if (TK == TK_Definition) {
2628 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2629 Diag(NameLoc, diag::err_redefinition) << Name;
2630 Diag(Def->getLocation(), diag::note_previous_definition);
2631 // If this is a redefinition, recover by making this struct be
2632 // anonymous, which will make any later references get the previous
2633 // definition.
2634 Name = 0;
2635 PrevDecl = 0;
2636 }
2637 // Okay, this is definition of a previously declared or referenced
2638 // tag PrevDecl. We're going to create a new Decl for it.
2639 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002640 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002641 // If we get here we have (another) forward declaration or we
2642 // have a definition. Just create a new decl.
2643 } else {
2644 // If we get here, this is a definition of a new tag type in a nested
2645 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2646 // new decl/type. We set PrevDecl to NULL so that the entities
2647 // have distinct types.
2648 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002649 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002650 // If we get here, we're going to create a new Decl. If PrevDecl
2651 // is non-NULL, it's a definition of the tag declared by
2652 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002653 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002654 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002655 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002656 // The tag name clashes with a namespace name, issue an error and
2657 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002658 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002659 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002660 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002661 PrevDecl = 0;
2662 } else {
2663 // The existing declaration isn't relevant to us; we're in a
2664 // new scope, so clear out the previous declaration.
2665 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002666 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002667 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002668 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002669
Chris Lattnercc98eac2008-12-17 07:13:27 +00002670CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002671
2672 // If there is an identifier, use the location of the identifier as the
2673 // location of the decl, otherwise use the location of the struct/union
2674 // keyword.
2675 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2676
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002677 // Otherwise, create a new declaration. If there is a previous
2678 // declaration of the same entity, the two will be linked via
2679 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00002680 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002681 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002682 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2683 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002684 New = EnumDecl::Create(Context, DC, Loc, Name,
2685 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002686 // If this is an undefined enum, warn.
2687 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002688 } else {
2689 // struct/union/class
2690
Reid Spencer5f016e22007-07-11 17:01:13 +00002691 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2692 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002693 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002694 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002695 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2696 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002697 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002698 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2699 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002700 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002701
2702 if (Kind != TagDecl::TK_enum) {
2703 // Handle #pragma pack: if the #pragma pack stack has non-default
2704 // alignment, make up a packed attribute for this decl. These
2705 // attributes are checked when the ASTContext lays out the
2706 // structure.
2707 //
2708 // It is important for implementing the correct semantics that this
2709 // happen here (in act on tag decl). The #pragma pack stack is
2710 // maintained as a result of parser callbacks which can occur at
2711 // many points during the parsing of a struct declaration (because
2712 // the #pragma tokens are effectively skipped over during the
2713 // parsing of the struct).
2714 if (unsigned Alignment = PackContext.getAlignment())
2715 New->addAttr(new PackedAttr(Alignment * 8));
2716 }
2717
2718 if (Attr)
2719 ProcessDeclAttributeList(New, Attr);
2720
2721 // Set the lexical context. If the tag has a C++ scope specifier, the
2722 // lexical context will be different from the semantic context.
2723 New->setLexicalDeclContext(CurContext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002724
2725 // If this has an identifier, add it to the scope stack.
2726 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002727 // The scope passed in may not be a decl scope. Zip up the scope tree until
2728 // we find one that is.
2729 while ((S->getFlags() & Scope::DeclScope) == 0)
2730 S = S->getParent();
2731
2732 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002733 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002734 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002735
Reid Spencer5f016e22007-07-11 17:01:13 +00002736 return New;
2737}
2738
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002739
Chris Lattner1d353ba2008-11-12 21:17:48 +00002740/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2741/// types into constant array types in certain situations which would otherwise
2742/// be errors (for GCC compatibility).
2743static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2744 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002745 // This method tries to turn a variable array into a constant
2746 // array even when the size isn't an ICE. This is necessary
2747 // for compatibility with code that depends on gcc's buggy
2748 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00002749 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2750 if (!VLATy) return QualType();
2751
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002752 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00002753 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002754 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00002755 return QualType();
2756
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002757 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
2758 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00002759 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2760 return Context.getConstantArrayType(VLATy->getElementType(),
2761 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002762 return QualType();
2763}
2764
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002765bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00002766 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002767 // FIXME: 6.7.2.1p4 - verify the field type.
2768
2769 llvm::APSInt Value;
2770 if (VerifyIntegerConstantExpression(BitWidth, &Value))
2771 return true;
2772
Chris Lattnercd087072008-12-12 04:56:04 +00002773 // Zero-width bitfield is ok for anonymous field.
2774 if (Value == 0 && FieldName)
2775 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
2776
2777 if (Value.isNegative())
2778 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002779
2780 uint64_t TypeSize = Context.getTypeSize(FieldTy);
2781 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00002782 if (TypeSize && Value.getZExtValue() > TypeSize)
2783 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
2784 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002785
2786 return false;
2787}
2788
Steve Naroff08d92e42007-09-15 18:49:24 +00002789/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002790/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00002791Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00002792 SourceLocation DeclStart,
2793 Declarator &D, ExprTy *BitfieldWidth) {
2794 IdentifierInfo *II = D.getIdentifier();
2795 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002796 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00002797 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002798 if (II) Loc = D.getIdentifierLoc();
2799
2800 // FIXME: Unnamed fields can be handled in various different ways, for
2801 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00002802
Reid Spencer5f016e22007-07-11 17:01:13 +00002803 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002804 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2805 bool InvalidDecl = false;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002806
Reid Spencer5f016e22007-07-11 17:01:13 +00002807 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2808 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002809 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00002810 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002811 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002812 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002813 T = FixedTy;
2814 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002815 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00002816 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002817 InvalidDecl = true;
2818 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002819 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002820
2821 if (BitWidth) {
2822 if (VerifyBitField(Loc, II, T, BitWidth))
2823 InvalidDecl = true;
2824 } else {
2825 // Not a bitfield.
2826
2827 // validate II.
2828
2829 }
2830
Reid Spencer5f016e22007-07-11 17:01:13 +00002831 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002832 FieldDecl *NewFD;
2833
Douglas Gregor44b43212008-12-11 16:49:14 +00002834 // FIXME: We don't want CurContext for C, do we? No, we'll need some
2835 // other way to determine the current RecordDecl.
2836 NewFD = FieldDecl::Create(Context, Record,
2837 Loc, II, T, BitWidth,
2838 D.getDeclSpec().getStorageClassSpec() ==
2839 DeclSpec::SCS_mutable,
2840 /*PrevDecl=*/0);
2841
Douglas Gregor72b505b2008-12-16 21:30:33 +00002842 if (getLangOptions().CPlusPlus)
2843 CheckExtraCXXDefaultArguments(D);
2844
Chris Lattner3ff30c82008-06-29 00:02:00 +00002845 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002846
Steve Naroff5912a352007-08-28 20:14:24 +00002847 if (D.getInvalidType() || InvalidDecl)
2848 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002849
2850 if (II && getLangOptions().CPlusPlus)
2851 PushOnScopeChains(NewFD, S);
2852 else
2853 Record->addDecl(Context, NewFD);
2854
Steve Naroff5912a352007-08-28 20:14:24 +00002855 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002856}
2857
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002858/// TranslateIvarVisibility - Translate visibility from a token ID to an
2859/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002860static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002861TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002862 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002863 default: assert(0 && "Unknown visitibility kind");
2864 case tok::objc_private: return ObjCIvarDecl::Private;
2865 case tok::objc_public: return ObjCIvarDecl::Public;
2866 case tok::objc_protected: return ObjCIvarDecl::Protected;
2867 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002868 }
2869}
2870
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002871/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2872/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002873Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002874 SourceLocation DeclStart,
2875 Declarator &D, ExprTy *BitfieldWidth,
2876 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002877 IdentifierInfo *II = D.getIdentifier();
2878 Expr *BitWidth = (Expr*)BitfieldWidth;
2879 SourceLocation Loc = DeclStart;
2880 if (II) Loc = D.getIdentifierLoc();
2881
2882 // FIXME: Unnamed fields can be handled in various different ways, for
2883 // example, unnamed unions inject all members into the struct namespace!
2884
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002885 QualType T = GetTypeForDeclarator(D, S);
2886 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2887 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002888
2889 if (BitWidth) {
2890 // TODO: Validate.
2891 //printf("WARNING: BITFIELDS IGNORED!\n");
2892
2893 // 6.7.2.1p3
2894 // 6.7.2.1p4
2895
2896 } else {
2897 // Not a bitfield.
2898
2899 // validate II.
2900
2901 }
2902
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002903 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2904 // than a variably modified type.
2905 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002906 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002907 InvalidDecl = true;
2908 }
2909
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002910 // Get the visibility (access control) for this ivar.
2911 ObjCIvarDecl::AccessControl ac =
2912 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2913 : ObjCIvarDecl::None;
2914
2915 // Construct the decl.
2916 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002917 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002918
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002919 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002920 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002921
2922 if (D.getInvalidType() || InvalidDecl)
2923 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002924
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002925 return NewID;
2926}
2927
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002928void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002929 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002930 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002931 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002932 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002933 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2934 assert(EnclosingDecl && "missing record or interface decl");
2935 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2936
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002937 if (Record)
2938 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2939 // Diagnose code like:
2940 // struct S { struct S {} X; };
2941 // We discover this when we complete the outer S. Reject and ignore the
2942 // outer S.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002943 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002944 << DefRecord->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002945 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002946 Record->setInvalidDecl();
2947 return;
2948 }
2949
Reid Spencer5f016e22007-07-11 17:01:13 +00002950 // Verify that all the fields are okay.
2951 unsigned NumNamedMembers = 0;
2952 llvm::SmallVector<FieldDecl*, 32> RecFields;
2953 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002954
Reid Spencer5f016e22007-07-11 17:01:13 +00002955 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002956
Steve Naroff74216642007-09-14 22:20:54 +00002957 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2958 assert(FD && "missing field decl");
2959
2960 // Remember all fields.
2961 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002962
2963 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002964 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002965
Reid Spencer5f016e22007-07-11 17:01:13 +00002966 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002967 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002968 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002969 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002970 FD->setInvalidDecl();
2971 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002972 continue;
2973 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002974 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2975 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002976 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002977 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002978 FD->setInvalidDecl();
2979 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002980 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002981 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002982 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002983 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002984 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002985 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002986 FD->setInvalidDecl();
2987 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002988 continue;
2989 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002990 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002991 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002992 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002993 FD->setInvalidDecl();
2994 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002995 continue;
2996 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002997 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002998 if (Record)
2999 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003000 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003001 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3002 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003003 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003004 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3005 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003006 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003007 Record->setHasFlexibleArrayMember(true);
3008 } else {
3009 // If this is a struct/class and this is not the last element, reject
3010 // it. Note that GCC supports variable sized arrays in the middle of
3011 // structures.
3012 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003013 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003014 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003015 FD->setInvalidDecl();
3016 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003017 continue;
3018 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003019 // We support flexible arrays at the end of structs in other structs
3020 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003021 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003022 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003023 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003024 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003025 }
3026 }
3027 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003028 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003029 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003030 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003031 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003032 FD->setInvalidDecl();
3033 EnclosingDecl->setInvalidDecl();
3034 continue;
3035 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003036 // Keep track of the number of named members.
3037 if (IdentifierInfo *II = FD->getIdentifier()) {
3038 // Detect duplicate member names.
3039 if (!FieldIDs.insert(II)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00003040 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Reid Spencer5f016e22007-07-11 17:01:13 +00003041 // Find the previous decl.
3042 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00003043 for (unsigned i = 0; ; ++i) {
3044 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00003045 if (RecFields[i]->getIdentifier() == II) {
3046 PrevLoc = RecFields[i]->getLocation();
3047 break;
3048 }
3049 }
Chris Lattner5f4a6822008-11-23 23:12:31 +00003050 Diag(PrevLoc, diag::note_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00003051 FD->setInvalidDecl();
3052 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003053 continue;
3054 }
3055 ++NumNamedMembers;
3056 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003057 }
3058
Reid Spencer5f016e22007-07-11 17:01:13 +00003059 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003060 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003061 Record->completeDefinition(Context);
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00003062 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
3063 // Sema::ActOnFinishCXXClassDef.
3064 if (!isa<CXXRecordDecl>(Record))
3065 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00003066 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003067 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003068 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003069 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003070 // Must enforce the rule that ivars in the base classes may not be
3071 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003072 if (ID->getSuperClass()) {
3073 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3074 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3075 ObjCIvarDecl* Ivar = (*IVI);
3076 IdentifierInfo *II = Ivar->getIdentifier();
3077 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3078 if (prevIvar) {
3079 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3080 Diag(prevIvar->getLocation(), diag::note_previous_definition);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003081 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003082 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003083 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003084 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003085 else if (ObjCImplementationDecl *IMPDecl =
3086 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003087 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3088 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003089 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003090 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003091 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003092
3093 if (Attr)
3094 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003095}
3096
Steve Naroff08d92e42007-09-15 18:49:24 +00003097Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003098 DeclTy *lastEnumConst,
3099 SourceLocation IdLoc, IdentifierInfo *Id,
3100 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003101 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003102 EnumConstantDecl *LastEnumConst =
3103 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3104 Expr *Val = static_cast<Expr*>(val);
3105
Chris Lattner31e05722007-08-26 06:24:45 +00003106 // The scope passed in may not be a decl scope. Zip up the scope tree until
3107 // we find one that is.
3108 while ((S->getFlags() & Scope::DeclScope) == 0)
3109 S = S->getParent();
3110
Reid Spencer5f016e22007-07-11 17:01:13 +00003111 // Verify that there isn't already something declared with this name in this
3112 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003113 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003114 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003115 // Maybe we will complain about the shadowed template parameter.
3116 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3117 // Just pretend that we didn't see the previous declaration.
3118 PrevDecl = 0;
3119 }
3120
3121 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003122 // When in C++, we may get a TagDecl with the same name; in this case the
3123 // enum constant will 'hide' the tag.
3124 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3125 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003126 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003127 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003128 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003129 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003130 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003131 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003132 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003133 return 0;
3134 }
3135 }
3136
3137 llvm::APSInt EnumVal(32);
3138 QualType EltTy;
3139 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003140 // Make sure to promote the operand type to int.
3141 UsualUnaryConversions(Val);
3142
Reid Spencer5f016e22007-07-11 17:01:13 +00003143 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3144 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003145 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003146 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003147 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003148 } else {
3149 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003150 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003151 }
3152
3153 if (!Val) {
3154 if (LastEnumConst) {
3155 // Assign the last value + 1.
3156 EnumVal = LastEnumConst->getInitVal();
3157 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003158
3159 // Check for overflow on increment.
3160 if (EnumVal < LastEnumConst->getInitVal())
3161 Diag(IdLoc, diag::warn_enum_value_overflow);
3162
Chris Lattnerb7416f92007-08-27 17:37:24 +00003163 EltTy = LastEnumConst->getType();
3164 } else {
3165 // First value, set to zero.
3166 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003167 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003168 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003169 }
3170
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003171 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003172 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3173 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003174 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003175
3176 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003177 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003178
3179 // Add this enumerator into the enum itself.
3180 // FIXME: This means that the enumerator is stored in two
3181 // DeclContexts. This is not a long-term solution.
3182 New->setLexicalDeclContext(TheEnumDecl);
3183 TheEnumDecl->addDecl(Context, New, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003184 return New;
3185}
3186
Steve Naroff02408c62008-08-07 14:08:16 +00003187// FIXME: For consistency with ActOnFields(), we should have the parser
3188// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003189void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003190 DeclTy **Elements, unsigned NumElements) {
3191 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00003192
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003193 if (Enum) {
3194 if (EnumDecl *Def = cast_or_null<EnumDecl>(Enum->getDefinition(Context))) {
3195 // Diagnose code like:
3196 // enum e0 {
3197 // E0 = sizeof(enum e0 { E1 })
3198 // };
3199 Diag(Def->getLocation(), diag::err_nested_redefinition)
3200 << Enum->getDeclName();
3201 Diag(Enum->getLocation(), diag::note_previous_definition);
3202 Enum->setInvalidDecl();
3203 return;
3204 }
Steve Naroff02408c62008-08-07 14:08:16 +00003205 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00003206 // TODO: If the result value doesn't fit in an int, it must be a long or long
3207 // long value. ISO C does not support this, but GCC does as an extension,
3208 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003209 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003210
Chris Lattnerac609682007-08-28 06:15:15 +00003211 // Verify that all the values are okay, compute the size of the values, and
3212 // reverse the list.
3213 unsigned NumNegativeBits = 0;
3214 unsigned NumPositiveBits = 0;
3215
3216 // Keep track of whether all elements have type int.
3217 bool AllElementsInt = true;
3218
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003219 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003220 EnumConstantDecl *EltList = 0;
3221 for (unsigned i = 0; i != NumElements; ++i) {
3222 EnumConstantDecl *ECD =
3223 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3224 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003225
3226 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003227 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003228 assert(InitVal.getBitWidth() >= IntWidth &&
3229 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003230 if (InitVal.getBitWidth() > IntWidth) {
3231 llvm::APSInt V(InitVal);
3232 V.trunc(IntWidth);
3233 V.extend(InitVal.getBitWidth());
3234 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003235 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3236 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003237 }
Chris Lattnerac609682007-08-28 06:15:15 +00003238
3239 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003240 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003241 NumPositiveBits = std::max(NumPositiveBits,
3242 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003243 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003244 NumNegativeBits = std::max(NumNegativeBits,
3245 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003246
Chris Lattnerac609682007-08-28 06:15:15 +00003247 // Keep track of whether every enum element has type int (very commmon).
3248 if (AllElementsInt)
3249 AllElementsInt = ECD->getType() == Context.IntTy;
3250
Reid Spencer5f016e22007-07-11 17:01:13 +00003251 ECD->setNextDeclarator(EltList);
3252 EltList = ECD;
3253 }
3254
Chris Lattnerac609682007-08-28 06:15:15 +00003255 // Figure out the type that should be used for this enum.
3256 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3257 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003258 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003259
3260 if (NumNegativeBits) {
3261 // If there is a negative value, figure out the smallest integer type (of
3262 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003263 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003264 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003265 BestWidth = IntWidth;
3266 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003267 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003268
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003269 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003270 BestType = Context.LongTy;
3271 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003272 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003273
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003274 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003275 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3276 BestType = Context.LongLongTy;
3277 }
3278 }
3279 } else {
3280 // If there is no negative value, figure out which of uint, ulong, ulonglong
3281 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003282 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003283 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003284 BestWidth = IntWidth;
3285 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003286 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003287 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003288 } else {
3289 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003290 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003291 "How could an initializer get larger than ULL?");
3292 BestType = Context.UnsignedLongLongTy;
3293 }
3294 }
3295
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003296 // Loop over all of the enumerator constants, changing their types to match
3297 // the type of the enum if needed.
3298 for (unsigned i = 0; i != NumElements; ++i) {
3299 EnumConstantDecl *ECD =
3300 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3301 if (!ECD) continue; // Already issued a diagnostic.
3302
3303 // Standard C says the enumerators have int type, but we allow, as an
3304 // extension, the enumerators to be larger than int size. If each
3305 // enumerator value fits in an int, type it as an int, otherwise type it the
3306 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3307 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003308 if (ECD->getType() == Context.IntTy) {
3309 // Make sure the init value is signed.
3310 llvm::APSInt IV = ECD->getInitVal();
3311 IV.setIsSigned(true);
3312 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003313
3314 if (getLangOptions().CPlusPlus)
3315 // C++ [dcl.enum]p4: Following the closing brace of an
3316 // enum-specifier, each enumerator has the type of its
3317 // enumeration.
3318 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003319 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003320 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003321
3322 // Determine whether the value fits into an int.
3323 llvm::APSInt InitVal = ECD->getInitVal();
3324 bool FitsInInt;
3325 if (InitVal.isUnsigned() || !InitVal.isNegative())
3326 FitsInInt = InitVal.getActiveBits() < IntWidth;
3327 else
3328 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3329
3330 // If it fits into an integer type, force it. Otherwise force it to match
3331 // the enum decl type.
3332 QualType NewTy;
3333 unsigned NewWidth;
3334 bool NewSign;
3335 if (FitsInInt) {
3336 NewTy = Context.IntTy;
3337 NewWidth = IntWidth;
3338 NewSign = true;
3339 } else if (ECD->getType() == BestType) {
3340 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003341 if (getLangOptions().CPlusPlus)
3342 // C++ [dcl.enum]p4: Following the closing brace of an
3343 // enum-specifier, each enumerator has the type of its
3344 // enumeration.
3345 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003346 continue;
3347 } else {
3348 NewTy = BestType;
3349 NewWidth = BestWidth;
3350 NewSign = BestType->isSignedIntegerType();
3351 }
3352
3353 // Adjust the APSInt value.
3354 InitVal.extOrTrunc(NewWidth);
3355 InitVal.setIsSigned(NewSign);
3356 ECD->setInitVal(InitVal);
3357
3358 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003359 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3360 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003361 if (getLangOptions().CPlusPlus)
3362 // C++ [dcl.enum]p4: Following the closing brace of an
3363 // enum-specifier, each enumerator has the type of its
3364 // enumeration.
3365 ECD->setType(EnumType);
3366 else
3367 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003368 }
Chris Lattnerac609682007-08-28 06:15:15 +00003369
Douglas Gregor44b43212008-12-11 16:49:14 +00003370 Enum->completeDefinition(Context, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003371 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003372}
3373
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003374Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003375 ExprArg expr) {
3376 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3377
Chris Lattner8e25d862008-03-16 00:16:02 +00003378 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003379}
3380
Douglas Gregorf44515a2008-12-16 22:23:02 +00003381
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003382void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3383 ExprTy *alignment, SourceLocation PragmaLoc,
3384 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3385 Expr *Alignment = static_cast<Expr *>(alignment);
3386
3387 // If specified then alignment must be a "small" power of two.
3388 unsigned AlignmentVal = 0;
3389 if (Alignment) {
3390 llvm::APSInt Val;
3391 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3392 !Val.isPowerOf2() ||
3393 Val.getZExtValue() > 16) {
3394 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3395 delete Alignment;
3396 return; // Ignore
3397 }
3398
3399 AlignmentVal = (unsigned) Val.getZExtValue();
3400 }
3401
3402 switch (Kind) {
3403 case Action::PPK_Default: // pack([n])
3404 PackContext.setAlignment(AlignmentVal);
3405 break;
3406
3407 case Action::PPK_Show: // pack(show)
3408 // Show the current alignment, making sure to show the right value
3409 // for the default.
3410 AlignmentVal = PackContext.getAlignment();
3411 // FIXME: This should come from the target.
3412 if (AlignmentVal == 0)
3413 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003414 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003415 break;
3416
3417 case Action::PPK_Push: // pack(push [, id] [, [n])
3418 PackContext.push(Name);
3419 // Set the new alignment if specified.
3420 if (Alignment)
3421 PackContext.setAlignment(AlignmentVal);
3422 break;
3423
3424 case Action::PPK_Pop: // pack(pop [, id] [, n])
3425 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3426 // "#pragma pack(pop, identifier, n) is undefined"
3427 if (Alignment && Name)
3428 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3429
3430 // Do the pop.
3431 if (!PackContext.pop(Name)) {
3432 // If a name was specified then failure indicates the name
3433 // wasn't found. Otherwise failure indicates the stack was
3434 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003435 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3436 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003437
3438 // FIXME: Warn about popping named records as MSVC does.
3439 } else {
3440 // Pop succeeded, set the new alignment if specified.
3441 if (Alignment)
3442 PackContext.setAlignment(AlignmentVal);
3443 }
3444 break;
3445
3446 default:
3447 assert(0 && "Invalid #pragma pack kind.");
3448 }
3449}
3450
3451bool PragmaPackStack::pop(IdentifierInfo *Name) {
3452 if (Stack.empty())
3453 return false;
3454
3455 // If name is empty just pop top.
3456 if (!Name) {
3457 Alignment = Stack.back().first;
3458 Stack.pop_back();
3459 return true;
3460 }
3461
3462 // Otherwise, find the named record.
3463 for (unsigned i = Stack.size(); i != 0; ) {
3464 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003465 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003466 // Found it, pop up to and including this record.
3467 Alignment = Stack[i].first;
3468 Stack.erase(Stack.begin() + i, Stack.end());
3469 return true;
3470 }
3471 }
3472
3473 return false;
3474}