blob: cf71d394ce97b7fb257fbabf65867f188f838ff6 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6953a072008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000022#include "clang/Basic/SourceManager.h"
23// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000024#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000025#include "clang/Lex/HeaderSearch.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026#include "llvm/ADT/SmallSet.h"
Douglas Gregor39677622008-12-11 20:41:00 +000027#include "llvm/ADT/STLExtras.h"
Douglas Gregor6e71edc2008-12-23 21:05:05 +000028#include <algorithm>
29#include <functional>
Douglas Gregor39677622008-12-11 20:41:00 +000030
Chris Lattner4b009652007-07-25 00:24:17 +000031using namespace clang;
32
Steve Naroff7b36a1b2009-01-28 19:39:02 +000033Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, Scope *S,
34 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000035 DeclContext *DC = 0;
Steve Naroffc349ee22009-01-29 00:07:50 +000036
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000037 if (SS) {
38 if (SS->isInvalid())
39 return 0;
40 DC = static_cast<DeclContext*>(SS->getScopeRep());
41 }
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000042 Decl *IIDecl = 0;
Steve Naroffa4e04982009-01-29 18:09:31 +000043
44 LookupResult Result = DC ? LookupDeclInContext(&II, Decl::IDNS_Ordinary, DC) :
45 LookupDeclInScope(&II, Decl::IDNS_Ordinary, S);
46
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000047 switch (Result.getKind()) {
Steve Naroffa4e04982009-01-29 18:09:31 +000048 case LookupResult::NotFound:
49 case LookupResult::FoundOverloaded:
50 case LookupResult::AmbiguousBaseSubobjectTypes:
51 case LookupResult::AmbiguousBaseSubobjects:
52 // FIXME: In the event of an ambiguous lookup, we could visit all of
53 // the entities found to determine whether they are all types. This
54 // might provide better diagnostics.
55 return 0;
56 case LookupResult::Found:
57 IIDecl = Result.getAsDecl();
58 break;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000059 }
60
Steve Naroffa4e04982009-01-29 18:09:31 +000061 if (IIDecl) {
62 if (isa<TypedefDecl>(IIDecl) ||
63 isa<ObjCInterfaceDecl>(IIDecl) ||
64 isa<TagDecl>(IIDecl) ||
65 isa<TemplateTypeParmDecl>(IIDecl))
66 return IIDecl;
67 }
Steve Naroff81f1bba2007-09-06 21:24:23 +000068 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000069}
70
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000071DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000072 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000073 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000074 if (MD->isOutOfLineDefinition())
75 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000076
77 // A C++ inline method is parsed *after* the topmost class it was declared in
78 // is fully parsed (it's "complete").
79 // The parsing of a C++ inline method happens at the declaration context of
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000080 // the topmost (non-nested) class it is lexically declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000081 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
82 DC = MD->getParent();
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000083 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000084 DC = RD;
85
86 // Return the declaration context of the topmost class the inline method is
87 // declared in.
88 return DC;
89 }
90
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000091 if (isa<ObjCMethodDecl>(DC))
92 return Context.getTranslationUnitDecl();
93
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +000094 if (Decl *D = dyn_cast<Decl>(DC))
95 return D->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000096
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000097 return DC->getLexicalParent();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000098}
99
Douglas Gregor8acb7272008-12-11 16:49:14 +0000100void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000101 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu2c9b8102008-12-08 07:14:51 +0000102 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +0000103 CurContext = DC;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000104 S->setEntity(DC);
Chris Lattnereee57c02008-04-04 06:12:32 +0000105}
106
Chris Lattnerf3874bc2008-04-06 04:47:34 +0000107void Sema::PopDeclContext() {
108 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor8acb7272008-12-11 16:49:14 +0000109
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000110 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +0000111}
112
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000113/// Add this decl to the scope shadowed decl chains.
114void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregord8028382009-01-05 19:45:36 +0000115 // Move up the scope chain until we find the nearest enclosing
116 // non-transparent context. The declaration will be introduced into this
117 // scope.
118 while (S->getEntity() &&
119 ((DeclContext *)S->getEntity())->isTransparentContext())
120 S = S->getParent();
121
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000122 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000123
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000124 // Add scoped declarations into their context, so that they can be
125 // found later. Declarations without a context won't be inserted
126 // into any context.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000127 CurContext->addDecl(D);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000128
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000129 // C++ [basic.scope]p4:
130 // -- exactly one declaration shall declare a class name or
131 // enumeration name that is not a typedef name and the other
132 // declarations shall all refer to the same object or
133 // enumerator, or all refer to functions and function templates;
134 // in this case the class name or enumeration name is hidden.
135 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
136 // We are pushing the name of a tag (enum or class).
Douglas Gregor3a423132009-01-07 16:34:42 +0000137 if (CurContext->getLookupContext()
138 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000139 // We're pushing the tag into the current context, which might
140 // require some reshuffling in the identifier resolver.
141 IdentifierResolver::iterator
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000142 I = IdResolver.begin(TD->getDeclName(), CurContext,
143 false/*LookInParentCtx*/),
144 IEnd = IdResolver.end();
145 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
146 NamedDecl *PrevDecl = *I;
147 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
148 PrevDecl = *I, ++I) {
149 if (TD->declarationReplaces(*I)) {
150 // This is a redeclaration. Remove it from the chain and
151 // break out, so that we'll add in the shadowed
152 // declaration.
153 S->RemoveDecl(*I);
154 if (PrevDecl == *I) {
155 IdResolver.RemoveDecl(*I);
156 IdResolver.AddDecl(TD);
157 return;
158 } else {
159 IdResolver.RemoveDecl(*I);
160 break;
161 }
162 }
163 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000164
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000165 // There is already a declaration with the same name in the same
166 // scope, which is not a tag declaration. It must be found
167 // before we find the new declaration, so insert the new
168 // declaration at the end of the chain.
169 IdResolver.AddShadowedDecl(TD, PrevDecl);
170
171 return;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000172 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000173 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000174 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000175 // We are pushing the name of a function, which might be an
176 // overloaded name.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000177 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor69e781f2009-01-06 23:51:29 +0000178 DeclContext *DC = FD->getDeclContext()->getLookupContext();
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000179 IdentifierResolver::iterator Redecl
Douglas Gregord8028382009-01-05 19:45:36 +0000180 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000181 false/*LookInParentCtx*/),
182 IdResolver.end(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000183 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000184 FD));
185 if (Redecl != IdResolver.end()) {
186 // There is already a declaration of a function on our
187 // IdResolver chain. Replace it with this declaration.
188 S->RemoveDecl(*Redecl);
189 IdResolver.RemoveDecl(*Redecl);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000190 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000191 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000192
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000193 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000194}
195
Steve Naroff9637a9b2007-10-09 22:01:59 +0000196void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000197 if (S->decl_empty()) return;
Douglas Gregordd861062008-12-05 18:15:24 +0000198 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
199 "Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000200
Chris Lattner4b009652007-07-25 00:24:17 +0000201 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
202 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000203 Decl *TmpD = static_cast<Decl*>(*I);
204 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000205
Douglas Gregor8acb7272008-12-11 16:49:14 +0000206 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
207 NamedDecl *D = cast<NamedDecl>(TmpD);
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000208
Douglas Gregor8acb7272008-12-11 16:49:14 +0000209 if (!D->getDeclName()) continue;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000210
Douglas Gregor8acb7272008-12-11 16:49:14 +0000211 // Remove this name from our lexical scope.
212 IdResolver.RemoveDecl(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000213 }
214}
215
Steve Naroffe57c21a2008-04-01 23:04:06 +0000216/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
217/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000218ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000219 // The third "scope" argument is 0 since we aren't enabling lazy built-in
220 // creation from this context.
Steve Naroffc349ee22009-01-29 00:07:50 +0000221 Decl *IDecl = LookupDeclInScope(Id, Decl::IDNS_Ordinary, 0);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000222
Steve Naroff6384a012008-04-02 14:35:35 +0000223 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000224}
225
Douglas Gregor5eca99e2009-01-12 18:45:55 +0000226/// getNonFieldDeclScope - Retrieves the innermost scope, starting
227/// from S, where a non-field would be declared. This routine copes
228/// with the difference between C and C++ scoping rules in structs and
229/// unions. For example, the following code is well-formed in C but
230/// ill-formed in C++:
231/// @code
232/// struct S6 {
233/// enum { BAR } e;
234/// };
235///
236/// void test_S6() {
237/// struct S6 a;
238/// a.e = BAR;
239/// }
240/// @endcode
241/// For the declaration of BAR, this routine will return a different
242/// scope. The scope S will be the scope of the unnamed enumeration
243/// within S6. In C++, this routine will return the scope associated
244/// with S6, because the enumeration's scope is a transparent
245/// context but structures can contain non-field names. In C, this
246/// routine will return the translation unit scope, since the
247/// enumeration's scope is a transparent context and structures cannot
248/// contain non-field names.
249Scope *Sema::getNonFieldDeclScope(Scope *S) {
250 while (((S->getFlags() & Scope::DeclScope) == 0) ||
251 (S->getEntity() &&
252 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
253 (S->isClassScope() && !getLangOptions().CPlusPlus))
254 S = S->getParent();
255 return S;
256}
257
Steve Naroffc349ee22009-01-29 00:07:50 +0000258/// LookupDeclInScope - Look up the inner-most declaration in the specified
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000259/// namespace. NamespaceNameOnly - during lookup only namespace names
260/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
261/// 'When looking up a namespace-name in a using-directive or
262/// namespace-alias-definition, only namespace names are considered.'
Douglas Gregor78d70132009-01-14 22:20:51 +0000263///
264/// Note: The use of this routine is deprecated. Please use
265/// LookupName, LookupQualifiedName, or LookupParsedName instead.
266Sema::LookupResult
Steve Naroffc349ee22009-01-29 00:07:50 +0000267Sema::LookupDeclInScope(DeclarationName Name, unsigned NSI, Scope *S,
268 bool LookInParent) {
Steve Naroffa4e04982009-01-29 18:09:31 +0000269 if (getLangOptions().CPlusPlus) {
270 LookupCriteria::NameKind Kind;
271 if (NSI == Decl::IDNS_Ordinary) {
272 Kind = LookupCriteria::Ordinary;
273 } else if (NSI == Decl::IDNS_Tag)
274 Kind = LookupCriteria::Tag;
275 else {
276 assert(NSI == Decl::IDNS_Member &&"Unable to grok LookupDecl NSI argument");
277 Kind = LookupCriteria::Member;
278 }
279 // Unqualified lookup
280 return LookupName(S, Name,
281 LookupCriteria(Kind, !LookInParent,
282 getLangOptions().CPlusPlus));
Chris Lattner50500f62009-01-16 19:44:00 +0000283 }
Steve Naroffa4e04982009-01-29 18:09:31 +0000284 // Fast path for C/ObjC.
285
286 // Unqualified name lookup in C/Objective-C is purely lexical, so
287 // search in the declarations attached to the name.
288
289 // For the purposes of unqualified name lookup, structs and unions
290 // don't have scopes at all. For example:
291 //
292 // struct X {
293 // struct T { int i; } x;
294 // };
295 //
296 // void f() {
297 // struct T t; // okay: T is defined lexically within X, but
298 // // semantically at global scope
299 // };
300 //
301 // FIXME: Is there a better way to deal with this?
302 DeclContext *SearchCtx = CurContext;
303 while (isa<RecordDecl>(SearchCtx) || isa<EnumDecl>(SearchCtx))
304 SearchCtx = SearchCtx->getParent();
305 IdentifierResolver::iterator I
306 = IdResolver.begin(Name, SearchCtx, LookInParent);
307
308 // Scan up the scope chain looking for a decl that matches this
309 // identifier that is in the appropriate namespace. This search
310 // should not take long, as shadowing of names is uncommon, and
311 // deep shadowing is extremely uncommon.
312 for (; I != IdResolver.end(); ++I) {
313 switch (NSI) {
314 case Decl::IDNS_Ordinary:
315 case Decl::IDNS_Tag:
316 case Decl::IDNS_Member:
317 if ((*I)->isInIdentifierNamespace(NSI))
318 return LookupResult::CreateLookupResult(Context, *I);
319 break;
320 default:
321 assert(0 && "Unable to grok LookupDecl NSI argument");
322 }
323 }
324 if (NSI == Decl::IDNS_Ordinary) {
325 IdentifierInfo *II = Name.getAsIdentifierInfo();
326 if (II) {
327 // If this is a builtin on this (or all) targets, create the decl.
328 if (unsigned BuiltinID = II->getBuiltinID())
329 return LookupResult::CreateLookupResult(Context,
330 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
331 S));
332 }
333 if (getLangOptions().ObjC1 && II) {
334 // @interface and @compatibility_alias introduce typedef-like names.
335 // Unlike typedef's, they can only be introduced at file-scope (and are
336 // therefore not scoped decls). They can, however, be shadowed by
337 // other names in IDNS_Ordinary.
338 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
339 if (IDI != ObjCInterfaceDecls.end())
340 return LookupResult::CreateLookupResult(Context, IDI->second);
341 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
342 if (I != ObjCAliasDecls.end())
343 return LookupResult::CreateLookupResult(Context,
344 I->second->getClassInterface());
345 }
346 }
347 return LookupResult::CreateLookupResult(Context, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000348}
349
Steve Naroffc349ee22009-01-29 00:07:50 +0000350Sema::LookupResult
351Sema::LookupDeclInContext(DeclarationName Name, unsigned NSI,
352 const DeclContext *LookupCtx,
353 bool LookInParent) {
354 assert(LookupCtx && "LookupDeclInContext(): Missing DeclContext");
355 LookupCriteria::NameKind Kind;
356 if (NSI == Decl::IDNS_Ordinary) {
357 Kind = LookupCriteria::Ordinary;
358 } else if (NSI == Decl::IDNS_Tag)
359 Kind = LookupCriteria::Tag;
360 else {
361 assert(NSI == Decl::IDNS_Member &&"Unable to grok LookupDecl NSI argument");
362 Kind = LookupCriteria::Member;
363 }
364 return LookupQualifiedName(const_cast<DeclContext *>(LookupCtx), Name,
365 LookupCriteria(Kind, !LookInParent,
366 getLangOptions().CPlusPlus));
367}
368
Chris Lattnera9c87f22008-05-05 22:18:14 +0000369void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000370 if (!Context.getBuiltinVaListType().isNull())
371 return;
372
373 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffc349ee22009-01-29 00:07:50 +0000374 Decl *VaDecl = LookupDeclInScope(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000375 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000376 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
377}
378
Chris Lattner4b009652007-07-25 00:24:17 +0000379/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
380/// lazily create a decl for it.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000381NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
382 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000383 Builtin::ID BID = (Builtin::ID)bid;
384
Chris Lattnerb23469f2008-09-28 05:54:29 +0000385 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000386 InitBuiltinVaListType();
387
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000388 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000389 FunctionDecl *New = FunctionDecl::Create(Context,
390 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000391 SourceLocation(), II, R,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000392 FunctionDecl::Extern, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000393
Chris Lattnera9c87f22008-05-05 22:18:14 +0000394 // Create Decl objects for each parameter, adding them to the
395 // FunctionDecl.
396 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
397 llvm::SmallVector<ParmVarDecl*, 16> Params;
398 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
399 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000400 FT->getArgType(i), VarDecl::None, 0));
Ted Kremenek8494c962009-01-14 00:42:25 +0000401 New->setParams(Context, &Params[0], Params.size());
Chris Lattnera9c87f22008-05-05 22:18:14 +0000402 }
403
404
405
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000406 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregord394a272009-01-09 18:51:29 +0000407 // FIXME: This is hideous. We need to teach PushOnScopeChains to
408 // relate Scopes to DeclContexts, and probably eliminate CurContext
409 // entirely, but we're not there yet.
410 DeclContext *SavedContext = CurContext;
411 CurContext = Context.getTranslationUnitDecl();
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000412 PushOnScopeChains(New, TUScope);
Douglas Gregord394a272009-01-09 18:51:29 +0000413 CurContext = SavedContext;
Chris Lattner4b009652007-07-25 00:24:17 +0000414 return New;
415}
416
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000417/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
418/// everything from the standard library is defined.
419NamespaceDecl *Sema::GetStdNamespace() {
420 if (!StdNamespace) {
Chris Lattnerf0939602008-11-20 05:45:14 +0000421 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000422 DeclContext *Global = Context.getTranslationUnitDecl();
Steve Naroffc349ee22009-01-29 00:07:50 +0000423 Decl *Std = LookupDeclInContext(StdIdent, Decl::IDNS_Ordinary, Global);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000424 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
425 }
426 return StdNamespace;
427}
428
Chris Lattner4b009652007-07-25 00:24:17 +0000429/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
430/// and scope as a previous declaration 'Old'. Figure out how to resolve this
431/// situation, merging decls or emitting diagnostics as appropriate.
432///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000433TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahaniande939672009-01-16 19:58:32 +0000434 bool objc_types = false;
Steve Naroff453a8782008-09-09 14:32:20 +0000435 // Allow multiple definitions for ObjC built-in typedefs.
436 // FIXME: Verify the underlying types are equivalent!
437 if (getLangOptions().ObjC1) {
Chris Lattner6d16b052008-11-20 05:41:43 +0000438 const IdentifierInfo *TypeID = New->getIdentifier();
439 switch (TypeID->getLength()) {
440 default: break;
441 case 2:
442 if (!TypeID->isStr("id"))
443 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000444 Context.setObjCIdType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000445 objc_types = true;
446 break;
Chris Lattner6d16b052008-11-20 05:41:43 +0000447 case 5:
448 if (!TypeID->isStr("Class"))
449 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000450 Context.setObjCClassType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000451 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000452 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000453 case 3:
454 if (!TypeID->isStr("SEL"))
455 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000456 Context.setObjCSelType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000457 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000458 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000459 case 8:
460 if (!TypeID->isStr("Protocol"))
461 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000462 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahaniande939672009-01-16 19:58:32 +0000463 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000464 return New;
465 }
466 // Fall through - the typedef name was not a builtin type.
467 }
Douglas Gregorb31f2942009-01-28 17:15:10 +0000468 // Verify the old decl was also a type.
469 TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
Chris Lattner4b009652007-07-25 00:24:17 +0000470 if (!Old) {
Douglas Gregorb31f2942009-01-28 17:15:10 +0000471 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000472 << New->getDeclName();
Fariborz Jahaniande939672009-01-16 19:58:32 +0000473 if (!objc_types)
474 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000475 return New;
476 }
Douglas Gregorb31f2942009-01-28 17:15:10 +0000477
478 // Determine the "old" type we'll use for checking and diagnostics.
479 QualType OldType;
480 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
481 OldType = OldTypedef->getUnderlyingType();
482 else
483 OldType = Context.getTypeDeclType(Old);
484
Chris Lattnerbef8d622008-07-25 18:44:27 +0000485 // If the typedef types are not identical, reject them in all languages and
486 // with any extensions enabled.
Douglas Gregorb31f2942009-01-28 17:15:10 +0000487
488 if (OldType != New->getUnderlyingType() &&
489 Context.getCanonicalType(OldType) !=
Chris Lattnerbef8d622008-07-25 18:44:27 +0000490 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner8d756812008-11-20 06:13:02 +0000491 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregorb31f2942009-01-28 17:15:10 +0000492 << New->getUnderlyingType() << OldType;
Fariborz Jahaniande939672009-01-16 19:58:32 +0000493 if (!objc_types)
494 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregord1675382009-01-09 19:42:16 +0000495 return New;
Chris Lattnerbef8d622008-07-25 18:44:27 +0000496 }
Fariborz Jahaniande939672009-01-16 19:58:32 +0000497 if (objc_types) return New;
Eli Friedman324d5032008-06-11 06:20:39 +0000498 if (getLangOptions().Microsoft) return New;
499
Douglas Gregor49ba1b72008-11-21 16:29:06 +0000500 // C++ [dcl.typedef]p2:
501 // In a given non-class scope, a typedef specifier can be used to
502 // redefine the name of any type declared in that scope to refer
503 // to the type to which it already refers.
504 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
505 return New;
506
507 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroffa9eae582008-01-30 23:46:05 +0000508 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
509 // *either* declaration is in a system header. The code below implements
510 // this adhoc compatibility rule. FIXME: The following code will not
511 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000512 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
513 SourceManager &SrcMgr = Context.getSourceManager();
514 if (SrcMgr.isInSystemHeader(Old->getLocation()))
515 return New;
516 if (SrcMgr.isInSystemHeader(New->getLocation()))
517 return New;
518 }
Eli Friedman324d5032008-06-11 06:20:39 +0000519
Chris Lattnerb1753422008-11-23 21:45:46 +0000520 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000521 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000522 return New;
523}
524
Chris Lattner6953a072008-06-26 18:38:35 +0000525/// DeclhasAttr - returns true if decl Declaration already has the target
526/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000527static bool DeclHasAttr(const Decl *decl, const Attr *target) {
528 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
529 if (attr->getKind() == target->getKind())
530 return true;
531
532 return false;
533}
534
535/// MergeAttributes - append attributes from the Old decl to the New one.
536static void MergeAttributes(Decl *New, Decl *Old) {
537 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
538
Chris Lattner402b3372008-03-03 03:28:21 +0000539 while (attr) {
540 tmp = attr;
541 attr = attr->getNext();
542
543 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000544 tmp->setInherited(true);
Chris Lattner402b3372008-03-03 03:28:21 +0000545 New->addAttr(tmp);
546 } else {
547 tmp->setNext(0);
548 delete(tmp);
549 }
550 }
Nuno Lopes77654342008-06-01 22:53:53 +0000551
552 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000553}
554
Chris Lattner3e254fb2008-04-08 04:40:51 +0000555/// MergeFunctionDecl - We just parsed a function 'New' from
556/// declarator D which has the same name and scope as a previous
557/// declaration 'Old'. Figure out how to resolve this situation,
558/// merging decls or emitting diagnostics as appropriate.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000559/// Redeclaration will be set true if this New is a redeclaration OldD.
560///
561/// In C++, New and Old must be declarations that are not
562/// overloaded. Use IsOverload to determine whether New and Old are
563/// overloaded, and to select the Old declaration that New should be
564/// merged with.
Douglas Gregor42214c52008-04-21 02:02:58 +0000565FunctionDecl *
566Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000567 assert(!isa<OverloadedFunctionDecl>(OldD) &&
568 "Cannot merge with an overloaded function declaration");
569
Douglas Gregor42214c52008-04-21 02:02:58 +0000570 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000571 // Verify the old decl was also a function.
572 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
573 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000574 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000575 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000576 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000577 return New;
578 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000579
580 // Determine whether the previous declaration was a definition,
581 // implicit declaration, or a declaration.
582 diag::kind PrevDiag;
583 if (Old->isThisDeclarationADefinition())
Chris Lattner1336cab2008-11-23 23:12:31 +0000584 PrevDiag = diag::note_previous_definition;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000585 else if (Old->isImplicit())
Chris Lattner1336cab2008-11-23 23:12:31 +0000586 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000587 else
Chris Lattner1336cab2008-11-23 23:12:31 +0000588 PrevDiag = diag::note_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000589
Chris Lattner42a21742008-04-06 23:10:54 +0000590 QualType OldQType = Context.getCanonicalType(Old->getType());
591 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000592
Douglas Gregord2baafd2008-10-21 16:13:35 +0000593 if (getLangOptions().CPlusPlus) {
594 // (C++98 13.1p2):
595 // Certain function declarations cannot be overloaded:
596 // -- Function declarations that differ only in the return type
597 // cannot be overloaded.
598 QualType OldReturnType
599 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
600 QualType NewReturnType
601 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
602 if (OldReturnType != NewReturnType) {
603 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
604 Diag(Old->getLocation(), PrevDiag);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000605 Redeclaration = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000606 return New;
607 }
608
609 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
610 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
611 if (OldMethod && NewMethod) {
612 // -- Member function declarations with the same name and the
613 // same parameter types cannot be overloaded if any of them
614 // is a static member function declaration.
615 if (OldMethod->isStatic() || NewMethod->isStatic()) {
616 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
617 Diag(Old->getLocation(), PrevDiag);
618 return New;
619 }
Douglas Gregorb9213832008-12-15 21:24:18 +0000620
621 // C++ [class.mem]p1:
622 // [...] A member shall not be declared twice in the
623 // member-specification, except that a nested class or member
624 // class template can be declared and then later defined.
625 if (OldMethod->getLexicalDeclContext() ==
626 NewMethod->getLexicalDeclContext()) {
627 unsigned NewDiag;
628 if (isa<CXXConstructorDecl>(OldMethod))
629 NewDiag = diag::err_constructor_redeclared;
630 else if (isa<CXXDestructorDecl>(NewMethod))
631 NewDiag = diag::err_destructor_redeclared;
632 else if (isa<CXXConversionDecl>(NewMethod))
633 NewDiag = diag::err_conv_function_redeclared;
634 else
635 NewDiag = diag::err_member_redeclared;
636
637 Diag(New->getLocation(), NewDiag);
638 Diag(Old->getLocation(), PrevDiag);
639 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000640 }
641
642 // (C++98 8.3.5p3):
643 // All declarations for a function shall agree exactly in both the
644 // return type and the parameter-type-list.
645 if (OldQType == NewQType) {
646 // We have a redeclaration.
647 MergeAttributes(New, Old);
648 Redeclaration = true;
649 return MergeCXXFunctionDecl(New, Old);
650 }
651
652 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000653 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000654
655 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000656 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000657 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000658 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000659 MergeAttributes(New, Old);
660 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000661 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000662 }
Chris Lattner1470b072007-11-06 06:07:26 +0000663
Steve Naroff6c9e7922008-01-16 15:01:34 +0000664 // A function that has already been declared has been redeclared or defined
665 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000666
Chris Lattner4b009652007-07-25 00:24:17 +0000667 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
668 // TODO: This is totally simplistic. It should handle merging functions
669 // together etc, merging extern int X; int X; ...
Chris Lattner271d4c22008-11-24 05:29:24 +0000670 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff6c9e7922008-01-16 15:01:34 +0000671 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000672 return New;
673}
674
Steve Naroffb5e78152008-08-08 17:50:35 +0000675/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000676static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000677 if (VD->isFileVarDecl())
678 return (!VD->getInit() &&
679 (VD->getStorageClass() == VarDecl::None ||
680 VD->getStorageClass() == VarDecl::Static));
681 return false;
682}
683
684/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
685/// when dealing with C "tentative" external object definitions (C99 6.9.2).
686void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
687 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000688 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000689
Douglas Gregor3a423132009-01-07 16:34:42 +0000690 // FIXME: I don't think this will actually see all of the
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000691 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffb5e78152008-08-08 17:50:35 +0000692 for (IdentifierResolver::iterator
693 I = IdResolver.begin(VD->getIdentifier(),
694 VD->getDeclContext(), false/*LookInParentCtx*/),
695 E = IdResolver.end(); I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000696 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000697 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
698
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000699 // Handle the following case:
700 // int a[10];
701 // int a[]; - the code below makes sure we set the correct type.
702 // int a[11]; - this is an error, size isn't 10.
703 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
704 OldDecl->getType()->isConstantArrayType())
705 VD->setType(OldDecl->getType());
706
Steve Naroffb5e78152008-08-08 17:50:35 +0000707 // Check for "tentative" definitions. We can't accomplish this in
708 // MergeVarDecl since the initializer hasn't been attached.
709 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
710 continue;
711
712 // Handle __private_extern__ just like extern.
713 if (OldDecl->getStorageClass() != VarDecl::Extern &&
714 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
715 VD->getStorageClass() != VarDecl::Extern &&
716 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000717 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000718 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffb5e78152008-08-08 17:50:35 +0000719 }
720 }
721 }
722}
723
Chris Lattner4b009652007-07-25 00:24:17 +0000724/// MergeVarDecl - We just parsed a variable 'New' which has the same name
725/// and scope as a previous declaration 'Old'. Figure out how to resolve this
726/// situation, merging decls or emitting diagnostics as appropriate.
727///
Steve Naroffb5e78152008-08-08 17:50:35 +0000728/// Tentative definition rules (C99 6.9.2p2) are checked by
729/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
730/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000731///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000732VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000733 // Verify the old decl was also a variable.
734 VarDecl *Old = dyn_cast<VarDecl>(OldD);
735 if (!Old) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000736 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000737 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000738 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000739 return New;
740 }
Chris Lattner402b3372008-03-03 03:28:21 +0000741
742 MergeAttributes(New, Old);
743
Eli Friedman4a480d62009-01-24 23:49:55 +0000744 // Merge the types
745 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
746 if (MergedT.isNull()) {
Douglas Gregord1675382009-01-09 19:42:16 +0000747 Diag(New->getLocation(), diag::err_redefinition_different_type)
748 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000749 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000750 return New;
751 }
Eli Friedman4a480d62009-01-24 23:49:55 +0000752 New->setType(MergedT);
Steve Naroffb00247f2008-01-30 00:44:01 +0000753 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
754 if (New->getStorageClass() == VarDecl::Static &&
755 (Old->getStorageClass() == VarDecl::None ||
756 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000757 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000758 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000759 return New;
760 }
761 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
762 if (New->getStorageClass() != VarDecl::Static &&
763 Old->getStorageClass() == VarDecl::Static) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000764 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000765 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000766 return New;
767 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000768 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
769 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000770 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000771 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000772 }
773 return New;
774}
775
Chris Lattner3e254fb2008-04-08 04:40:51 +0000776/// CheckParmsForFunctionDef - Check that the parameters of the given
777/// function are appropriate for the definition of a function. This
778/// takes care of any checks that cannot be performed on the
779/// declaration itself, e.g., that the types of each of the function
780/// parameters are complete.
781bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
782 bool HasInvalidParm = false;
783 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
784 ParmVarDecl *Param = FD->getParamDecl(p);
785
786 // C99 6.7.5.3p4: the parameters in a parameter type list in a
787 // function declarator that is part of a function definition of
788 // that function shall not have incomplete type.
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000789 if (!Param->isInvalidDecl() &&
790 DiagnoseIncompleteType(Param->getLocation(), Param->getType(),
791 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000792 Param->setInvalidDecl();
793 HasInvalidParm = true;
794 }
Chris Lattnerb0b42f62008-12-17 07:32:46 +0000795
796 // C99 6.9.1p5: If the declarator includes a parameter type list, the
797 // declaration of each parameter shall include an identifier.
798 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
799 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000800 }
801
802 return HasInvalidParm;
803}
804
Chris Lattner4b009652007-07-25 00:24:17 +0000805/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
806/// no declarator (e.g. "struct foo;") is parsed.
807Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregorb748fc52009-01-12 22:49:06 +0000808 TagDecl *Tag
809 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
810 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
811 if (!Record->getDeclName() && Record->isDefinition() &&
812 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
813 return BuildAnonymousStructOrUnion(S, DS, Record);
814
815 // Microsoft allows unnamed struct/union fields. Don't complain
816 // about them.
817 // FIXME: Should we support Microsoft's extensions in this area?
818 if (Record->getDeclName() && getLangOptions().Microsoft)
819 return Tag;
820 }
821
Sebastian Redlb7605e82008-12-28 15:28:59 +0000822 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregoredd94e92009-01-22 16:23:54 +0000823 // Warn about typedefs of enums without names, since this is an
824 // extension in both Microsoft an GNU.
Douglas Gregor72de8492009-01-17 02:55:50 +0000825 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
826 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregoredd94e92009-01-22 16:23:54 +0000827 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregor80c720e2009-01-13 23:10:51 +0000828 << DS.getSourceRange();
829 return Tag;
830 }
831
Sebastian Redlb7605e82008-12-28 15:28:59 +0000832 // FIXME: This diagnostic is emitted even when various previous
833 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
834 // DeclSpec has no means of communicating this information, and the
835 // responsible parser functions are quite far apart.
836 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
837 << DS.getSourceRange();
838 return 0;
839 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000840
Douglas Gregor723d3332009-01-07 00:43:41 +0000841 return Tag;
842}
843
844/// InjectAnonymousStructOrUnionMembers - Inject the members of the
845/// anonymous struct or union AnonRecord into the owning context Owner
846/// and scope S. This routine will be invoked just after we realize
847/// that an unnamed union or struct is actually an anonymous union or
848/// struct, e.g.,
849///
850/// @code
851/// union {
852/// int i;
853/// float f;
854/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
855/// // f into the surrounding scope.x
856/// @endcode
857///
858/// This routine is recursive, injecting the names of nested anonymous
859/// structs/unions into the owning context and scope as well.
860bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
861 RecordDecl *AnonRecord) {
862 bool Invalid = false;
863 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
864 FEnd = AnonRecord->field_end();
865 F != FEnd; ++F) {
866 if ((*F)->getDeclName()) {
Steve Naroffc349ee22009-01-29 00:07:50 +0000867 Decl *PrevDecl = LookupDeclInContext((*F)->getDeclName(),
868 Decl::IDNS_Ordinary, Owner, false);
Douglas Gregor723d3332009-01-07 00:43:41 +0000869 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
870 // C++ [class.union]p2:
871 // The names of the members of an anonymous union shall be
872 // distinct from the names of any other entity in the
873 // scope in which the anonymous union is declared.
874 unsigned diagKind
875 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
876 : diag::err_anonymous_struct_member_redecl;
877 Diag((*F)->getLocation(), diagKind)
878 << (*F)->getDeclName();
879 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
880 Invalid = true;
881 } else {
882 // C++ [class.union]p2:
883 // For the purpose of name lookup, after the anonymous union
884 // definition, the members of the anonymous union are
885 // considered to have been defined in the scope in which the
886 // anonymous union is declared.
Douglas Gregor9ac66d22009-01-20 16:54:50 +0000887 Owner->makeDeclVisibleInContext(*F);
Douglas Gregor723d3332009-01-07 00:43:41 +0000888 S->AddDecl(*F);
889 IdResolver.AddDecl(*F);
890 }
891 } else if (const RecordType *InnerRecordType
892 = (*F)->getType()->getAsRecordType()) {
893 RecordDecl *InnerRecord = InnerRecordType->getDecl();
894 if (InnerRecord->isAnonymousStructOrUnion())
895 Invalid = Invalid ||
896 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
897 }
898 }
899
900 return Invalid;
901}
902
903/// ActOnAnonymousStructOrUnion - Handle the declaration of an
904/// anonymous structure or union. Anonymous unions are a C++ feature
905/// (C++ [class.union]) and a GNU C extension; anonymous structures
906/// are a GNU C and GNU C++ extension.
907Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
908 RecordDecl *Record) {
909 DeclContext *Owner = Record->getDeclContext();
910
911 // Diagnose whether this anonymous struct/union is an extension.
912 if (Record->isUnion() && !getLangOptions().CPlusPlus)
913 Diag(Record->getLocation(), diag::ext_anonymous_union);
914 else if (!Record->isUnion())
915 Diag(Record->getLocation(), diag::ext_anonymous_struct);
916
917 // C and C++ require different kinds of checks for anonymous
918 // structs/unions.
919 bool Invalid = false;
920 if (getLangOptions().CPlusPlus) {
921 const char* PrevSpec = 0;
922 // C++ [class.union]p3:
923 // Anonymous unions declared in a named namespace or in the
924 // global namespace shall be declared static.
925 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
926 (isa<TranslationUnitDecl>(Owner) ||
927 (isa<NamespaceDecl>(Owner) &&
928 cast<NamespaceDecl>(Owner)->getDeclName()))) {
929 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
930 Invalid = true;
931
932 // Recover by adding 'static'.
933 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
934 }
935 // C++ [class.union]p3:
936 // A storage class is not allowed in a declaration of an
937 // anonymous union in a class scope.
938 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
939 isa<RecordDecl>(Owner)) {
940 Diag(DS.getStorageClassSpecLoc(),
941 diag::err_anonymous_union_with_storage_spec);
942 Invalid = true;
943
944 // Recover by removing the storage specifier.
945 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
946 PrevSpec);
947 }
Douglas Gregorc7f01612009-01-07 19:46:03 +0000948
949 // C++ [class.union]p2:
950 // The member-specification of an anonymous union shall only
951 // define non-static data members. [Note: nested types and
952 // functions cannot be declared within an anonymous union. ]
953 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
954 MemEnd = Record->decls_end();
955 Mem != MemEnd; ++Mem) {
956 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
957 // C++ [class.union]p3:
958 // An anonymous union shall not have private or protected
959 // members (clause 11).
960 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
961 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
962 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
963 Invalid = true;
964 }
965 } else if ((*Mem)->isImplicit()) {
966 // Any implicit members are fine.
967 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
968 if (!MemRecord->isAnonymousStructOrUnion() &&
969 MemRecord->getDeclName()) {
970 // This is a nested type declaration.
971 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
972 << (int)Record->isUnion();
973 Invalid = true;
974 }
975 } else {
976 // We have something that isn't a non-static data
977 // member. Complain about it.
978 unsigned DK = diag::err_anonymous_record_bad_member;
979 if (isa<TypeDecl>(*Mem))
980 DK = diag::err_anonymous_record_with_type;
981 else if (isa<FunctionDecl>(*Mem))
982 DK = diag::err_anonymous_record_with_function;
983 else if (isa<VarDecl>(*Mem))
984 DK = diag::err_anonymous_record_with_static;
985 Diag((*Mem)->getLocation(), DK)
986 << (int)Record->isUnion();
987 Invalid = true;
988 }
989 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000990 } else {
991 // FIXME: Check GNU C semantics
Douglas Gregorb748fc52009-01-12 22:49:06 +0000992 if (Record->isUnion() && !Owner->isRecord()) {
993 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
994 << (int)getLangOptions().CPlusPlus;
995 Invalid = true;
996 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000997 }
998
999 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorb748fc52009-01-12 22:49:06 +00001000 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1001 << (int)getLangOptions().CPlusPlus;
Douglas Gregor723d3332009-01-07 00:43:41 +00001002 Invalid = true;
1003 }
1004
1005 // Create a declaration for this anonymous struct/union.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001006 NamedDecl *Anon = 0;
Douglas Gregor723d3332009-01-07 00:43:41 +00001007 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1008 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1009 /*IdentifierInfo=*/0,
1010 Context.getTypeDeclType(Record),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001011 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001012 Anon->setAccess(AS_public);
1013 if (getLangOptions().CPlusPlus)
1014 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor723d3332009-01-07 00:43:41 +00001015 } else {
1016 VarDecl::StorageClass SC;
1017 switch (DS.getStorageClassSpec()) {
1018 default: assert(0 && "Unknown storage class!");
1019 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1020 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1021 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1022 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1023 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1024 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1025 case DeclSpec::SCS_mutable:
1026 // mutable can only appear on non-static class members, so it's always
1027 // an error here
1028 Diag(Record->getLocation(), diag::err_mutable_nonmember);
1029 Invalid = true;
1030 SC = VarDecl::None;
1031 break;
1032 }
1033
1034 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1035 /*IdentifierInfo=*/0,
1036 Context.getTypeDeclType(Record),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001037 SC, DS.getSourceRange().getBegin());
Douglas Gregor723d3332009-01-07 00:43:41 +00001038 }
Douglas Gregorc7f01612009-01-07 19:46:03 +00001039 Anon->setImplicit();
Douglas Gregor723d3332009-01-07 00:43:41 +00001040
1041 // Add the anonymous struct/union object to the current
1042 // context. We'll be referencing this object when we refer to one of
1043 // its members.
Douglas Gregor03b2ad22009-01-12 23:27:07 +00001044 Owner->addDecl(Anon);
Douglas Gregor723d3332009-01-07 00:43:41 +00001045
1046 // Inject the members of the anonymous struct/union into the owning
1047 // context and into the identifier resolver chain for name lookup
1048 // purposes.
Douglas Gregorb748fc52009-01-12 22:49:06 +00001049 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1050 Invalid = true;
Douglas Gregor723d3332009-01-07 00:43:41 +00001051
1052 // Mark this as an anonymous struct/union type. Note that we do not
1053 // do this until after we have already checked and injected the
1054 // members of this anonymous struct/union type, because otherwise
1055 // the members could be injected twice: once by DeclContext when it
1056 // builds its lookup table, and once by
1057 // InjectAnonymousStructOrUnionMembers.
1058 Record->setAnonymousStructOrUnion(true);
1059
1060 if (Invalid)
1061 Anon->setInvalidDecl();
1062
1063 return Anon;
Chris Lattner4b009652007-07-25 00:24:17 +00001064}
1065
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001066bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
1067 bool DirectInit) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001068 // Get the type before calling CheckSingleAssignmentConstraints(), since
1069 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +00001070 QualType InitType = Init->getType();
Douglas Gregor6fd35572008-12-19 17:40:08 +00001071
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001072 if (getLangOptions().CPlusPlus) {
1073 // FIXME: I dislike this error message. A lot.
1074 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
1075 return Diag(Init->getSourceRange().getBegin(),
1076 diag::err_typecheck_convert_incompatible)
1077 << DeclType << Init->getType() << "initializing"
1078 << Init->getSourceRange();
1079
1080 return false;
1081 }
Douglas Gregor6fd35572008-12-19 17:40:08 +00001082
Chris Lattner005ed752008-01-04 18:04:52 +00001083 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1084 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1085 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +00001086}
1087
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001088bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001089 const ArrayType *AT = Context.getAsArrayType(DeclT);
1090
1091 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001092 // C99 6.7.8p14. We have an array of character type with unknown size
1093 // being initialized to a string literal.
1094 llvm::APSInt ConstVal(32);
1095 ConstVal = strLiteral->getByteLength() + 1;
1096 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +00001097 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001098 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +00001099 } else {
1100 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001101 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +00001102 // FIXME: Avoid truncation for 64-bit length strings.
1103 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001104 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00001105 diag::warn_initializer_string_for_char_array_too_long)
1106 << strLiteral->getSourceRange();
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001107 }
1108 // Set type from "char *" to "constant array of char".
1109 strLiteral->setType(DeclT);
1110 // For now, we always return false (meaning success).
1111 return false;
1112}
1113
1114StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001115 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +00001116 if (AT && AT->getElementType()->isCharType()) {
Anders Carlsson37704be2009-01-24 17:47:50 +00001117 return dyn_cast<StringLiteral>(Init->IgnoreParens());
Steve Narofff3cb5142008-01-25 00:51:06 +00001118 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001119 return 0;
1120}
1121
Douglas Gregor6428e762008-11-05 15:29:30 +00001122bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1123 SourceLocation InitLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001124 DeclarationName InitEntity,
1125 bool DirectInit) {
Douglas Gregorf1ae3e02008-12-18 21:49:58 +00001126 if (DeclType->isDependentType() || Init->isTypeDependent())
1127 return false;
1128
Douglas Gregor81c29152008-10-29 00:13:59 +00001129 // C++ [dcl.init.ref]p1:
Sebastian Redl51504af2008-11-24 20:06:50 +00001130 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor81c29152008-10-29 00:13:59 +00001131 // (8.3.2), shall be initialized by an object, or function, of
1132 // type T or by an object that can be converted into a T.
1133 if (DeclType->isReferenceType())
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001134 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor81c29152008-10-29 00:13:59 +00001135
Steve Naroff8e9337f2008-01-21 23:53:58 +00001136 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1137 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +00001138 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattner9d2cf082008-11-19 05:27:50 +00001139 return Diag(InitLoc, diag::err_variable_object_no_init)
1140 << VAT->getSizeExpr()->getSourceRange();
Steve Naroff8e9337f2008-01-21 23:53:58 +00001141
Steve Naroffcb69fb72007-12-10 22:44:33 +00001142 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1143 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001144 // FIXME: Handle wide strings
1145 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1146 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +00001147
Douglas Gregor6428e762008-11-05 15:29:30 +00001148 // C++ [dcl.init]p14:
1149 // -- If the destination type is a (possibly cv-qualified) class
1150 // type:
1151 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1152 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1153 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1154
1155 // -- If the initialization is direct-initialization, or if it is
1156 // copy-initialization where the cv-unqualified version of the
1157 // source type is the same class as, or a derived class of, the
1158 // class of the destination, constructors are considered.
1159 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1160 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1161 CXXConstructorDecl *Constructor
1162 = PerformInitializationByConstructor(DeclType, &Init, 1,
1163 InitLoc, Init->getSourceRange(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001164 InitEntity,
1165 DirectInit? IK_Direct : IK_Copy);
Douglas Gregor6428e762008-11-05 15:29:30 +00001166 return Constructor == 0;
1167 }
1168
1169 // -- Otherwise (i.e., for the remaining copy-initialization
1170 // cases), user-defined conversion sequences that can
1171 // convert from the source type to the destination type or
1172 // (when a conversion function is used) to a derived class
1173 // thereof are enumerated as described in 13.3.1.4, and the
1174 // best one is chosen through overload resolution
1175 // (13.3). If the conversion cannot be done or is
1176 // ambiguous, the initialization is ill-formed. The
1177 // function selected is called with the initializer
1178 // expression as its argument; if the function is a
1179 // constructor, the call initializes a temporary of the
1180 // destination type.
1181 // FIXME: We're pretending to do copy elision here; return to
1182 // this when we have ASTs for such things.
Douglas Gregor6fd35572008-12-19 17:40:08 +00001183 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregor6428e762008-11-05 15:29:30 +00001184 return false;
Chris Lattner70b93d82008-11-18 22:52:51 +00001185
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001186 if (InitEntity)
1187 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1188 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1189 << Init->getType() << Init->getSourceRange();
1190 else
1191 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1192 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1193 << Init->getType() << Init->getSourceRange();
Douglas Gregor6428e762008-11-05 15:29:30 +00001194 }
1195
Steve Naroffb2f72412008-09-29 20:07:05 +00001196 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +00001197 if (DeclType->isArrayType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001198 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1199 << Init->getSourceRange();
Eli Friedman65280992008-02-08 00:48:24 +00001200
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001201 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregor15e04622008-11-05 16:20:31 +00001202 } else if (getLangOptions().CPlusPlus) {
1203 // C++ [dcl.init]p14:
1204 // [...] If the class is an aggregate (8.5.1), and the initializer
1205 // is a brace-enclosed list, see 8.5.1.
1206 //
1207 // Note: 8.5.1 is handled below; here, we diagnose the case where
1208 // we have an initializer list and a destination type that is not
1209 // an aggregate.
1210 // FIXME: In C++0x, this is yet another form of initialization.
1211 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1212 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1213 if (!ClassDecl->isAggregate())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001214 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001215 << DeclType << Init->getSourceRange();
Douglas Gregor15e04622008-11-05 16:20:31 +00001216 }
Steve Naroffcb69fb72007-12-10 22:44:33 +00001217 }
Eli Friedman38b7a912008-06-06 19:40:52 +00001218
Douglas Gregor849afc32009-01-29 00:45:39 +00001219 bool hadError = CheckInitList(InitList, DeclType);
1220 Init = InitList;
1221 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +00001222}
1223
Douglas Gregor6704b312008-11-17 22:58:34 +00001224/// GetNameForDeclarator - Determine the full declaration name for the
1225/// given Declarator.
1226DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1227 switch (D.getKind()) {
1228 case Declarator::DK_Abstract:
1229 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1230 return DeclarationName();
1231
1232 case Declarator::DK_Normal:
1233 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1234 return DeclarationName(D.getIdentifier());
1235
1236 case Declarator::DK_Constructor: {
1237 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1238 Ty = Context.getCanonicalType(Ty);
1239 return Context.DeclarationNames.getCXXConstructorName(Ty);
1240 }
1241
1242 case Declarator::DK_Destructor: {
1243 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1244 Ty = Context.getCanonicalType(Ty);
1245 return Context.DeclarationNames.getCXXDestructorName(Ty);
1246 }
1247
1248 case Declarator::DK_Conversion: {
1249 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1250 Ty = Context.getCanonicalType(Ty);
1251 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1252 }
Douglas Gregor96a32dd2008-11-18 14:39:36 +00001253
1254 case Declarator::DK_Operator:
1255 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1256 return Context.DeclarationNames.getCXXOperatorName(
1257 D.getOverloadedOperator());
Douglas Gregor6704b312008-11-17 22:58:34 +00001258 }
1259
1260 assert(false && "Unknown name kind");
1261 return DeclarationName();
1262}
1263
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001264/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1265/// functions Declaration and Definition are "nearly" matching. This
1266/// heuristic is used to improve diagnostics in the case where an
1267/// out-of-line member function definition doesn't match any
1268/// declaration within the class.
1269static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1270 FunctionDecl *Declaration,
1271 FunctionDecl *Definition) {
1272 if (Declaration->param_size() != Definition->param_size())
1273 return false;
1274 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1275 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1276 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1277
1278 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1279 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1280 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1281 return false;
1282 }
1283
1284 return true;
1285}
1286
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001287Sema::DeclTy *
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001288Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1289 bool IsFunctionDefinition) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001290 NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl);
Douglas Gregor6704b312008-11-17 22:58:34 +00001291 DeclarationName Name = GetNameForDeclarator(D);
1292
Chris Lattner4b009652007-07-25 00:24:17 +00001293 // All of these full declarators require an identifier. If it doesn't have
1294 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor6704b312008-11-17 22:58:34 +00001295 if (!Name) {
Chris Lattnercd61d592008-11-11 06:13:16 +00001296 if (!D.getInvalidType()) // Reject this if we think it is valid.
1297 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001298 diag::err_declarator_need_ident)
1299 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001300 return 0;
1301 }
1302
Chris Lattnera7549902007-08-26 06:24:45 +00001303 // The scope passed in may not be a decl scope. Zip up the scope tree until
1304 // we find one that is.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001305 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1306 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattnera7549902007-08-26 06:24:45 +00001307 S = S->getParent();
1308
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001309 DeclContext *DC;
1310 Decl *PrevDecl;
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001311 NamedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001312 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +00001313
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001314 // See if this is a redefinition of a variable in the same scope.
1315 if (!D.getCXXScopeSpec().isSet()) {
1316 DC = CurContext;
Steve Naroffc349ee22009-01-29 00:07:50 +00001317 PrevDecl = LookupDeclInScope(Name, Decl::IDNS_Ordinary, S);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001318 } else { // Something like "int foo::x;"
1319 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Steve Naroffc349ee22009-01-29 00:07:50 +00001320 PrevDecl = DC ? LookupDeclInContext(Name, Decl::IDNS_Ordinary, DC)
1321 : LookupDeclInScope(Name, Decl::IDNS_Ordinary, S);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001322
1323 // C++ 7.3.1.2p2:
1324 // Members (including explicit specializations of templates) of a named
1325 // namespace can also be defined outside that namespace by explicit
1326 // qualification of the name being defined, provided that the entity being
1327 // defined was already declared in the namespace and the definition appears
1328 // after the point of declaration in a namespace that encloses the
1329 // declarations namespace.
1330 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001331 // Note that we only check the context at this point. We don't yet
1332 // have enough information to make sure that PrevDecl is actually
1333 // the declaration we want to match. For example, given:
1334 //
Douglas Gregor98341042008-12-12 08:25:50 +00001335 // class X {
1336 // void f();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001337 // void f(float);
Douglas Gregor98341042008-12-12 08:25:50 +00001338 // };
1339 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001340 // void X::f(int) { } // ill-formed
1341 //
1342 // In this case, PrevDecl will point to the overload set
1343 // containing the two f's declared in X, but neither of them
1344 // matches.
1345 if (!CurContext->Encloses(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001346 // The qualifying scope doesn't enclose the original declaration.
1347 // Emit diagnostic based on current scope.
1348 SourceLocation L = D.getIdentifierLoc();
1349 SourceRange R = D.getCXXScopeSpec().getRange();
1350 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner254de7d2008-11-23 20:28:15 +00001351 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001352 } else {
Chris Lattner254de7d2008-11-23 20:28:15 +00001353 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattner271d4c22008-11-24 05:29:24 +00001354 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001355 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001356 InvalidDecl = true;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001357 }
1358 }
1359
Douglas Gregor2715a1f2008-12-08 18:40:42 +00001360 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00001361 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001362 InvalidDecl = InvalidDecl
1363 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +00001364 // Just pretend that we didn't see the previous declaration.
1365 PrevDecl = 0;
1366 }
1367
Douglas Gregor1d661552008-04-13 21:07:44 +00001368 // In C++, the previous declaration we find might be a tag type
1369 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorb31f2942009-01-28 17:15:10 +00001370 // tag type. Note that this does does not apply if we're declaring a
1371 // typedef (C++ [dcl.typedef]p4).
1372 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1373 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
Douglas Gregor1d661552008-04-13 21:07:44 +00001374 PrevDecl = 0;
1375
Chris Lattner82bb4792007-11-14 06:34:38 +00001376 QualType R = GetTypeForDeclarator(D, S);
1377 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1378
Chris Lattner4b009652007-07-25 00:24:17 +00001379 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001380 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1381 InvalidDecl);
Chris Lattner82bb4792007-11-14 06:34:38 +00001382 } else if (R.getTypePtr()->isFunctionType()) {
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001383 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1384 IsFunctionDefinition, InvalidDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001385 } else {
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001386 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1387 InvalidDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001388 }
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001389
1390 if (New == 0)
1391 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001392
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001393 // Set the lexical context. If the declarator has a C++ scope specifier, the
1394 // lexical context will be different from the semantic context.
1395 New->setLexicalDeclContext(CurContext);
1396
Chris Lattner4b009652007-07-25 00:24:17 +00001397 // If this has an identifier, add it to the scope stack.
Douglas Gregor6704b312008-11-17 22:58:34 +00001398 if (Name)
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001399 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001400 // If any semantic error occurred, mark the decl as invalid.
1401 if (D.getInvalidType() || InvalidDecl)
1402 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001403
1404 return New;
1405}
1406
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001407NamedDecl*
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001408Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001409 QualType R, Decl* LastDeclarator,
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001410 Decl* PrevDecl, bool& InvalidDecl) {
1411 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1412 if (D.getCXXScopeSpec().isSet()) {
1413 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1414 << D.getCXXScopeSpec().getRange();
1415 InvalidDecl = true;
1416 // Pretend we didn't see the scope specifier.
1417 DC = 0;
1418 }
1419
1420 // Check that there are no default arguments (C++ only).
1421 if (getLangOptions().CPlusPlus)
1422 CheckExtraCXXDefaultArguments(D);
1423
1424 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1425 if (!NewTD) return 0;
1426
1427 // Handle attributes prior to checking for duplicates in MergeVarDecl
1428 ProcessDeclAttributes(NewTD, D);
1429 // Merge the decl with the existing one if appropriate. If the decl is
1430 // in an outer scope, it isn't the same thing.
1431 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1432 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1433 if (NewTD == 0) return 0;
1434 }
1435
1436 if (S->getFnParent() == 0) {
1437 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1438 // then it shall have block scope.
1439 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1440 if (NewTD->getUnderlyingType()->isVariableArrayType())
1441 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1442 else
1443 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1444
1445 InvalidDecl = true;
1446 }
1447 }
1448 return NewTD;
1449}
1450
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001451NamedDecl*
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001452Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001453 QualType R, Decl* LastDeclarator,
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001454 Decl* PrevDecl, bool& InvalidDecl) {
1455 DeclarationName Name = GetNameForDeclarator(D);
1456
1457 // Check that there are no default arguments (C++ only).
1458 if (getLangOptions().CPlusPlus)
1459 CheckExtraCXXDefaultArguments(D);
1460
1461 if (R.getTypePtr()->isObjCInterfaceType()) {
1462 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1463 << D.getIdentifier();
1464 InvalidDecl = true;
1465 }
1466
1467 VarDecl *NewVD;
1468 VarDecl::StorageClass SC;
1469 switch (D.getDeclSpec().getStorageClassSpec()) {
1470 default: assert(0 && "Unknown storage class!");
1471 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1472 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1473 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1474 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1475 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1476 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1477 case DeclSpec::SCS_mutable:
1478 // mutable can only appear on non-static class members, so it's always
1479 // an error here
1480 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1481 InvalidDecl = true;
1482 SC = VarDecl::None;
1483 break;
1484 }
1485
1486 IdentifierInfo *II = Name.getAsIdentifierInfo();
1487 if (!II) {
1488 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1489 << Name.getAsString();
1490 return 0;
1491 }
1492
1493 if (DC->isRecord()) {
1494 // This is a static data member for a C++ class.
1495 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1496 D.getIdentifierLoc(), II,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001497 R);
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001498 } else {
1499 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1500 if (S->getFnParent() == 0) {
1501 // C99 6.9p2: The storage-class specifiers auto and register shall not
1502 // appear in the declaration specifiers in an external declaration.
1503 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1504 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1505 InvalidDecl = true;
1506 }
1507 }
1508 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001509 II, R, SC,
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001510 // FIXME: Move to DeclGroup...
1511 D.getDeclSpec().getSourceRange().getBegin());
1512 NewVD->setThreadSpecified(ThreadSpecified);
1513 }
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001514 NewVD->setNextDeclarator(LastDeclarator);
1515
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001516 // Handle attributes prior to checking for duplicates in MergeVarDecl
1517 ProcessDeclAttributes(NewVD, D);
1518
1519 // Handle GNU asm-label extension (encoded as an attribute).
1520 if (Expr *E = (Expr*) D.getAsmLabel()) {
1521 // The parser guarantees this is a string.
1522 StringLiteral *SE = cast<StringLiteral>(E);
1523 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1524 SE->getByteLength())));
1525 }
1526
1527 // Emit an error if an address space was applied to decl with local storage.
1528 // This includes arrays of objects with address space qualifiers, but not
1529 // automatic variables that point to other address spaces.
1530 // ISO/IEC TR 18037 S5.1.2
1531 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1532 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1533 InvalidDecl = true;
1534 }
1535 // Merge the decl with the existing one if appropriate. If the decl is
1536 // in an outer scope, it isn't the same thing.
1537 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1538 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1539 // The user tried to define a non-static data member
1540 // out-of-line (C++ [dcl.meaning]p1).
1541 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1542 << D.getCXXScopeSpec().getRange();
1543 NewVD->Destroy(Context);
1544 return 0;
1545 }
1546
1547 NewVD = MergeVarDecl(NewVD, PrevDecl);
1548 if (NewVD == 0) return 0;
1549
1550 if (D.getCXXScopeSpec().isSet()) {
1551 // No previous declaration in the qualifying scope.
1552 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1553 << Name << D.getCXXScopeSpec().getRange();
1554 InvalidDecl = true;
1555 }
1556 }
1557 return NewVD;
1558}
1559
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001560NamedDecl*
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001561Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001562 QualType R, Decl *LastDeclarator,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001563 Decl* PrevDecl, bool IsFunctionDefinition,
1564 bool& InvalidDecl) {
1565 assert(R.getTypePtr()->isFunctionType());
1566
1567 DeclarationName Name = GetNameForDeclarator(D);
1568 FunctionDecl::StorageClass SC = FunctionDecl::None;
1569 switch (D.getDeclSpec().getStorageClassSpec()) {
1570 default: assert(0 && "Unknown storage class!");
1571 case DeclSpec::SCS_auto:
1572 case DeclSpec::SCS_register:
1573 case DeclSpec::SCS_mutable:
1574 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1575 InvalidDecl = true;
1576 break;
1577 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1578 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1579 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
1580 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1581 }
1582
1583 bool isInline = D.getDeclSpec().isInlineSpecified();
1584 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1585 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1586
1587 FunctionDecl *NewFD;
1588 if (D.getKind() == Declarator::DK_Constructor) {
1589 // This is a C++ constructor declaration.
1590 assert(DC->isRecord() &&
1591 "Constructors can only be declared in a member context");
1592
1593 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1594
1595 // Create the new declaration
1596 NewFD = CXXConstructorDecl::Create(Context,
1597 cast<CXXRecordDecl>(DC),
1598 D.getIdentifierLoc(), Name, R,
1599 isExplicit, isInline,
1600 /*isImplicitlyDeclared=*/false);
1601
1602 if (InvalidDecl)
1603 NewFD->setInvalidDecl();
1604 } else if (D.getKind() == Declarator::DK_Destructor) {
1605 // This is a C++ destructor declaration.
1606 if (DC->isRecord()) {
1607 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1608
1609 NewFD = CXXDestructorDecl::Create(Context,
1610 cast<CXXRecordDecl>(DC),
1611 D.getIdentifierLoc(), Name, R,
1612 isInline,
1613 /*isImplicitlyDeclared=*/false);
1614
1615 if (InvalidDecl)
1616 NewFD->setInvalidDecl();
1617 } else {
1618 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1619
1620 // Create a FunctionDecl to satisfy the function definition parsing
1621 // code path.
1622 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001623 Name, R, SC, isInline,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001624 // FIXME: Move to DeclGroup...
1625 D.getDeclSpec().getSourceRange().getBegin());
1626 InvalidDecl = true;
1627 NewFD->setInvalidDecl();
1628 }
1629 } else if (D.getKind() == Declarator::DK_Conversion) {
1630 if (!DC->isRecord()) {
1631 Diag(D.getIdentifierLoc(),
1632 diag::err_conv_function_not_member);
1633 return 0;
1634 } else {
1635 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1636
1637 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1638 D.getIdentifierLoc(), Name, R,
1639 isInline, isExplicit);
1640
1641 if (InvalidDecl)
1642 NewFD->setInvalidDecl();
1643 }
1644 } else if (DC->isRecord()) {
1645 // This is a C++ method declaration.
1646 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1647 D.getIdentifierLoc(), Name, R,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001648 (SC == FunctionDecl::Static), isInline);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001649 } else {
1650 NewFD = FunctionDecl::Create(Context, DC,
1651 D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001652 Name, R, SC, isInline,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001653 // FIXME: Move to DeclGroup...
1654 D.getDeclSpec().getSourceRange().getBegin());
1655 }
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001656 NewFD->setNextDeclarator(LastDeclarator);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001657
1658 // Set the lexical context. If the declarator has a C++
1659 // scope specifier, the lexical context will be different
1660 // from the semantic context.
1661 NewFD->setLexicalDeclContext(CurContext);
1662
1663 // Handle GNU asm-label extension (encoded as an attribute).
1664 if (Expr *E = (Expr*) D.getAsmLabel()) {
1665 // The parser guarantees this is a string.
1666 StringLiteral *SE = cast<StringLiteral>(E);
1667 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1668 SE->getByteLength())));
1669 }
1670
1671 // Copy the parameter declarations from the declarator D to
1672 // the function declaration NewFD, if they are available.
1673 if (D.getNumTypeObjects() > 0) {
1674 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1675
1676 // Create Decl objects for each parameter, adding them to the
1677 // FunctionDecl.
1678 llvm::SmallVector<ParmVarDecl*, 16> Params;
1679
1680 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1681 // function that takes no arguments, not a function that takes a
1682 // single void argument.
1683 // We let through "const void" here because Sema::GetTypeForDeclarator
1684 // already checks for that case.
1685 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1686 FTI.ArgInfo[0].Param &&
1687 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1688 // empty arg list, don't push any params.
1689 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1690
1691 // In C++, the empty parameter-type-list must be spelled "void"; a
1692 // typedef of void is not permitted.
1693 if (getLangOptions().CPlusPlus &&
1694 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1695 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1696 }
1697 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1698 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1699 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1700 }
1701
1702 NewFD->setParams(Context, &Params[0], Params.size());
1703 } else if (R->getAsTypedefType()) {
1704 // When we're declaring a function with a typedef, as in the
1705 // following example, we'll need to synthesize (unnamed)
1706 // parameters for use in the declaration.
1707 //
1708 // @code
1709 // typedef void fn(int);
1710 // fn f;
1711 // @endcode
1712 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1713 if (!FT) {
1714 // This is a typedef of a function with no prototype, so we
1715 // don't need to do anything.
1716 } else if ((FT->getNumArgs() == 0) ||
1717 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1718 FT->getArgType(0)->isVoidType())) {
1719 // This is a zero-argument function. We don't need to do anything.
1720 } else {
1721 // Synthesize a parameter for each argument type.
1722 llvm::SmallVector<ParmVarDecl*, 16> Params;
1723 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1724 ArgType != FT->arg_type_end(); ++ArgType) {
1725 Params.push_back(ParmVarDecl::Create(Context, DC,
1726 SourceLocation(), 0,
1727 *ArgType, VarDecl::None,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001728 0));
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001729 }
1730
1731 NewFD->setParams(Context, &Params[0], Params.size());
1732 }
1733 }
1734
1735 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1736 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1737 else if (isa<CXXDestructorDecl>(NewFD)) {
1738 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1739 Record->setUserDeclaredDestructor(true);
1740 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1741 // user-defined destructor.
1742 Record->setPOD(false);
1743 } else if (CXXConversionDecl *Conversion =
1744 dyn_cast<CXXConversionDecl>(NewFD))
1745 ActOnConversionDeclarator(Conversion);
1746
1747 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1748 if (NewFD->isOverloadedOperator() &&
1749 CheckOverloadedOperatorDeclaration(NewFD))
1750 NewFD->setInvalidDecl();
1751
1752 // Merge the decl with the existing one if appropriate. Since C functions
1753 // are in a flat namespace, make sure we consider decls in outer scopes.
1754 if (PrevDecl &&
1755 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1756 bool Redeclaration = false;
1757
1758 // If C++, determine whether NewFD is an overload of PrevDecl or
1759 // a declaration that requires merging. If it's an overload,
1760 // there's no more work to do here; we'll just add the new
1761 // function to the scope.
1762 OverloadedFunctionDecl::function_iterator MatchedDecl;
1763 if (!getLangOptions().CPlusPlus ||
1764 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1765 Decl *OldDecl = PrevDecl;
1766
1767 // If PrevDecl was an overloaded function, extract the
1768 // FunctionDecl that matched.
1769 if (isa<OverloadedFunctionDecl>(PrevDecl))
1770 OldDecl = *MatchedDecl;
1771
1772 // NewFD and PrevDecl represent declarations that need to be
1773 // merged.
1774 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1775
1776 if (NewFD == 0) return 0;
1777 if (Redeclaration) {
1778 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1779
1780 // An out-of-line member function declaration must also be a
1781 // definition (C++ [dcl.meaning]p1).
1782 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1783 !InvalidDecl) {
1784 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1785 << D.getCXXScopeSpec().getRange();
1786 NewFD->setInvalidDecl();
1787 }
1788 }
1789 }
1790
1791 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1792 // The user tried to provide an out-of-line definition for a
1793 // member function, but there was no such member function
1794 // declared (C++ [class.mfct]p2). For example:
1795 //
1796 // class X {
1797 // void f() const;
1798 // };
1799 //
1800 // void X::f() { } // ill-formed
1801 //
1802 // Complain about this problem, and attempt to suggest close
1803 // matches (e.g., those that differ only in cv-qualifiers and
1804 // whether the parameter types are references).
1805 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1806 << cast<CXXRecordDecl>(DC)->getDeclName()
1807 << D.getCXXScopeSpec().getRange();
1808 InvalidDecl = true;
1809
Steve Naroffc349ee22009-01-29 00:07:50 +00001810 PrevDecl = LookupDeclInContext(Name, Decl::IDNS_Ordinary, DC);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001811 if (!PrevDecl) {
1812 // Nothing to suggest.
1813 } else if (OverloadedFunctionDecl *Ovl
1814 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1815 for (OverloadedFunctionDecl::function_iterator
1816 Func = Ovl->function_begin(),
1817 FuncEnd = Ovl->function_end();
1818 Func != FuncEnd; ++Func) {
1819 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1820 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1821
1822 }
1823 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1824 // Suggest this no matter how mismatched it is; it's the only
1825 // thing we have.
1826 unsigned diag;
1827 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1828 diag = diag::note_member_def_close_match;
1829 else if (Method->getBody())
1830 diag = diag::note_previous_definition;
1831 else
1832 diag = diag::note_previous_declaration;
1833 Diag(Method->getLocation(), diag);
1834 }
1835
1836 PrevDecl = 0;
1837 }
1838 }
1839 // Handle attributes. We need to have merged decls when handling attributes
1840 // (for example to check for conflicts, etc).
1841 ProcessDeclAttributes(NewFD, D);
1842
1843 if (getLangOptions().CPlusPlus) {
1844 // In C++, check default arguments now that we have merged decls.
1845 CheckCXXDefaultArguments(NewFD);
1846
1847 // An out-of-line member function declaration must also be a
1848 // definition (C++ [dcl.meaning]p1).
1849 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1850 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1851 << D.getCXXScopeSpec().getRange();
1852 InvalidDecl = true;
1853 }
1854 }
1855 return NewFD;
1856}
1857
Steve Narofffc08f5e2008-10-27 11:34:16 +00001858void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001859 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1860 << Init->getSourceRange();
Steve Narofffc08f5e2008-10-27 11:34:16 +00001861}
1862
Eli Friedman02c22ce2008-05-20 13:48:25 +00001863bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1864 switch (Init->getStmtClass()) {
1865 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001866 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001867 return true;
1868 case Expr::ParenExprClass: {
1869 const ParenExpr* PE = cast<ParenExpr>(Init);
1870 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1871 }
1872 case Expr::CompoundLiteralExprClass:
1873 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor566782a2009-01-06 05:10:23 +00001874 case Expr::DeclRefExprClass:
1875 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001876 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001877 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1878 if (VD->hasGlobalStorage())
1879 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001880 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001881 return true;
1882 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001883 if (isa<FunctionDecl>(D))
1884 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001885 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001886 return true;
1887 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001888 case Expr::MemberExprClass: {
1889 const MemberExpr *M = cast<MemberExpr>(Init);
1890 if (M->isArrow())
1891 return CheckAddressConstantExpression(M->getBase());
1892 return CheckAddressConstantExpressionLValue(M->getBase());
1893 }
1894 case Expr::ArraySubscriptExprClass: {
1895 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1896 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1897 return CheckAddressConstantExpression(ASE->getBase()) ||
1898 CheckArithmeticConstantExpression(ASE->getIdx());
1899 }
1900 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001901 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001902 return false;
1903 case Expr::UnaryOperatorClass: {
1904 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1905
1906 // C99 6.6p9
1907 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001908 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001909
Steve Narofffc08f5e2008-10-27 11:34:16 +00001910 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001911 return true;
1912 }
1913 }
1914}
1915
1916bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1917 switch (Init->getStmtClass()) {
1918 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001919 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001920 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001921 case Expr::ParenExprClass:
1922 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001923 case Expr::StringLiteralClass:
1924 case Expr::ObjCStringLiteralClass:
1925 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001926 case Expr::CallExprClass:
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001927 case Expr::CXXOperatorCallExprClass:
Chris Lattner0903cba2008-10-06 07:26:43 +00001928 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1929 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1930 Builtin::BI__builtin___CFStringMakeConstantString)
1931 return false;
1932
Steve Narofffc08f5e2008-10-27 11:34:16 +00001933 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001934 return true;
1935
Eli Friedman02c22ce2008-05-20 13:48:25 +00001936 case Expr::UnaryOperatorClass: {
1937 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1938
1939 // C99 6.6p9
1940 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1941 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1942
1943 if (Exp->getOpcode() == UnaryOperator::Extension)
1944 return CheckAddressConstantExpression(Exp->getSubExpr());
1945
Steve Narofffc08f5e2008-10-27 11:34:16 +00001946 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001947 return true;
1948 }
1949 case Expr::BinaryOperatorClass: {
1950 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1951 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1952
1953 Expr *PExp = Exp->getLHS();
1954 Expr *IExp = Exp->getRHS();
1955 if (IExp->getType()->isPointerType())
1956 std::swap(PExp, IExp);
1957
1958 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1959 return CheckAddressConstantExpression(PExp) ||
1960 CheckArithmeticConstantExpression(IExp);
1961 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001962 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001963 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001964 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001965 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1966 // Check for implicit promotion
1967 if (SubExpr->getType()->isFunctionType() ||
1968 SubExpr->getType()->isArrayType())
1969 return CheckAddressConstantExpressionLValue(SubExpr);
1970 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001971
1972 // Check for pointer->pointer cast
1973 if (SubExpr->getType()->isPointerType())
1974 return CheckAddressConstantExpression(SubExpr);
1975
Eli Friedman1fad3c62008-08-25 20:46:57 +00001976 if (SubExpr->getType()->isIntegralType()) {
1977 // Check for the special-case of a pointer->int->pointer cast;
1978 // this isn't standard, but some code requires it. See
1979 // PR2720 for an example.
1980 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1981 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1982 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1983 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1984 if (IntWidth >= PointerWidth) {
1985 return CheckAddressConstantExpression(SubCast->getSubExpr());
1986 }
1987 }
1988 }
1989 }
1990 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001991 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001992 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001993
Steve Narofffc08f5e2008-10-27 11:34:16 +00001994 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001995 return true;
1996 }
1997 case Expr::ConditionalOperatorClass: {
1998 // FIXME: Should we pedwarn here?
1999 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
2000 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00002001 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002002 return true;
2003 }
2004 if (CheckArithmeticConstantExpression(Exp->getCond()))
2005 return true;
2006 if (Exp->getLHS() &&
2007 CheckAddressConstantExpression(Exp->getLHS()))
2008 return true;
2009 return CheckAddressConstantExpression(Exp->getRHS());
2010 }
2011 case Expr::AddrLabelExprClass:
2012 return false;
2013 }
2014}
2015
Eli Friedman998dffb2008-06-09 05:05:07 +00002016static const Expr* FindExpressionBaseAddress(const Expr* E);
2017
2018static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
2019 switch (E->getStmtClass()) {
2020 default:
2021 return E;
2022 case Expr::ParenExprClass: {
2023 const ParenExpr* PE = cast<ParenExpr>(E);
2024 return FindExpressionBaseAddressLValue(PE->getSubExpr());
2025 }
2026 case Expr::MemberExprClass: {
2027 const MemberExpr *M = cast<MemberExpr>(E);
2028 if (M->isArrow())
2029 return FindExpressionBaseAddress(M->getBase());
2030 return FindExpressionBaseAddressLValue(M->getBase());
2031 }
2032 case Expr::ArraySubscriptExprClass: {
2033 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
2034 return FindExpressionBaseAddress(ASE->getBase());
2035 }
2036 case Expr::UnaryOperatorClass: {
2037 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2038
2039 if (Exp->getOpcode() == UnaryOperator::Deref)
2040 return FindExpressionBaseAddress(Exp->getSubExpr());
2041
2042 return E;
2043 }
2044 }
2045}
2046
2047static const Expr* FindExpressionBaseAddress(const Expr* E) {
2048 switch (E->getStmtClass()) {
2049 default:
2050 return E;
2051 case Expr::ParenExprClass: {
2052 const ParenExpr* PE = cast<ParenExpr>(E);
2053 return FindExpressionBaseAddress(PE->getSubExpr());
2054 }
2055 case Expr::UnaryOperatorClass: {
2056 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2057
2058 // C99 6.6p9
2059 if (Exp->getOpcode() == UnaryOperator::AddrOf)
2060 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
2061
2062 if (Exp->getOpcode() == UnaryOperator::Extension)
2063 return FindExpressionBaseAddress(Exp->getSubExpr());
2064
2065 return E;
2066 }
2067 case Expr::BinaryOperatorClass: {
2068 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2069
2070 Expr *PExp = Exp->getLHS();
2071 Expr *IExp = Exp->getRHS();
2072 if (IExp->getType()->isPointerType())
2073 std::swap(PExp, IExp);
2074
2075 return FindExpressionBaseAddress(PExp);
2076 }
2077 case Expr::ImplicitCastExprClass: {
2078 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
2079
2080 // Check for implicit promotion
2081 if (SubExpr->getType()->isFunctionType() ||
2082 SubExpr->getType()->isArrayType())
2083 return FindExpressionBaseAddressLValue(SubExpr);
2084
2085 // Check for pointer->pointer cast
2086 if (SubExpr->getType()->isPointerType())
2087 return FindExpressionBaseAddress(SubExpr);
2088
2089 // We assume that we have an arithmetic expression here;
2090 // if we don't, we'll figure it out later
2091 return 0;
2092 }
Douglas Gregor035d0882008-10-28 15:36:24 +00002093 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00002094 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2095
2096 // Check for pointer->pointer cast
2097 if (SubExpr->getType()->isPointerType())
2098 return FindExpressionBaseAddress(SubExpr);
2099
2100 // We assume that we have an arithmetic expression here;
2101 // if we don't, we'll figure it out later
2102 return 0;
2103 }
2104 }
2105}
2106
Anders Carlssone8bd9f22008-11-22 21:04:56 +00002107bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002108 switch (Init->getStmtClass()) {
2109 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00002110 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002111 return true;
2112 case Expr::ParenExprClass: {
2113 const ParenExpr* PE = cast<ParenExpr>(Init);
2114 return CheckArithmeticConstantExpression(PE->getSubExpr());
2115 }
2116 case Expr::FloatingLiteralClass:
2117 case Expr::IntegerLiteralClass:
2118 case Expr::CharacterLiteralClass:
2119 case Expr::ImaginaryLiteralClass:
2120 case Expr::TypesCompatibleExprClass:
2121 case Expr::CXXBoolLiteralExprClass:
2122 return false;
Douglas Gregor65fedaf2008-11-14 16:09:21 +00002123 case Expr::CallExprClass:
2124 case Expr::CXXOperatorCallExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002125 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002126
2127 // Allow any constant foldable calls to builtins.
2128 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002129 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002130
Steve Narofffc08f5e2008-10-27 11:34:16 +00002131 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002132 return true;
2133 }
Douglas Gregor566782a2009-01-06 05:10:23 +00002134 case Expr::DeclRefExprClass:
2135 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002136 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2137 if (isa<EnumConstantDecl>(D))
2138 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002139 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002140 return true;
2141 }
2142 case Expr::CompoundLiteralExprClass:
2143 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2144 // but vectors are allowed to be magic.
2145 if (Init->getType()->isVectorType())
2146 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002147 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002148 return true;
2149 case Expr::UnaryOperatorClass: {
2150 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2151
2152 switch (Exp->getOpcode()) {
2153 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2154 // See C99 6.6p3.
2155 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00002156 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002157 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002158 case UnaryOperator::OffsetOf:
Eli Friedman02c22ce2008-05-20 13:48:25 +00002159 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2160 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002161 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002162 return true;
2163 case UnaryOperator::Extension:
2164 case UnaryOperator::LNot:
2165 case UnaryOperator::Plus:
2166 case UnaryOperator::Minus:
2167 case UnaryOperator::Not:
2168 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2169 }
2170 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002171 case Expr::SizeOfAlignOfExprClass: {
2172 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002173 // Special check for void types, which are allowed as an extension
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002174 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedman02c22ce2008-05-20 13:48:25 +00002175 return false;
2176 // alignof always evaluates to a constant.
2177 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002178 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00002179 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002180 return true;
2181 }
2182 return false;
2183 }
2184 case Expr::BinaryOperatorClass: {
2185 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2186
2187 if (Exp->getLHS()->getType()->isArithmeticType() &&
2188 Exp->getRHS()->getType()->isArithmeticType()) {
2189 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2190 CheckArithmeticConstantExpression(Exp->getRHS());
2191 }
2192
Eli Friedman998dffb2008-06-09 05:05:07 +00002193 if (Exp->getLHS()->getType()->isPointerType() &&
2194 Exp->getRHS()->getType()->isPointerType()) {
2195 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2196 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2197
2198 // Only allow a null (constant integer) base; we could
2199 // allow some additional cases if necessary, but this
2200 // is sufficient to cover offsetof-like constructs.
2201 if (!LHSBase && !RHSBase) {
2202 return CheckAddressConstantExpression(Exp->getLHS()) ||
2203 CheckAddressConstantExpression(Exp->getRHS());
2204 }
2205 }
2206
Steve Narofffc08f5e2008-10-27 11:34:16 +00002207 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002208 return true;
2209 }
2210 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00002211 case Expr::CStyleCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002212 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00002213 if (SubExpr->getType()->isArithmeticType())
2214 return CheckArithmeticConstantExpression(SubExpr);
2215
Eli Friedman266df142008-09-02 09:37:00 +00002216 if (SubExpr->getType()->isPointerType()) {
2217 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2218 // If the pointer has a null base, this is an offsetof-like construct
2219 if (!Base)
2220 return CheckAddressConstantExpression(SubExpr);
2221 }
2222
Steve Narofffc08f5e2008-10-27 11:34:16 +00002223 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00002224 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002225 }
2226 case Expr::ConditionalOperatorClass: {
2227 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00002228
2229 // If GNU extensions are disabled, we require all operands to be arithmetic
2230 // constant expressions.
2231 if (getLangOptions().NoExtensions) {
2232 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2233 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2234 CheckArithmeticConstantExpression(Exp->getRHS());
2235 }
2236
2237 // Otherwise, we have to emulate some of the behavior of fold here.
2238 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2239 // because it can constant fold things away. To retain compatibility with
2240 // GCC code, we see if we can fold the condition to a constant (which we
2241 // should always be able to do in theory). If so, we only require the
2242 // specified arm of the conditional to be a constant. This is a horrible
2243 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson8c3de802008-12-19 20:58:05 +00002244 Expr::EvalResult EvalResult;
2245 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2246 EvalResult.HasSideEffects) {
Chris Lattneref069662008-11-16 21:24:15 +00002247 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner94d45412008-10-06 05:42:39 +00002248 // won't be able to either. Use it to emit the diagnostic though.
2249 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattneref069662008-11-16 21:24:15 +00002250 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner94d45412008-10-06 05:42:39 +00002251 return Res;
2252 }
2253
2254 // Verify that the side following the condition is also a constant.
2255 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson8c3de802008-12-19 20:58:05 +00002256 if (EvalResult.Val.getInt() == 0)
Chris Lattner94d45412008-10-06 05:42:39 +00002257 std::swap(TrueSide, FalseSide);
2258
2259 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002260 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00002261
2262 // Okay, the evaluated side evaluates to a constant, so we accept this.
2263 // Check to see if the other side is obviously not a constant. If so,
2264 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002265 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00002266 Diag(Init->getExprLoc(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00002267 diag::ext_typecheck_expression_not_constant_but_accepted)
2268 << FalseSide->getSourceRange();
Chris Lattner94d45412008-10-06 05:42:39 +00002269 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002270 }
2271 }
2272}
2273
2274bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00002275 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init))
2276 Init = DIE->getInit();
2277
Nuno Lopese7280452008-07-07 16:46:50 +00002278 Init = Init->IgnoreParens();
2279
Nate Begemand6d2f772009-01-18 03:20:47 +00002280 if (Init->isEvaluatable(Context))
Anders Carlssonf6791c62008-12-05 05:09:56 +00002281 return false;
2282
Eli Friedman02c22ce2008-05-20 13:48:25 +00002283 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2284 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2285 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2286
Nuno Lopese7280452008-07-07 16:46:50 +00002287 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2288 return CheckForConstantInitializer(e->getInitializer(), DclT);
2289
Douglas Gregorc9e012a2009-01-29 17:44:32 +00002290 if (isa<ImplicitValueInitExpr>(Init)) {
2291 // FIXME: In C++, check for non-POD types.
2292 return false;
2293 }
2294
Eli Friedman02c22ce2008-05-20 13:48:25 +00002295 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2296 unsigned numInits = Exp->getNumInits();
2297 for (unsigned i = 0; i < numInits; i++) {
2298 // FIXME: Need to get the type of the declaration for C++,
2299 // because it could be a reference?
Douglas Gregorf603b472009-01-28 21:54:33 +00002300
Eli Friedman02c22ce2008-05-20 13:48:25 +00002301 if (CheckForConstantInitializer(Exp->getInit(i),
2302 Exp->getInit(i)->getType()))
2303 return true;
2304 }
2305 return false;
2306 }
2307
Anders Carlssonf6791c62008-12-05 05:09:56 +00002308 // FIXME: We can probably remove some of this code below, now that
2309 // Expr::Evaluate is doing the heavy lifting for scalars.
2310
Eli Friedman02c22ce2008-05-20 13:48:25 +00002311 if (Init->isNullPointerConstant(Context))
2312 return false;
2313 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002314 QualType InitTy = Context.getCanonicalType(Init->getType())
2315 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00002316 if (InitTy == Context.BoolTy) {
2317 // Special handling for pointers implicitly cast to bool;
2318 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2319 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2320 Expr* SubE = ICE->getSubExpr();
2321 if (SubE->getType()->isPointerType() ||
2322 SubE->getType()->isArrayType() ||
2323 SubE->getType()->isFunctionType()) {
2324 return CheckAddressConstantExpression(Init);
2325 }
2326 }
2327 } else if (InitTy->isIntegralType()) {
2328 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002329 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00002330 SubE = CE->getSubExpr();
2331 // Special check for pointer cast to int; we allow as an extension
2332 // an address constant cast to an integer if the integer
2333 // is of an appropriate width (this sort of code is apparently used
2334 // in some places).
2335 // FIXME: Add pedwarn?
2336 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2337 if (SubE && (SubE->getType()->isPointerType() ||
2338 SubE->getType()->isArrayType() ||
2339 SubE->getType()->isFunctionType())) {
2340 unsigned IntWidth = Context.getTypeSize(Init->getType());
2341 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2342 if (IntWidth >= PointerWidth)
2343 return CheckAddressConstantExpression(Init);
2344 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00002345 }
2346
2347 return CheckArithmeticConstantExpression(Init);
2348 }
2349
2350 if (Init->getType()->isPointerType())
2351 return CheckAddressConstantExpression(Init);
2352
Eli Friedman25086f02008-05-30 18:14:48 +00002353 // An array type at the top level that isn't an init-list must
2354 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00002355 if (Init->getType()->isArrayType())
2356 return false;
2357
Nuno Lopes1dc26762008-09-01 18:42:41 +00002358 if (Init->getType()->isFunctionType())
2359 return false;
2360
Steve Naroffdff3fb22008-10-02 17:12:56 +00002361 // Allow block exprs at top level.
2362 if (Init->getType()->isBlockPointerType())
2363 return false;
Nuno Lopes8260d5d2009-01-15 16:44:45 +00002364
2365 // GCC cast to union extension
2366 // note: the validity of the cast expr is checked by CheckCastTypes()
2367 if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2368 QualType T = C->getType();
2369 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2370 }
2371
Steve Narofffc08f5e2008-10-27 11:34:16 +00002372 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002373 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00002374}
2375
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002376void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002377 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2378}
2379
2380/// AddInitializerToDecl - Adds the initializer Init to the
2381/// declaration dcl. If DirectInit is true, this is C++ direct
2382/// initialization rather than copy initialization.
2383void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002384 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002385 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002386 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00002387
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002388 // If there is no declaration, there was an error parsing it. Just ignore
2389 // the initializer.
2390 if (RealDecl == 0) {
2391 delete Init;
2392 return;
2393 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002394
Steve Naroff420d0f52007-09-12 20:13:48 +00002395 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2396 if (!VDecl) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002397 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00002398 RealDecl->setInvalidDecl();
2399 return;
2400 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002401 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00002402 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00002403 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002404 if (VDecl->isBlockVarDecl()) {
2405 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002406 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00002407 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002408 VDecl->setInvalidDecl();
2409 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002410 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002411 VDecl->getDeclName(), DirectInit))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002412 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00002413
2414 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2415 if (!getLangOptions().CPlusPlus) {
2416 if (SC == VarDecl::Static) // C99 6.7.8p4.
2417 CheckForConstantInitializer(Init, DclT);
2418 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002419 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002420 } else if (VDecl->isFileVarDecl()) {
2421 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00002422 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002423 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00002424 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002425 VDecl->getDeclName(), DirectInit))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002426 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00002427
Anders Carlssonea7140a2008-08-22 05:00:02 +00002428 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2429 if (!getLangOptions().CPlusPlus) {
2430 // C99 6.7.8p4. All file scoped initializers need to be constant.
2431 CheckForConstantInitializer(Init, DclT);
2432 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002433 }
2434 // If the type changed, it means we had an incomplete type that was
2435 // completed by the initializer. For example:
2436 // int ary[] = { 1, 3, 5 };
2437 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00002438 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002439 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00002440 Init->setType(DclT);
2441 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002442
2443 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00002444 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00002445 return;
2446}
2447
Douglas Gregor81c29152008-10-29 00:13:59 +00002448void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2449 Decl *RealDecl = static_cast<Decl *>(dcl);
2450
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00002451 // If there is no declaration, there was an error parsing it. Just ignore it.
2452 if (RealDecl == 0)
2453 return;
2454
Douglas Gregor81c29152008-10-29 00:13:59 +00002455 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2456 QualType Type = Var->getType();
2457 // C++ [dcl.init.ref]p3:
2458 // The initializer can be omitted for a reference only in a
2459 // parameter declaration (8.3.5), in the declaration of a
2460 // function return type, in the declaration of a class member
2461 // within its class declaration (9.2), and where the extern
2462 // specifier is explicitly used.
Douglas Gregorb9213832008-12-15 21:24:18 +00002463 if (Type->isReferenceType() &&
2464 Var->getStorageClass() != VarDecl::Extern &&
2465 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002466 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattner271d4c22008-11-24 05:29:24 +00002467 << Var->getDeclName()
2468 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor5870a952008-11-03 20:45:27 +00002469 Var->setInvalidDecl();
2470 return;
2471 }
2472
2473 // C++ [dcl.init]p9:
2474 //
2475 // If no initializer is specified for an object, and the object
2476 // is of (possibly cv-qualified) non-POD class type (or array
2477 // thereof), the object shall be default-initialized; if the
2478 // object is of const-qualified type, the underlying class type
2479 // shall have a user-declared default constructor.
2480 if (getLangOptions().CPlusPlus) {
2481 QualType InitType = Type;
2482 if (const ArrayType *Array = Context.getAsArrayType(Type))
2483 InitType = Array->getElementType();
Douglas Gregorb9213832008-12-15 21:24:18 +00002484 if (Var->getStorageClass() != VarDecl::Extern &&
2485 Var->getStorageClass() != VarDecl::PrivateExtern &&
2486 InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002487 const CXXConstructorDecl *Constructor
2488 = PerformInitializationByConstructor(InitType, 0, 0,
2489 Var->getLocation(),
2490 SourceRange(Var->getLocation(),
2491 Var->getLocation()),
Chris Lattner271d4c22008-11-24 05:29:24 +00002492 Var->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00002493 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00002494 if (!Constructor)
2495 Var->setInvalidDecl();
2496 }
2497 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002498
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002499#if 0
2500 // FIXME: Temporarily disabled because we are not properly parsing
2501 // linkage specifications on declarations, e.g.,
2502 //
2503 // extern "C" const CGPoint CGPointerZero;
2504 //
Douglas Gregor81c29152008-10-29 00:13:59 +00002505 // C++ [dcl.init]p9:
2506 //
2507 // If no initializer is specified for an object, and the
2508 // object is of (possibly cv-qualified) non-POD class type (or
2509 // array thereof), the object shall be default-initialized; if
2510 // the object is of const-qualified type, the underlying class
2511 // type shall have a user-declared default
2512 // constructor. Otherwise, if no initializer is specified for
2513 // an object, the object and its subobjects, if any, have an
2514 // indeterminate initial value; if the object or any of its
2515 // subobjects are of const-qualified type, the program is
2516 // ill-formed.
2517 //
2518 // This isn't technically an error in C, so we don't diagnose it.
2519 //
2520 // FIXME: Actually perform the POD/user-defined default
2521 // constructor check.
2522 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002523 Context.getCanonicalType(Type).isConstQualified() &&
2524 Var->getStorageClass() != VarDecl::Extern)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002525 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2526 << Var->getName()
2527 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002528#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00002529 }
2530}
2531
Chris Lattner4b009652007-07-25 00:24:17 +00002532/// The declarators are chained together backwards, reverse the list.
2533Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2534 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002535 Decl *GroupDecl = static_cast<Decl*>(group);
2536 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00002537 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00002538
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002539 Decl *Group = dyn_cast<Decl>(GroupDecl);
2540 Decl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002541 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00002542 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002543 else { // reverse the list.
2544 while (Group) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002545 Decl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002546 Group->setNextDeclarator(NewGroup);
2547 NewGroup = Group;
2548 Group = Next;
2549 }
2550 }
2551 // Perform semantic analysis that depends on having fully processed both
2552 // the declarator and initializer.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002553 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00002554 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2555 if (!IDecl)
2556 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002557 QualType T = IDecl->getType();
2558
Anders Carlsson68adbd12008-12-07 00:20:55 +00002559 if (T->isVariableArrayType()) {
Anders Carlssonef2f7df2008-12-20 21:51:53 +00002560 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002561
2562 // FIXME: This won't give the correct result for
2563 // int a[10][n];
2564 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002565 if (IDecl->isFileVarDecl()) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002566 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2567 SizeRange;
2568
Eli Friedman8ff07782008-02-15 18:16:39 +00002569 IDecl->setInvalidDecl();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002570 } else {
2571 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2572 // static storage duration, it shall not have a variable length array.
2573 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002574 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2575 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002576 IDecl->setInvalidDecl();
2577 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002578 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2579 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002580 IDecl->setInvalidDecl();
2581 }
2582 }
2583 } else if (T->isVariablyModifiedType()) {
2584 if (IDecl->isFileVarDecl()) {
2585 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2586 IDecl->setInvalidDecl();
2587 } else {
2588 if (IDecl->getStorageClass() == VarDecl::Extern) {
2589 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2590 IDecl->setInvalidDecl();
2591 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002592 }
2593 }
Anders Carlsson68adbd12008-12-07 00:20:55 +00002594
Steve Naroff6a0e2092007-09-12 14:07:44 +00002595 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2596 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002597 if (IDecl->isBlockVarDecl() &&
2598 IDecl->getStorageClass() != VarDecl::Extern) {
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002599 if (!IDecl->isInvalidDecl() &&
2600 DiagnoseIncompleteType(IDecl->getLocation(), T,
2601 diag::err_typecheck_decl_incomplete_type))
Steve Naroff6a0e2092007-09-12 14:07:44 +00002602 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002603 }
2604 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2605 // object that has file scope without an initializer, and without a
2606 // storage-class specifier or with the storage-class specifier "static",
2607 // constitutes a tentative definition. Note: A tentative definition with
2608 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00002609 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00002610 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00002611 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2612 // array to be completed. Don't issue a diagnostic.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002613 } else if (!IDecl->isInvalidDecl() &&
2614 DiagnoseIncompleteType(IDecl->getLocation(), T,
2615 diag::err_typecheck_decl_incomplete_type))
Steve Naroff60685462008-01-18 20:40:52 +00002616 // C99 6.9.2p3: If the declaration of an identifier for an object is
2617 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2618 // declared type shall not be an incomplete type.
Steve Naroff6a0e2092007-09-12 14:07:44 +00002619 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002620 }
Steve Naroffb5e78152008-08-08 17:50:35 +00002621 if (IDecl->isFileVarDecl())
2622 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002623 }
2624 return NewGroup;
2625}
Steve Naroff91b03f72007-08-28 03:03:08 +00002626
Chris Lattner3e254fb2008-04-08 04:40:51 +00002627/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2628/// to introduce parameters into function prototype scope.
2629Sema::DeclTy *
2630Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00002631 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002632
Chris Lattner3e254fb2008-04-08 04:40:51 +00002633 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002634 VarDecl::StorageClass StorageClass = VarDecl::None;
2635 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2636 StorageClass = VarDecl::Register;
2637 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002638 Diag(DS.getStorageClassSpecLoc(),
2639 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002640 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002641 }
2642 if (DS.isThreadSpecified()) {
2643 Diag(DS.getThreadSpecLoc(),
2644 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002645 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002646 }
2647
Douglas Gregor2b9422f2008-05-07 04:49:29 +00002648 // Check that there are no default arguments inside the type of this
2649 // parameter (C++ only).
2650 if (getLangOptions().CPlusPlus)
2651 CheckExtraCXXDefaultArguments(D);
2652
Chris Lattner3e254fb2008-04-08 04:40:51 +00002653 // In this context, we *do not* check D.getInvalidType(). If the declarator
2654 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2655 // though it will not reflect the user specified type.
2656 QualType parmDeclType = GetTypeForDeclarator(D, S);
2657
2658 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2659
Chris Lattner4b009652007-07-25 00:24:17 +00002660 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2661 // Can this happen for params? We already checked that they don't conflict
2662 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002663 IdentifierInfo *II = D.getIdentifier();
Chris Lattner310dea32009-01-21 02:38:50 +00002664 if (II) {
Steve Naroffc349ee22009-01-29 00:07:50 +00002665 if (Decl *PrevDecl = LookupDeclInScope(II, Decl::IDNS_Ordinary, S)) {
Chris Lattner310dea32009-01-21 02:38:50 +00002666 if (PrevDecl->isTemplateParameter()) {
2667 // Maybe we will complain about the shadowed template parameter.
2668 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2669 // Just pretend that we didn't see the previous declaration.
2670 PrevDecl = 0;
2671 } else if (S->isDeclScope(PrevDecl)) {
2672 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002673
Chris Lattner310dea32009-01-21 02:38:50 +00002674 // Recover by removing the name
2675 II = 0;
2676 D.SetIdentifier(0, D.getIdentifierLoc());
2677 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002678 }
Chris Lattner4b009652007-07-25 00:24:17 +00002679 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00002680
2681 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2682 // Doing the promotion here has a win and a loss. The win is the type for
2683 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2684 // code generator). The loss is the orginal type isn't preserved. For example:
2685 //
2686 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2687 // int blockvardecl[5];
2688 // sizeof(parmvardecl); // size == 4
2689 // sizeof(blockvardecl); // size == 20
2690 // }
2691 //
2692 // For expressions, all implicit conversions are captured using the
2693 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2694 //
2695 // FIXME: If a source translation tool needs to see the original type, then
2696 // we need to consider storing both types (in ParmVarDecl)...
2697 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00002698 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00002699 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00002700 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00002701 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00002702 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002703
Chris Lattner3e254fb2008-04-08 04:40:51 +00002704 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2705 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002706 parmDeclType, StorageClass,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002707 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00002708
Chris Lattner3e254fb2008-04-08 04:40:51 +00002709 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00002710 New->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002711
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002712 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2713 if (D.getCXXScopeSpec().isSet()) {
2714 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2715 << D.getCXXScopeSpec().getRange();
2716 New->setInvalidDecl();
2717 }
2718
Douglas Gregor8acb7272008-12-11 16:49:14 +00002719 // Add the parameter declaration into this scope.
2720 S->AddDecl(New);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002721 if (II)
Douglas Gregor8acb7272008-12-11 16:49:14 +00002722 IdResolver.AddDecl(New);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00002723
Chris Lattner9b384ca2008-06-29 00:02:00 +00002724 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00002725 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002726
Chris Lattner4b009652007-07-25 00:24:17 +00002727}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00002728
Douglas Gregor65075ec2009-01-23 16:23:13 +00002729void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +00002730 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2731 "Not a function declarator!");
2732 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002733
Chris Lattner4b009652007-07-25 00:24:17 +00002734 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2735 // for a K&R function.
2736 if (!FTI.hasPrototype) {
2737 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002738 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002739 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2740 << FTI.ArgInfo[i].Ident;
Chris Lattner4b009652007-07-25 00:24:17 +00002741 // Implicitly declare the argument as type 'int' for lack of a better
2742 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002743 DeclSpec DS;
2744 const char* PrevSpec; // unused
2745 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2746 PrevSpec);
2747 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2748 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor65075ec2009-01-23 16:23:13 +00002749 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00002750 }
2751 }
Douglas Gregor65075ec2009-01-23 16:23:13 +00002752 }
2753}
2754
2755Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2756 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2757 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2758 "Not a function declarator!");
2759 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2760
2761 if (FTI.hasPrototype) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002762 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00002763 }
2764
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002765 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00002766
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002767 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002768 ActOnDeclarator(ParentScope, D, 0,
2769 /*IsFunctionDefinition=*/true));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002770}
2771
2772Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2773 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002774 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002775
2776 // See if this is a redefinition.
2777 const FunctionDecl *Definition;
2778 if (FD->getBody(Definition)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002779 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00002780 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor56da7862008-10-29 15:10:40 +00002781 }
2782
Douglas Gregor8acb7272008-12-11 16:49:14 +00002783 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002784
Chris Lattner3e254fb2008-04-08 04:40:51 +00002785 // Check the validity of our function parameters
2786 CheckParmsForFunctionDef(FD);
2787
2788 // Introduce our parameters into the function scope
2789 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2790 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregord394a272009-01-09 18:51:29 +00002791 Param->setOwningFunction(FD);
2792
Chris Lattner3e254fb2008-04-08 04:40:51 +00002793 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002794 if (Param->getIdentifier())
2795 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002796 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002797
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002798 // Checking attributes of current function definition
2799 // dllimport attribute.
2800 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2801 // dllimport attribute cannot be applied to definition.
2802 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2803 Diag(FD->getLocation(),
2804 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2805 << "dllimport";
2806 FD->setInvalidDecl();
2807 return FD;
2808 } else {
2809 // If a symbol previously declared dllimport is later defined, the
2810 // attribute is ignored in subsequent references, and a warning is
2811 // emitted.
2812 Diag(FD->getLocation(),
2813 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2814 << FD->getNameAsCString() << "dllimport";
2815 }
2816 }
Chris Lattner4b009652007-07-25 00:24:17 +00002817 return FD;
2818}
2819
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002820Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002821 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002822 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff3ac43f92008-07-25 17:57:26 +00002823 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002824 FD->setBody(Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002825 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002826 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002827 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002828 } else
2829 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002830 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002831 // Verify and clean out per-function state.
2832
2833 // Check goto/label use.
2834 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2835 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2836 // Verify that we have no forward references left. If so, there was a goto
2837 // or address of a label taken, but no definition of it. Label fwd
2838 // definitions are indicated with a null substmt.
2839 if (I->second->getSubStmt() == 0) {
2840 LabelStmt *L = I->second;
2841 // Emit error.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002842 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Chris Lattner4b009652007-07-25 00:24:17 +00002843
2844 // At this point, we have gotos that use the bogus label. Stitch it into
2845 // the function body so that they aren't leaked and that the AST is well
2846 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002847 if (Body) {
2848 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002849 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner83343342008-01-25 00:01:10 +00002850 } else {
2851 // The whole function wasn't parsed correctly, just delete this.
2852 delete L;
2853 }
Chris Lattner4b009652007-07-25 00:24:17 +00002854 }
2855 }
2856 LabelMap.clear();
2857
Steve Naroff99ee4302007-11-11 23:20:51 +00002858 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002859}
2860
Chris Lattner4b009652007-07-25 00:24:17 +00002861/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2862/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002863NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2864 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002865 // Extension in C99. Legal in C90, but warn about it.
2866 if (getLangOptions().C99)
Chris Lattner65cae292008-11-19 08:23:25 +00002867 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002868 else
Chris Lattner65cae292008-11-19 08:23:25 +00002869 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Chris Lattner4b009652007-07-25 00:24:17 +00002870
2871 // FIXME: handle stuff like:
2872 // void foo() { extern float X(); }
2873 // void bar() { X(); } <-- implicit decl for X in another scope.
2874
2875 // Set a Declarator for the implicit definition: int foo();
2876 const char *Dummy;
2877 DeclSpec DS;
2878 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2879 Error = Error; // Silence warning.
2880 assert(!Error && "Error setting up implicit decl!");
2881 Declarator D(DS, Declarator::BlockContext);
Chris Lattnerdefaf412009-01-20 19:11:22 +00002882 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc, D));
Chris Lattner4b009652007-07-25 00:24:17 +00002883 D.SetIdentifier(&II, Loc);
2884
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002885 // Insert this function into translation-unit scope.
2886
2887 DeclContext *PrevDC = CurContext;
2888 CurContext = Context.getTranslationUnitDecl();
2889
Steve Naroff9104f3c2008-04-04 14:32:09 +00002890 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002891 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002892 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002893
2894 CurContext = PrevDC;
2895
Steve Naroff9104f3c2008-04-04 14:32:09 +00002896 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002897}
2898
2899
Chris Lattner82bb4792007-11-14 06:34:38 +00002900TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002901 Decl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002902 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002903 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002904
2905 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002906 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2907 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002908 D.getIdentifier(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002909 T);
2910 NewTD->setNextDeclarator(LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002911 if (D.getInvalidType())
2912 NewTD->setInvalidDecl();
2913 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002914}
2915
Steve Naroff0acc9c92007-09-15 18:49:24 +00002916/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002917/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregor98b27542009-01-17 00:42:38 +00002918/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Chris Lattner4b009652007-07-25 00:24:17 +00002919/// reference/declaration/definition of a tag.
Douglas Gregor98b27542009-01-17 00:42:38 +00002920Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002921 SourceLocation KWLoc, const CXXScopeSpec &SS,
2922 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregor52473432008-12-24 02:52:09 +00002923 AttributeList *Attr,
2924 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorae644892008-12-15 16:32:14 +00002925 // If this is not a definition, it must have a name.
Chris Lattner4b009652007-07-25 00:24:17 +00002926 assert((Name != 0 || TK == TK_Definition) &&
2927 "Nameless record must be a definition!");
2928
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002929 TagDecl::TagKind Kind;
Douglas Gregor98b27542009-01-17 00:42:38 +00002930 switch (TagSpec) {
Chris Lattner4b009652007-07-25 00:24:17 +00002931 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002932 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2933 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2934 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2935 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002936 }
2937
Douglas Gregorb748fc52009-01-12 22:49:06 +00002938 DeclContext *SearchDC = CurContext;
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002939 DeclContext *DC = CurContext;
Douglas Gregorcab994d2009-01-09 22:42:13 +00002940 DeclContext *LexicalContext = CurContext;
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002941 Decl *PrevDecl = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002942
Douglas Gregor98b27542009-01-17 00:42:38 +00002943 bool Invalid = false;
2944
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002945 if (Name && SS.isNotEmpty()) {
2946 // We have a nested-name tag ('struct foo::bar').
2947
2948 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002949 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002950 Name = 0;
2951 goto CreateNewDecl;
2952 }
2953
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002954 DC = static_cast<DeclContext*>(SS.getScopeRep());
2955 // Look-up name inside 'foo::'.
Steve Naroffc349ee22009-01-29 00:07:50 +00002956 PrevDecl = dyn_cast_or_null<TagDecl>(
2957 LookupDeclInContext(Name, Decl::IDNS_Tag, DC).getAsDecl());
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002958
2959 // A tag 'foo::bar' must already exist.
2960 if (PrevDecl == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002961 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002962 Name = 0;
2963 goto CreateNewDecl;
2964 }
Chris Lattner310dea32009-01-21 02:38:50 +00002965 } else if (Name) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002966 // If this is a named struct, check to see if there was a previous forward
2967 // declaration or definition.
Steve Naroffa4e04982009-01-29 18:09:31 +00002968 Decl *D = LookupDeclInScope(Name, Decl::IDNS_Tag, S);
2969 PrevDecl = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregordb568cf2009-01-08 20:45:30 +00002970
2971 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2972 // FIXME: This makes sure that we ignore the contexts associated
2973 // with C structs, unions, and enums when looking for a matching
2974 // tag declaration or definition. See the similar lookup tweak
2975 // in Sema::LookupDecl; is there a better way to deal with this?
Douglas Gregorb748fc52009-01-12 22:49:06 +00002976 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2977 SearchDC = SearchDC->getParent();
Douglas Gregordb568cf2009-01-08 20:45:30 +00002978 }
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002979 }
2980
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002981 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002982 // Maybe we will complain about the shadowed template parameter.
2983 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2984 // Just pretend that we didn't see the previous declaration.
2985 PrevDecl = 0;
2986 }
2987
Ted Kremenekd4434152008-09-02 21:26:19 +00002988 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002989 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002990 // If this is a use of a previous tag, or if the tag is already declared
2991 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002992 // rementions the tag), reuse the decl.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002993 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002994 // Make sure that this wasn't declared as an enum and now used as a
2995 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002996 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner65cae292008-11-19 08:23:25 +00002997 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002998 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002999 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00003000 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00003001 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00003002 Invalid = true;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00003003 } else {
Douglas Gregorae644892008-12-15 16:32:14 +00003004 // If this is a use, just return the declaration we found.
Chris Lattner5bf0ad52008-07-03 03:30:58 +00003005
Douglas Gregorae644892008-12-15 16:32:14 +00003006 // FIXME: In the future, return a variant or some other clue
3007 // for the consumer of this Decl to know it doesn't own it.
3008 // For our current ASTs this shouldn't be a problem, but will
3009 // need to be changed with DeclGroups.
3010 if (TK == TK_Reference)
Chris Lattner5bf0ad52008-07-03 03:30:58 +00003011 return PrevDecl;
Douglas Gregorae644892008-12-15 16:32:14 +00003012
3013 // Diagnose attempts to redefine a tag.
3014 if (TK == TK_Definition) {
3015 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
3016 Diag(NameLoc, diag::err_redefinition) << Name;
3017 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor98b27542009-01-17 00:42:38 +00003018 // If this is a redefinition, recover by making this
3019 // struct be anonymous, which will make any later
3020 // references get the previous definition.
Douglas Gregorae644892008-12-15 16:32:14 +00003021 Name = 0;
3022 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00003023 Invalid = true;
3024 } else {
3025 // If the type is currently being defined, complain
3026 // about a nested redefinition.
3027 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
3028 if (Tag->isBeingDefined()) {
3029 Diag(NameLoc, diag::err_nested_redefinition) << Name;
3030 Diag(PrevTagDecl->getLocation(),
3031 diag::note_previous_definition);
3032 Name = 0;
3033 PrevDecl = 0;
3034 Invalid = true;
3035 }
Douglas Gregorae644892008-12-15 16:32:14 +00003036 }
Douglas Gregor98b27542009-01-17 00:42:38 +00003037
Douglas Gregorae644892008-12-15 16:32:14 +00003038 // Okay, this is definition of a previously declared or referenced
3039 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor98b27542009-01-17 00:42:38 +00003040 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00003041 }
Douglas Gregorae644892008-12-15 16:32:14 +00003042 // If we get here we have (another) forward declaration or we
3043 // have a definition. Just create a new decl.
3044 } else {
3045 // If we get here, this is a definition of a new tag type in a nested
3046 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
3047 // new decl/type. We set PrevDecl to NULL so that the entities
3048 // have distinct types.
3049 PrevDecl = 0;
Chris Lattner4b009652007-07-25 00:24:17 +00003050 }
Douglas Gregorae644892008-12-15 16:32:14 +00003051 // If we get here, we're going to create a new Decl. If PrevDecl
3052 // is non-NULL, it's a definition of the tag declared by
3053 // PrevDecl. If it's NULL, we have a new definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00003054 } else {
Douglas Gregorb31f2942009-01-28 17:15:10 +00003055 // PrevDecl is a namespace, template, or anything else
3056 // that lives in the IDNS_Tag identifier namespace.
Douglas Gregorb748fc52009-01-12 22:49:06 +00003057 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00003058 // The tag name clashes with a namespace name, issue an error and
3059 // recover by making this tag be anonymous.
Chris Lattner65cae292008-11-19 08:23:25 +00003060 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00003061 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00003062 Name = 0;
Douglas Gregorae644892008-12-15 16:32:14 +00003063 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00003064 Invalid = true;
Douglas Gregorae644892008-12-15 16:32:14 +00003065 } else {
3066 // The existing declaration isn't relevant to us; we're in a
3067 // new scope, so clear out the previous declaration.
3068 PrevDecl = 0;
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00003069 }
Chris Lattner4b009652007-07-25 00:24:17 +00003070 }
Douglas Gregorcab994d2009-01-09 22:42:13 +00003071 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
3072 (Kind != TagDecl::TK_enum)) {
3073 // C++ [basic.scope.pdecl]p5:
3074 // -- for an elaborated-type-specifier of the form
3075 //
3076 // class-key identifier
3077 //
3078 // if the elaborated-type-specifier is used in the
3079 // decl-specifier-seq or parameter-declaration-clause of a
3080 // function defined in namespace scope, the identifier is
3081 // declared as a class-name in the namespace that contains
3082 // the declaration; otherwise, except as a friend
3083 // declaration, the identifier is declared in the smallest
3084 // non-class, non-function-prototype scope that contains the
3085 // declaration.
3086 //
3087 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
3088 // C structs and unions.
3089
3090 // Find the context where we'll be declaring the tag.
Douglas Gregorb748fc52009-01-12 22:49:06 +00003091 // FIXME: We would like to maintain the current DeclContext as the
3092 // lexical context,
Douglas Gregorcab994d2009-01-09 22:42:13 +00003093 while (DC->isRecord())
3094 DC = DC->getParent();
3095 LexicalContext = DC;
3096
3097 // Find the scope where we'll be declaring the tag.
3098 while (S->isClassScope() ||
3099 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003100 ((S->getFlags() & Scope::DeclScope) == 0) ||
3101 (S->getEntity() &&
3102 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregorcab994d2009-01-09 22:42:13 +00003103 S = S->getParent();
Chris Lattner4b009652007-07-25 00:24:17 +00003104 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00003105
Chris Lattner9bb9abf2008-12-17 07:13:27 +00003106CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00003107
3108 // If there is an identifier, use the location of the identifier as the
3109 // location of the decl, otherwise use the location of the struct/union
3110 // keyword.
3111 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3112
Douglas Gregorae644892008-12-15 16:32:14 +00003113 // Otherwise, create a new declaration. If there is a previous
3114 // declaration of the same entity, the two will be linked via
3115 // PrevDecl.
Chris Lattner4b009652007-07-25 00:24:17 +00003116 TagDecl *New;
Douglas Gregor723d3332009-01-07 00:43:41 +00003117
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003118 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00003119 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3120 // enum X { A, B, C } D; D should chain to X.
Douglas Gregorae644892008-12-15 16:32:14 +00003121 New = EnumDecl::Create(Context, DC, Loc, Name,
3122 cast_or_null<EnumDecl>(PrevDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003123 // If this is an undefined enum, warn.
3124 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003125 } else {
3126 // struct/union/class
3127
Chris Lattner4b009652007-07-25 00:24:17 +00003128 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3129 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003130 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00003131 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregorae644892008-12-15 16:32:14 +00003132 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
3133 cast_or_null<CXXRecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003134 else
Douglas Gregorae644892008-12-15 16:32:14 +00003135 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
3136 cast_or_null<RecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003137 }
Douglas Gregorae644892008-12-15 16:32:14 +00003138
3139 if (Kind != TagDecl::TK_enum) {
3140 // Handle #pragma pack: if the #pragma pack stack has non-default
3141 // alignment, make up a packed attribute for this decl. These
3142 // attributes are checked when the ASTContext lays out the
3143 // structure.
3144 //
3145 // It is important for implementing the correct semantics that this
3146 // happen here (in act on tag decl). The #pragma pack stack is
3147 // maintained as a result of parser callbacks which can occur at
3148 // many points during the parsing of a struct declaration (because
3149 // the #pragma tokens are effectively skipped over during the
3150 // parsing of the struct).
3151 if (unsigned Alignment = PackContext.getAlignment())
3152 New->addAttr(new PackedAttr(Alignment * 8));
3153 }
3154
Douglas Gregorb31f2942009-01-28 17:15:10 +00003155 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
3156 // C++ [dcl.typedef]p3:
3157 // [...] Similarly, in a given scope, a class or enumeration
3158 // shall not be declared with the same name as a typedef-name
3159 // that is declared in that scope and refers to a type other
3160 // than the class or enumeration itself.
3161 LookupResult Lookup = LookupName(S, Name,
3162 LookupCriteria(LookupCriteria::Ordinary,
3163 true, true));
3164 TypedefDecl *PrevTypedef = 0;
3165 if (Lookup.getKind() == LookupResult::Found)
3166 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
3167
3168 if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
3169 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
3170 Context.getCanonicalType(Context.getTypeDeclType(New))) {
3171 Diag(Loc, diag::err_tag_definition_of_typedef)
3172 << Context.getTypeDeclType(New)
3173 << PrevTypedef->getUnderlyingType();
3174 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
3175 Invalid = true;
3176 }
3177 }
3178
Douglas Gregor98b27542009-01-17 00:42:38 +00003179 if (Invalid)
3180 New->setInvalidDecl();
3181
Douglas Gregorae644892008-12-15 16:32:14 +00003182 if (Attr)
3183 ProcessDeclAttributeList(New, Attr);
3184
Douglas Gregor98b27542009-01-17 00:42:38 +00003185 // If we're declaring or defining a tag in function prototype scope
3186 // in C, note that this type can only be used within the function.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003187 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3188 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3189
Douglas Gregorae644892008-12-15 16:32:14 +00003190 // Set the lexical context. If the tag has a C++ scope specifier, the
3191 // lexical context will be different from the semantic context.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003192 New->setLexicalDeclContext(LexicalContext);
Douglas Gregor98b27542009-01-17 00:42:38 +00003193
3194 if (TK == TK_Definition)
3195 New->startDefinition();
Chris Lattner4b009652007-07-25 00:24:17 +00003196
3197 // If this has an identifier, add it to the scope stack.
3198 if (Name) {
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003199 S = getNonFieldDeclScope(S);
Chris Lattnera7549902007-08-26 06:24:45 +00003200
3201 // Add it to the decl chain.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003202 if (LexicalContext != CurContext) {
3203 // FIXME: PushOnScopeChains should not rely on CurContext!
3204 DeclContext *OldContext = CurContext;
3205 CurContext = LexicalContext;
3206 PushOnScopeChains(New, S);
3207 CurContext = OldContext;
3208 } else
3209 PushOnScopeChains(New, S);
Douglas Gregorb748fc52009-01-12 22:49:06 +00003210 } else {
Douglas Gregor03b2ad22009-01-12 23:27:07 +00003211 LexicalContext->addDecl(New);
Chris Lattner4b009652007-07-25 00:24:17 +00003212 }
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00003213
Chris Lattner4b009652007-07-25 00:24:17 +00003214 return New;
3215}
3216
Douglas Gregordb568cf2009-01-08 20:45:30 +00003217void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3218 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3219
3220 // Enter the tag context.
3221 PushDeclContext(S, Tag);
3222
3223 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3224 FieldCollector->StartClass();
3225
3226 if (Record->getIdentifier()) {
3227 // C++ [class]p2:
3228 // [...] The class-name is also inserted into the scope of the
3229 // class itself; this is known as the injected-class-name. For
3230 // purposes of access checking, the injected-class-name is treated
3231 // as if it were a public member name.
3232 RecordDecl *InjectedClassName
3233 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3234 CurContext, Record->getLocation(),
3235 Record->getIdentifier(), Record);
3236 InjectedClassName->setImplicit();
3237 PushOnScopeChains(InjectedClassName, S);
3238 }
3239 }
3240}
3241
3242void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3243 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3244
3245 if (isa<CXXRecordDecl>(Tag))
3246 FieldCollector->FinishClass();
3247
3248 // Exit this scope of this tag's definition.
3249 PopDeclContext();
3250
3251 // Notify the consumer that we've defined a tag.
3252 Consumer.HandleTagDeclDefinition(Tag);
3253}
Chris Lattner1bf58f62008-06-21 19:39:06 +00003254
Chris Lattnera73e2202008-11-12 21:17:48 +00003255/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3256/// types into constant array types in certain situations which would otherwise
3257/// be errors (for GCC compatibility).
3258static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3259 ASTContext &Context) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003260 // This method tries to turn a variable array into a constant
3261 // array even when the size isn't an ICE. This is necessary
3262 // for compatibility with code that depends on gcc's buggy
3263 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003264 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3265 if (!VLATy) return QualType();
3266
Anders Carlsson8c3de802008-12-19 20:58:05 +00003267 Expr::EvalResult EvalResult;
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003268 if (!VLATy->getSizeExpr() ||
Anders Carlsson8c3de802008-12-19 20:58:05 +00003269 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003270 return QualType();
3271
Anders Carlsson8c3de802008-12-19 20:58:05 +00003272 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3273 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003274 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3275 return Context.getConstantArrayType(VLATy->getElementType(),
3276 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003277 return QualType();
3278}
3279
Anders Carlsson108229a2008-12-06 20:33:04 +00003280bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattner8464c372008-12-12 04:56:04 +00003281 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson108229a2008-12-06 20:33:04 +00003282 // FIXME: 6.7.2.1p4 - verify the field type.
3283
3284 llvm::APSInt Value;
3285 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3286 return true;
3287
Chris Lattner8464c372008-12-12 04:56:04 +00003288 // Zero-width bitfield is ok for anonymous field.
3289 if (Value == 0 && FieldName)
3290 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3291
3292 if (Value.isNegative())
3293 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson108229a2008-12-06 20:33:04 +00003294
3295 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3296 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattner8464c372008-12-12 04:56:04 +00003297 if (TypeSize && Value.getZExtValue() > TypeSize)
3298 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3299 << FieldName << (unsigned)TypeSize;
Anders Carlsson108229a2008-12-06 20:33:04 +00003300
3301 return false;
3302}
3303
Steve Naroff0acc9c92007-09-15 18:49:24 +00003304/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00003305/// to create a FieldDecl object for it.
Douglas Gregor8acb7272008-12-11 16:49:14 +00003306Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Chris Lattner4b009652007-07-25 00:24:17 +00003307 SourceLocation DeclStart,
3308 Declarator &D, ExprTy *BitfieldWidth) {
3309 IdentifierInfo *II = D.getIdentifier();
3310 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00003311 SourceLocation Loc = DeclStart;
Douglas Gregor8acb7272008-12-11 16:49:14 +00003312 RecordDecl *Record = (RecordDecl *)TagD;
Chris Lattner4b009652007-07-25 00:24:17 +00003313 if (II) Loc = D.getIdentifierLoc();
3314
3315 // FIXME: Unnamed fields can be handled in various different ways, for
3316 // example, unnamed unions inject all members into the struct namespace!
Chris Lattner4b009652007-07-25 00:24:17 +00003317
Chris Lattner4b009652007-07-25 00:24:17 +00003318 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003319 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3320 bool InvalidDecl = false;
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003321
Chris Lattner4b009652007-07-25 00:24:17 +00003322 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3323 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00003324 if (T->isVariablyModifiedType()) {
Chris Lattnera73e2202008-11-12 21:17:48 +00003325 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003326 if (!FixedTy.isNull()) {
Chris Lattner86be8572008-11-13 18:49:38 +00003327 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003328 T = FixedTy;
3329 } else {
Chris Lattner86be8572008-11-13 18:49:38 +00003330 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner2a884752008-11-12 19:45:49 +00003331 T = Context.IntTy;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003332 InvalidDecl = true;
3333 }
Chris Lattner4b009652007-07-25 00:24:17 +00003334 }
Anders Carlsson108229a2008-12-06 20:33:04 +00003335
3336 if (BitWidth) {
3337 if (VerifyBitField(Loc, II, T, BitWidth))
3338 InvalidDecl = true;
3339 } else {
3340 // Not a bitfield.
3341
3342 // validate II.
3343
3344 }
3345
Chris Lattner4b009652007-07-25 00:24:17 +00003346 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003347 FieldDecl *NewFD;
3348
Douglas Gregor8acb7272008-12-11 16:49:14 +00003349 NewFD = FieldDecl::Create(Context, Record,
3350 Loc, II, T, BitWidth,
3351 D.getDeclSpec().getStorageClassSpec() ==
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003352 DeclSpec::SCS_mutable);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003353
Douglas Gregordb568cf2009-01-08 20:45:30 +00003354 if (II) {
3355 Decl *PrevDecl
Steve Naroffc349ee22009-01-29 00:07:50 +00003356 = LookupDeclInScope(II, Decl::IDNS_Member, S, false);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003357 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3358 && !isa<TagDecl>(PrevDecl)) {
3359 Diag(Loc, diag::err_duplicate_member) << II;
3360 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3361 NewFD->setInvalidDecl();
3362 Record->setInvalidDecl();
3363 }
3364 }
3365
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003366 if (getLangOptions().CPlusPlus) {
Douglas Gregor605de8d2008-12-16 21:30:33 +00003367 CheckExtraCXXDefaultArguments(D);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003368 if (!T->isPODType())
3369 cast<CXXRecordDecl>(Record)->setPOD(false);
3370 }
Douglas Gregor605de8d2008-12-16 21:30:33 +00003371
Chris Lattner9b384ca2008-06-29 00:02:00 +00003372 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00003373
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003374 if (D.getInvalidType() || InvalidDecl)
3375 NewFD->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00003376
Douglas Gregordb568cf2009-01-08 20:45:30 +00003377 if (II) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003378 PushOnScopeChains(NewFD, S);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003379 } else
Douglas Gregor03b2ad22009-01-12 23:27:07 +00003380 Record->addDecl(NewFD);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003381
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003382 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00003383}
3384
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003385/// TranslateIvarVisibility - Translate visibility from a token ID to an
3386/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00003387static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003388TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00003389 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00003390 default: assert(0 && "Unknown visitibility kind");
3391 case tok::objc_private: return ObjCIvarDecl::Private;
3392 case tok::objc_public: return ObjCIvarDecl::Public;
3393 case tok::objc_protected: return ObjCIvarDecl::Protected;
3394 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00003395 }
3396}
3397
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003398/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3399/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003400Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003401 SourceLocation DeclStart,
3402 Declarator &D, ExprTy *BitfieldWidth,
3403 tok::ObjCKeywordKind Visibility) {
Douglas Gregordb568cf2009-01-08 20:45:30 +00003404
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003405 IdentifierInfo *II = D.getIdentifier();
3406 Expr *BitWidth = (Expr*)BitfieldWidth;
3407 SourceLocation Loc = DeclStart;
3408 if (II) Loc = D.getIdentifierLoc();
3409
3410 // FIXME: Unnamed fields can be handled in various different ways, for
3411 // example, unnamed unions inject all members into the struct namespace!
3412
Anders Carlsson108229a2008-12-06 20:33:04 +00003413 QualType T = GetTypeForDeclarator(D, S);
3414 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3415 bool InvalidDecl = false;
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003416
3417 if (BitWidth) {
3418 // TODO: Validate.
3419 //printf("WARNING: BITFIELDS IGNORED!\n");
3420
3421 // 6.7.2.1p3
3422 // 6.7.2.1p4
3423
3424 } else {
3425 // Not a bitfield.
3426
3427 // validate II.
3428
3429 }
3430
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003431 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3432 // than a variably modified type.
3433 if (T->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00003434 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003435 InvalidDecl = true;
3436 }
3437
Ted Kremenek173dd312008-07-23 18:04:17 +00003438 // Get the visibility (access control) for this ivar.
3439 ObjCIvarDecl::AccessControl ac =
3440 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3441 : ObjCIvarDecl::None;
3442
3443 // Construct the decl.
3444 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00003445 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003446
Douglas Gregordb568cf2009-01-08 20:45:30 +00003447 if (II) {
Steve Naroffc349ee22009-01-29 00:07:50 +00003448 Decl *PrevDecl = LookupDeclInScope(II, Decl::IDNS_Member, S, false);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003449 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3450 && !isa<TagDecl>(PrevDecl)) {
3451 Diag(Loc, diag::err_duplicate_member) << II;
3452 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3453 NewID->setInvalidDecl();
3454 }
3455 }
3456
Ted Kremenek173dd312008-07-23 18:04:17 +00003457 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00003458 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003459
3460 if (D.getInvalidType() || InvalidDecl)
3461 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00003462
Douglas Gregordb568cf2009-01-08 20:45:30 +00003463 if (II) {
3464 // FIXME: When interfaces are DeclContexts, we'll need to add
3465 // these to the interface.
3466 S->AddDecl(NewID);
3467 IdResolver.AddDecl(NewID);
3468 }
3469
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003470 return NewID;
3471}
3472
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00003473void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003474 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00003475 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00003476 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00003477 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003478 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3479 assert(EnclosingDecl && "missing record or interface decl");
3480 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3481
Chris Lattner4b009652007-07-25 00:24:17 +00003482 // Verify that all the fields are okay.
3483 unsigned NumNamedMembers = 0;
3484 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorc7f01612009-01-07 19:46:03 +00003485
Chris Lattner4b009652007-07-25 00:24:17 +00003486 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003487 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3488 assert(FD && "missing field decl");
3489
Chris Lattner4b009652007-07-25 00:24:17 +00003490 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00003491 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorc7f01612009-01-07 19:46:03 +00003492
Douglas Gregordb568cf2009-01-08 20:45:30 +00003493 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorc7f01612009-01-07 19:46:03 +00003494 // Remember all fields written by the user.
3495 RecFields.push_back(FD);
3496 }
Steve Naroffffeaa552007-09-14 23:09:53 +00003497
Chris Lattner4b009652007-07-25 00:24:17 +00003498 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00003499 if (FDTy->isFunctionType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003500 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattner271d4c22008-11-24 05:29:24 +00003501 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003502 FD->setInvalidDecl();
3503 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003504 continue;
3505 }
Chris Lattner4b009652007-07-25 00:24:17 +00003506 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3507 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003508 if (!Record) { // Incomplete ivar type is always an error.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003509 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3510 diag::err_field_incomplete);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003511 FD->setInvalidDecl();
3512 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003513 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003514 }
Chris Lattner4b009652007-07-25 00:24:17 +00003515 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003516 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00003517 !FDTy->isArrayType()) { //... may have incomplete array type.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003518 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3519 diag::err_field_incomplete);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003520 FD->setInvalidDecl();
3521 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003522 continue;
3523 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003524 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003525 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003526 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003527 FD->setInvalidDecl();
3528 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003529 continue;
3530 }
Chris Lattner4b009652007-07-25 00:24:17 +00003531 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003532 if (Record)
3533 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003534 }
Chris Lattner4b009652007-07-25 00:24:17 +00003535 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3536 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00003537 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003538 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3539 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003540 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003541 Record->setHasFlexibleArrayMember(true);
3542 } else {
3543 // If this is a struct/class and this is not the last element, reject
3544 // it. Note that GCC supports variable sized arrays in the middle of
3545 // structures.
3546 if (i != NumFields-1) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003547 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003548 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003549 FD->setInvalidDecl();
3550 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003551 continue;
3552 }
Chris Lattner4b009652007-07-25 00:24:17 +00003553 // We support flexible arrays at the end of structs in other structs
3554 // as an extension.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003555 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003556 << FD->getDeclName();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003557 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003558 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003559 }
3560 }
3561 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003562 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00003563 if (FDTy->isObjCInterfaceType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003564 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattnerb1753422008-11-23 21:45:46 +00003565 << FD->getDeclName();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003566 FD->setInvalidDecl();
3567 EnclosingDecl->setInvalidDecl();
3568 continue;
3569 }
Chris Lattner4b009652007-07-25 00:24:17 +00003570 // Keep track of the number of named members.
Douglas Gregordb568cf2009-01-08 20:45:30 +00003571 if (FD->getIdentifier())
Chris Lattner4b009652007-07-25 00:24:17 +00003572 ++NumNamedMembers;
Chris Lattner4b009652007-07-25 00:24:17 +00003573 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003574
Chris Lattner4b009652007-07-25 00:24:17 +00003575 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00003576 if (Record) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003577 Record->completeDefinition(Context);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003578 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003579 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003580 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003581 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003582 // Must enforce the rule that ivars in the base classes may not be
3583 // duplicates.
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003584 if (ID->getSuperClass()) {
3585 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3586 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3587 ObjCIvarDecl* Ivar = (*IVI);
3588 IdentifierInfo *II = Ivar->getIdentifier();
3589 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3590 if (prevIvar) {
3591 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregordb568cf2009-01-08 20:45:30 +00003592 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003593 }
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003594 }
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003595 }
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003596 }
Chris Lattner1100cfb2008-02-05 22:40:55 +00003597 else if (ObjCImplementationDecl *IMPDecl =
3598 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003599 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3600 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00003601 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00003602 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00003603 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00003604
3605 if (Attr)
3606 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00003607}
3608
Steve Naroff0acc9c92007-09-15 18:49:24 +00003609Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00003610 DeclTy *lastEnumConst,
3611 SourceLocation IdLoc, IdentifierInfo *Id,
3612 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00003613 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003614 EnumConstantDecl *LastEnumConst =
3615 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3616 Expr *Val = static_cast<Expr*>(val);
3617
Chris Lattnera7549902007-08-26 06:24:45 +00003618 // The scope passed in may not be a decl scope. Zip up the scope tree until
3619 // we find one that is.
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003620 S = getNonFieldDeclScope(S);
Chris Lattnera7549902007-08-26 06:24:45 +00003621
Chris Lattner4b009652007-07-25 00:24:17 +00003622 // Verify that there isn't already something declared with this name in this
3623 // scope.
Steve Naroffc349ee22009-01-29 00:07:50 +00003624 Decl *PrevDecl = LookupDeclInScope(Id, Decl::IDNS_Ordinary, S);
Douglas Gregor2715a1f2008-12-08 18:40:42 +00003625 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00003626 // Maybe we will complain about the shadowed template parameter.
3627 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3628 // Just pretend that we didn't see the previous declaration.
3629 PrevDecl = 0;
3630 }
3631
3632 if (PrevDecl) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00003633 // When in C++, we may get a TagDecl with the same name; in this case the
3634 // enum constant will 'hide' the tag.
3635 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3636 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00003637 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003638 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner65cae292008-11-19 08:23:25 +00003639 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner4b009652007-07-25 00:24:17 +00003640 else
Chris Lattner65cae292008-11-19 08:23:25 +00003641 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner1336cab2008-11-23 23:12:31 +00003642 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003643 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00003644 return 0;
3645 }
3646 }
3647
3648 llvm::APSInt EnumVal(32);
3649 QualType EltTy;
3650 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00003651 // Make sure to promote the operand type to int.
3652 UsualUnaryConversions(Val);
3653
Chris Lattner4b009652007-07-25 00:24:17 +00003654 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3655 SourceLocation ExpLoc;
Anders Carlsson5374c6b2008-12-05 16:33:57 +00003656 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003657 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00003658 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00003659 } else {
3660 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003661 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00003662 }
3663
3664 if (!Val) {
3665 if (LastEnumConst) {
3666 // Assign the last value + 1.
3667 EnumVal = LastEnumConst->getInitVal();
3668 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00003669
3670 // Check for overflow on increment.
3671 if (EnumVal < LastEnumConst->getInitVal())
3672 Diag(IdLoc, diag::warn_enum_value_overflow);
3673
Chris Lattnere7f53a42007-08-27 17:37:24 +00003674 EltTy = LastEnumConst->getType();
3675 } else {
3676 // First value, set to zero.
3677 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003678 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00003679 }
Chris Lattner4b009652007-07-25 00:24:17 +00003680 }
3681
Chris Lattnere4650482008-03-15 06:12:44 +00003682 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00003683 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003684 Val, EnumVal);
Chris Lattner4b009652007-07-25 00:24:17 +00003685
3686 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00003687 PushOnScopeChains(New, S);
Douglas Gregor0c3ab042008-12-17 02:04:30 +00003688
Chris Lattner4b009652007-07-25 00:24:17 +00003689 return New;
3690}
3691
Steve Naroffb0726b82008-08-07 14:08:16 +00003692// FIXME: For consistency with ActOnFields(), we should have the parser
3693// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00003694void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00003695 DeclTy **Elements, unsigned NumElements) {
3696 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregord8028382009-01-05 19:45:36 +00003697 QualType EnumType = Context.getTypeDeclType(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003698
Chris Lattner435c3fd2007-08-28 05:10:31 +00003699 // TODO: If the result value doesn't fit in an int, it must be a long or long
3700 // long value. ISO C does not support this, but GCC does as an extension,
3701 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00003702 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00003703
Chris Lattner206754a2007-08-28 06:15:15 +00003704 // Verify that all the values are okay, compute the size of the values, and
3705 // reverse the list.
3706 unsigned NumNegativeBits = 0;
3707 unsigned NumPositiveBits = 0;
3708
3709 // Keep track of whether all elements have type int.
3710 bool AllElementsInt = true;
3711
Chris Lattner4b009652007-07-25 00:24:17 +00003712 for (unsigned i = 0; i != NumElements; ++i) {
3713 EnumConstantDecl *ECD =
3714 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3715 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003716
3717 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003718 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003719 assert(InitVal.getBitWidth() >= IntWidth &&
3720 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00003721 if (InitVal.getBitWidth() > IntWidth) {
3722 llvm::APSInt V(InitVal);
3723 V.trunc(IntWidth);
3724 V.extend(InitVal.getBitWidth());
3725 if (V != InitVal)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003726 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3727 << InitVal.toString(10);
Chris Lattnercb33ae12007-08-28 05:27:00 +00003728 }
Chris Lattner206754a2007-08-28 06:15:15 +00003729
3730 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003731 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00003732 NumPositiveBits = std::max(NumPositiveBits,
3733 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00003734 else
Chris Lattneraff63f02008-01-14 21:47:29 +00003735 NumNegativeBits = std::max(NumNegativeBits,
3736 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00003737
Chris Lattner206754a2007-08-28 06:15:15 +00003738 // Keep track of whether every enum element has type int (very commmon).
3739 if (AllElementsInt)
3740 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003741 }
3742
Chris Lattner206754a2007-08-28 06:15:15 +00003743 // Figure out the type that should be used for this enum.
3744 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3745 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003746 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00003747
3748 if (NumNegativeBits) {
3749 // If there is a negative value, figure out the smallest integer type (of
3750 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003751 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003752 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003753 BestWidth = IntWidth;
3754 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003755 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003756
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003757 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003758 BestType = Context.LongTy;
3759 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003760 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003761
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003762 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003763 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3764 BestType = Context.LongLongTy;
3765 }
3766 }
3767 } else {
3768 // If there is no negative value, figure out which of uint, ulong, ulonglong
3769 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003770 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003771 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003772 BestWidth = IntWidth;
3773 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00003774 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00003775 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003776 } else {
3777 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003778 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00003779 "How could an initializer get larger than ULL?");
3780 BestType = Context.UnsignedLongLongTy;
3781 }
3782 }
3783
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003784 // Loop over all of the enumerator constants, changing their types to match
3785 // the type of the enum if needed.
3786 for (unsigned i = 0; i != NumElements; ++i) {
3787 EnumConstantDecl *ECD =
3788 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3789 if (!ECD) continue; // Already issued a diagnostic.
3790
3791 // Standard C says the enumerators have int type, but we allow, as an
3792 // extension, the enumerators to be larger than int size. If each
3793 // enumerator value fits in an int, type it as an int, otherwise type it the
3794 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3795 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003796 if (ECD->getType() == Context.IntTy) {
3797 // Make sure the init value is signed.
3798 llvm::APSInt IV = ECD->getInitVal();
3799 IV.setIsSigned(true);
3800 ECD->setInitVal(IV);
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003801
3802 if (getLangOptions().CPlusPlus)
3803 // C++ [dcl.enum]p4: Following the closing brace of an
3804 // enum-specifier, each enumerator has the type of its
3805 // enumeration.
3806 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003807 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003808 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003809
3810 // Determine whether the value fits into an int.
3811 llvm::APSInt InitVal = ECD->getInitVal();
3812 bool FitsInInt;
3813 if (InitVal.isUnsigned() || !InitVal.isNegative())
3814 FitsInInt = InitVal.getActiveBits() < IntWidth;
3815 else
3816 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3817
3818 // If it fits into an integer type, force it. Otherwise force it to match
3819 // the enum decl type.
3820 QualType NewTy;
3821 unsigned NewWidth;
3822 bool NewSign;
3823 if (FitsInInt) {
3824 NewTy = Context.IntTy;
3825 NewWidth = IntWidth;
3826 NewSign = true;
3827 } else if (ECD->getType() == BestType) {
3828 // Already the right type!
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003829 if (getLangOptions().CPlusPlus)
3830 // C++ [dcl.enum]p4: Following the closing brace of an
3831 // enum-specifier, each enumerator has the type of its
3832 // enumeration.
3833 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003834 continue;
3835 } else {
3836 NewTy = BestType;
3837 NewWidth = BestWidth;
3838 NewSign = BestType->isSignedIntegerType();
3839 }
3840
3841 // Adjust the APSInt value.
3842 InitVal.extOrTrunc(NewWidth);
3843 InitVal.setIsSigned(NewSign);
3844 ECD->setInitVal(InitVal);
3845
3846 // Adjust the Expr initializer and type.
Chris Lattner8c6dc7a2009-01-15 19:19:42 +00003847 if (ECD->getInitExpr())
3848 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3849 /*isLvalue=*/false));
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003850 if (getLangOptions().CPlusPlus)
3851 // C++ [dcl.enum]p4: Following the closing brace of an
3852 // enum-specifier, each enumerator has the type of its
3853 // enumeration.
3854 ECD->setType(EnumType);
3855 else
3856 ECD->setType(NewTy);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003857 }
Chris Lattner206754a2007-08-28 06:15:15 +00003858
Douglas Gregor8acb7272008-12-11 16:49:14 +00003859 Enum->completeDefinition(Context, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00003860}
3861
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003862Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00003863 ExprArg expr) {
3864 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3865
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003866 return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003867}
3868
Douglas Gregorad17e372008-12-16 22:23:02 +00003869
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003870void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3871 ExprTy *alignment, SourceLocation PragmaLoc,
3872 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3873 Expr *Alignment = static_cast<Expr *>(alignment);
3874
3875 // If specified then alignment must be a "small" power of two.
3876 unsigned AlignmentVal = 0;
3877 if (Alignment) {
3878 llvm::APSInt Val;
3879 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3880 !Val.isPowerOf2() ||
3881 Val.getZExtValue() > 16) {
3882 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3883 delete Alignment;
3884 return; // Ignore
3885 }
3886
3887 AlignmentVal = (unsigned) Val.getZExtValue();
3888 }
3889
3890 switch (Kind) {
3891 case Action::PPK_Default: // pack([n])
3892 PackContext.setAlignment(AlignmentVal);
3893 break;
3894
3895 case Action::PPK_Show: // pack(show)
3896 // Show the current alignment, making sure to show the right value
3897 // for the default.
3898 AlignmentVal = PackContext.getAlignment();
3899 // FIXME: This should come from the target.
3900 if (AlignmentVal == 0)
3901 AlignmentVal = 8;
Chris Lattnera5cc1882008-11-19 07:25:44 +00003902 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003903 break;
3904
3905 case Action::PPK_Push: // pack(push [, id] [, [n])
3906 PackContext.push(Name);
3907 // Set the new alignment if specified.
3908 if (Alignment)
3909 PackContext.setAlignment(AlignmentVal);
3910 break;
3911
3912 case Action::PPK_Pop: // pack(pop [, id] [, n])
3913 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3914 // "#pragma pack(pop, identifier, n) is undefined"
3915 if (Alignment && Name)
3916 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3917
3918 // Do the pop.
3919 if (!PackContext.pop(Name)) {
3920 // If a name was specified then failure indicates the name
3921 // wasn't found. Otherwise failure indicates the stack was
3922 // empty.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003923 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3924 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003925
3926 // FIXME: Warn about popping named records as MSVC does.
3927 } else {
3928 // Pop succeeded, set the new alignment if specified.
3929 if (Alignment)
3930 PackContext.setAlignment(AlignmentVal);
3931 }
3932 break;
3933
3934 default:
3935 assert(0 && "Invalid #pragma pack kind.");
3936 }
3937}
3938
3939bool PragmaPackStack::pop(IdentifierInfo *Name) {
3940 if (Stack.empty())
3941 return false;
3942
3943 // If name is empty just pop top.
3944 if (!Name) {
3945 Alignment = Stack.back().first;
3946 Stack.pop_back();
3947 return true;
3948 }
3949
3950 // Otherwise, find the named record.
3951 for (unsigned i = Stack.size(); i != 0; ) {
3952 --i;
Daniel Dunbarc13c54c2008-11-19 10:32:38 +00003953 if (Stack[i].second == Name) {
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003954 // Found it, pop up to and including this record.
3955 Alignment = Stack[i].first;
3956 Stack.erase(Stack.begin() + i, Stack.end());
3957 return true;
3958 }
3959 }
3960
3961 return false;
3962}