blob: 21fe6e1ce4924e0538c6388041980d0cbfe72d47 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-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 Lattnere1e79852008-02-06 00:51:33 +000024#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000025#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "llvm/ADT/SmallSet.h"
Douglas Gregore267ff32008-12-11 20:41:00 +000027#include "llvm/ADT/STLExtras.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000028#include <algorithm>
29#include <functional>
Douglas Gregore267ff32008-12-11 20:41:00 +000030
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32
Steve Naroffb43a50f2009-01-28 19:39:02 +000033Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, Scope *S,
34 const CXXScopeSpec *SS) {
Douglas Gregor7176fff2009-01-15 00:26:24 +000035 Decl *IIDecl = 0;
Douglas Gregor4c921ae2009-01-30 01:04:22 +000036 LookupResult Result = LookupParsedName(S, SS, &II, LookupOrdinaryName, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +000037 switch (Result.getKind()) {
Steve Naroffa5189032009-01-29 18:09:31 +000038 case LookupResult::NotFound:
39 case LookupResult::FoundOverloaded:
40 case LookupResult::AmbiguousBaseSubobjectTypes:
41 case LookupResult::AmbiguousBaseSubobjects:
42 // FIXME: In the event of an ambiguous lookup, we could visit all of
43 // the entities found to determine whether they are all types. This
44 // might provide better diagnostics.
45 return 0;
46 case LookupResult::Found:
47 IIDecl = Result.getAsDecl();
48 break;
Douglas Gregor7176fff2009-01-15 00:26:24 +000049 }
50
Steve Naroffa5189032009-01-29 18:09:31 +000051 if (IIDecl) {
52 if (isa<TypedefDecl>(IIDecl) ||
53 isa<ObjCInterfaceDecl>(IIDecl) ||
54 isa<TagDecl>(IIDecl) ||
55 isa<TemplateTypeParmDecl>(IIDecl))
56 return IIDecl;
57 }
Steve Naroff3536b442007-09-06 21:24:23 +000058 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000059}
60
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000061DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000062 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000063 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000064 if (MD->isOutOfLineDefinition())
65 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000066
67 // A C++ inline method is parsed *after* the topmost class it was declared in
68 // is fully parsed (it's "complete").
69 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000070 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000071 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
72 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000073 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000074 DC = RD;
75
76 // Return the declaration context of the topmost class the inline method is
77 // declared in.
78 return DC;
79 }
80
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000081 if (isa<ObjCMethodDecl>(DC))
82 return Context.getTranslationUnitDecl();
83
Douglas Gregor4afa39d2009-01-20 01:17:11 +000084 if (Decl *D = dyn_cast<Decl>(DC))
85 return D->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000086
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000087 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000088}
89
Douglas Gregor44b43212008-12-11 16:49:14 +000090void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000091 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +000092 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000093 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +000094 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +000095}
96
Chris Lattnerb048c982008-04-06 04:47:34 +000097void Sema::PopDeclContext() {
98 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +000099
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000100 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000101}
102
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000103/// Add this decl to the scope shadowed decl chains.
104void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000105 // Move up the scope chain until we find the nearest enclosing
106 // non-transparent context. The declaration will be introduced into this
107 // scope.
108 while (S->getEntity() &&
109 ((DeclContext *)S->getEntity())->isTransparentContext())
110 S = S->getParent();
111
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000112 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000113
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000114 // Add scoped declarations into their context, so that they can be
115 // found later. Declarations without a context won't be inserted
116 // into any context.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000117 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000118
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000119 // C++ [basic.scope]p4:
120 // -- exactly one declaration shall declare a class name or
121 // enumeration name that is not a typedef name and the other
122 // declarations shall all refer to the same object or
123 // enumerator, or all refer to functions and function templates;
124 // in this case the class name or enumeration name is hidden.
125 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
126 // We are pushing the name of a tag (enum or class).
Douglas Gregore21b9942009-01-07 16:34:42 +0000127 if (CurContext->getLookupContext()
128 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000129 // We're pushing the tag into the current context, which might
130 // require some reshuffling in the identifier resolver.
131 IdentifierResolver::iterator
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000132 I = IdResolver.begin(TD->getDeclName()),
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000133 IEnd = IdResolver.end();
134 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
135 NamedDecl *PrevDecl = *I;
136 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
137 PrevDecl = *I, ++I) {
138 if (TD->declarationReplaces(*I)) {
139 // This is a redeclaration. Remove it from the chain and
140 // break out, so that we'll add in the shadowed
141 // declaration.
142 S->RemoveDecl(*I);
143 if (PrevDecl == *I) {
144 IdResolver.RemoveDecl(*I);
145 IdResolver.AddDecl(TD);
146 return;
147 } else {
148 IdResolver.RemoveDecl(*I);
149 break;
150 }
151 }
152 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000153
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000154 // There is already a declaration with the same name in the same
155 // scope, which is not a tag declaration. It must be found
156 // before we find the new declaration, so insert the new
157 // declaration at the end of the chain.
158 IdResolver.AddShadowedDecl(TD, PrevDecl);
159
160 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000161 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000162 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000163 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000164 // We are pushing the name of a function, which might be an
165 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000166 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000167 IdentifierResolver::iterator Redecl
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000168 = std::find_if(IdResolver.begin(FD->getDeclName()),
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000169 IdResolver.end(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000170 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000171 FD));
172 if (Redecl != IdResolver.end()) {
173 // There is already a declaration of a function on our
174 // IdResolver chain. Replace it with this declaration.
175 S->RemoveDecl(*Redecl);
176 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000177 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000178 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000179
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000180 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000181}
182
Steve Naroffb216c882007-10-09 22:01:59 +0000183void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000184 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000185 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
186 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000187
Reid Spencer5f016e22007-07-11 17:01:13 +0000188 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
189 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000190 Decl *TmpD = static_cast<Decl*>(*I);
191 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000192
Douglas Gregor44b43212008-12-11 16:49:14 +0000193 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
194 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000195
Douglas Gregor44b43212008-12-11 16:49:14 +0000196 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000197
Douglas Gregor44b43212008-12-11 16:49:14 +0000198 // Remove this name from our lexical scope.
199 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000200 }
201}
202
Steve Naroffe8043c32008-04-01 23:04:06 +0000203/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
204/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000205ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000206 // The third "scope" argument is 0 since we aren't enabling lazy built-in
207 // creation from this context.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000208 Decl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000209
Steve Naroffb327ce02008-04-02 14:35:35 +0000210 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000211}
212
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000213/// getNonFieldDeclScope - Retrieves the innermost scope, starting
214/// from S, where a non-field would be declared. This routine copes
215/// with the difference between C and C++ scoping rules in structs and
216/// unions. For example, the following code is well-formed in C but
217/// ill-formed in C++:
218/// @code
219/// struct S6 {
220/// enum { BAR } e;
221/// };
222///
223/// void test_S6() {
224/// struct S6 a;
225/// a.e = BAR;
226/// }
227/// @endcode
228/// For the declaration of BAR, this routine will return a different
229/// scope. The scope S will be the scope of the unnamed enumeration
230/// within S6. In C++, this routine will return the scope associated
231/// with S6, because the enumeration's scope is a transparent
232/// context but structures can contain non-field names. In C, this
233/// routine will return the translation unit scope, since the
234/// enumeration's scope is a transparent context and structures cannot
235/// contain non-field names.
236Scope *Sema::getNonFieldDeclScope(Scope *S) {
237 while (((S->getFlags() & Scope::DeclScope) == 0) ||
238 (S->getEntity() &&
239 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
240 (S->isClassScope() && !getLangOptions().CPlusPlus))
241 S = S->getParent();
242 return S;
243}
244
Chris Lattner95e2c712008-05-05 22:18:14 +0000245void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000246 if (!Context.getBuiltinVaListType().isNull())
247 return;
248
249 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000250 Decl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
Steve Naroff733002f2007-10-18 22:17:45 +0000251 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000252 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
253}
254
Reid Spencer5f016e22007-07-11 17:01:13 +0000255/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
256/// lazily create a decl for it.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000257NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
258 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000259 Builtin::ID BID = (Builtin::ID)bid;
260
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000261 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000262 InitBuiltinVaListType();
263
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000264 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000265 FunctionDecl *New = FunctionDecl::Create(Context,
266 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000267 SourceLocation(), II, R,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000268 FunctionDecl::Extern, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000269
Chris Lattner95e2c712008-05-05 22:18:14 +0000270 // Create Decl objects for each parameter, adding them to the
271 // FunctionDecl.
272 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
273 llvm::SmallVector<ParmVarDecl*, 16> Params;
274 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
275 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000276 FT->getArgType(i), VarDecl::None, 0));
Ted Kremenekfc767612009-01-14 00:42:25 +0000277 New->setParams(Context, &Params[0], Params.size());
Chris Lattner95e2c712008-05-05 22:18:14 +0000278 }
279
280
281
Chris Lattner7f925cc2008-04-11 07:00:53 +0000282 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000283 // FIXME: This is hideous. We need to teach PushOnScopeChains to
284 // relate Scopes to DeclContexts, and probably eliminate CurContext
285 // entirely, but we're not there yet.
286 DeclContext *SavedContext = CurContext;
287 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000288 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000289 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000290 return New;
291}
292
Sebastian Redlc42e1182008-11-11 11:37:55 +0000293/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
294/// everything from the standard library is defined.
295NamespaceDecl *Sema::GetStdNamespace() {
296 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000297 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000298 DeclContext *Global = Context.getTranslationUnitDecl();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000299 Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000300 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
301 }
302 return StdNamespace;
303}
304
Reid Spencer5f016e22007-07-11 17:01:13 +0000305/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
306/// and scope as a previous declaration 'Old'. Figure out how to resolve this
307/// situation, merging decls or emitting diagnostics as appropriate.
308///
Steve Naroffe8043c32008-04-01 23:04:06 +0000309TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000310 bool objc_types = false;
Steve Naroff2b255c42008-09-09 14:32:20 +0000311 // Allow multiple definitions for ObjC built-in typedefs.
312 // FIXME: Verify the underlying types are equivalent!
313 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000314 const IdentifierInfo *TypeID = New->getIdentifier();
315 switch (TypeID->getLength()) {
316 default: break;
317 case 2:
318 if (!TypeID->isStr("id"))
319 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000320 Context.setObjCIdType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000321 objc_types = true;
322 break;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000323 case 5:
324 if (!TypeID->isStr("Class"))
325 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000326 Context.setObjCClassType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000327 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000328 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000329 case 3:
330 if (!TypeID->isStr("SEL"))
331 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000332 Context.setObjCSelType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000333 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000334 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000335 case 8:
336 if (!TypeID->isStr("Protocol"))
337 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000338 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000339 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000340 return New;
341 }
342 // Fall through - the typedef name was not a builtin type.
343 }
Douglas Gregor66973122009-01-28 17:15:10 +0000344 // Verify the old decl was also a type.
345 TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 if (!Old) {
Douglas Gregor66973122009-01-28 17:15:10 +0000347 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000348 << New->getDeclName();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000349 if (!objc_types)
350 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000351 return New;
352 }
Douglas Gregor66973122009-01-28 17:15:10 +0000353
354 // Determine the "old" type we'll use for checking and diagnostics.
355 QualType OldType;
356 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
357 OldType = OldTypedef->getUnderlyingType();
358 else
359 OldType = Context.getTypeDeclType(Old);
360
Chris Lattner99cb9972008-07-25 18:44:27 +0000361 // If the typedef types are not identical, reject them in all languages and
362 // with any extensions enabled.
Douglas Gregor66973122009-01-28 17:15:10 +0000363
364 if (OldType != New->getUnderlyingType() &&
365 Context.getCanonicalType(OldType) !=
Chris Lattner99cb9972008-07-25 18:44:27 +0000366 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000367 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregor66973122009-01-28 17:15:10 +0000368 << New->getUnderlyingType() << OldType;
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000369 if (!objc_types)
370 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000371 return New;
Chris Lattner99cb9972008-07-25 18:44:27 +0000372 }
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000373 if (objc_types) return New;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000374 if (getLangOptions().Microsoft) return New;
375
Douglas Gregorbbe27432008-11-21 16:29:06 +0000376 // C++ [dcl.typedef]p2:
377 // In a given non-class scope, a typedef specifier can be used to
378 // redefine the name of any type declared in that scope to refer
379 // to the type to which it already refers.
380 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
381 return New;
382
383 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000384 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
385 // *either* declaration is in a system header. The code below implements
386 // this adhoc compatibility rule. FIXME: The following code will not
387 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000388 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
389 SourceManager &SrcMgr = Context.getSourceManager();
390 if (SrcMgr.isInSystemHeader(Old->getLocation()))
391 return New;
392 if (SrcMgr.isInSystemHeader(New->getLocation()))
393 return New;
394 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000395
Chris Lattner08631c52008-11-23 21:45:46 +0000396 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000397 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 return New;
399}
400
Chris Lattner6b6b5372008-06-26 18:38:35 +0000401/// DeclhasAttr - returns true if decl Declaration already has the target
402/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000403static bool DeclHasAttr(const Decl *decl, const Attr *target) {
404 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
405 if (attr->getKind() == target->getKind())
406 return true;
407
408 return false;
409}
410
411/// MergeAttributes - append attributes from the Old decl to the New one.
412static void MergeAttributes(Decl *New, Decl *Old) {
413 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
414
Chris Lattnerddee4232008-03-03 03:28:21 +0000415 while (attr) {
416 tmp = attr;
417 attr = attr->getNext();
418
419 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000420 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000421 New->addAttr(tmp);
422 } else {
423 tmp->setNext(0);
424 delete(tmp);
425 }
426 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000427
428 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000429}
430
Chris Lattner04421082008-04-08 04:40:51 +0000431/// MergeFunctionDecl - We just parsed a function 'New' from
432/// declarator D which has the same name and scope as a previous
433/// declaration 'Old'. Figure out how to resolve this situation,
434/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000435/// Redeclaration will be set true if this New is a redeclaration OldD.
436///
437/// In C++, New and Old must be declarations that are not
438/// overloaded. Use IsOverload to determine whether New and Old are
439/// overloaded, and to select the Old declaration that New should be
440/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000441FunctionDecl *
442Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000443 assert(!isa<OverloadedFunctionDecl>(OldD) &&
444 "Cannot merge with an overloaded function declaration");
445
Douglas Gregorf0097952008-04-21 02:02:58 +0000446 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000447 // Verify the old decl was also a function.
448 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
449 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000450 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000451 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000452 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000453 return New;
454 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455
456 // Determine whether the previous declaration was a definition,
457 // implicit declaration, or a declaration.
458 diag::kind PrevDiag;
459 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000460 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000461 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000462 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000463 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000464 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000465
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000466 QualType OldQType = Context.getCanonicalType(Old->getType());
467 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000468
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000469 if (getLangOptions().CPlusPlus) {
470 // (C++98 13.1p2):
471 // Certain function declarations cannot be overloaded:
472 // -- Function declarations that differ only in the return type
473 // cannot be overloaded.
474 QualType OldReturnType
475 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
476 QualType NewReturnType
477 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
478 if (OldReturnType != NewReturnType) {
479 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
480 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000481 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000482 return New;
483 }
484
485 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
486 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
487 if (OldMethod && NewMethod) {
488 // -- Member function declarations with the same name and the
489 // same parameter types cannot be overloaded if any of them
490 // is a static member function declaration.
491 if (OldMethod->isStatic() || NewMethod->isStatic()) {
492 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
493 Diag(Old->getLocation(), PrevDiag);
494 return New;
495 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000496
497 // C++ [class.mem]p1:
498 // [...] A member shall not be declared twice in the
499 // member-specification, except that a nested class or member
500 // class template can be declared and then later defined.
501 if (OldMethod->getLexicalDeclContext() ==
502 NewMethod->getLexicalDeclContext()) {
503 unsigned NewDiag;
504 if (isa<CXXConstructorDecl>(OldMethod))
505 NewDiag = diag::err_constructor_redeclared;
506 else if (isa<CXXDestructorDecl>(NewMethod))
507 NewDiag = diag::err_destructor_redeclared;
508 else if (isa<CXXConversionDecl>(NewMethod))
509 NewDiag = diag::err_conv_function_redeclared;
510 else
511 NewDiag = diag::err_member_redeclared;
512
513 Diag(New->getLocation(), NewDiag);
514 Diag(Old->getLocation(), PrevDiag);
515 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000516 }
517
518 // (C++98 8.3.5p3):
519 // All declarations for a function shall agree exactly in both the
520 // return type and the parameter-type-list.
521 if (OldQType == NewQType) {
522 // We have a redeclaration.
523 MergeAttributes(New, Old);
524 Redeclaration = true;
525 return MergeCXXFunctionDecl(New, Old);
526 }
527
528 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000529 }
Chris Lattner04421082008-04-08 04:40:51 +0000530
531 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000532 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000533 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000534 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000535 MergeAttributes(New, Old);
536 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000537 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000538 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000539
Steve Naroff837618c2008-01-16 15:01:34 +0000540 // A function that has already been declared has been redeclared or defined
541 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000542
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
544 // TODO: This is totally simplistic. It should handle merging functions
545 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000546 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000547 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000548 return New;
549}
550
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000551/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000552static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000553 if (VD->isFileVarDecl())
554 return (!VD->getInit() &&
555 (VD->getStorageClass() == VarDecl::None ||
556 VD->getStorageClass() == VarDecl::Static));
557 return false;
558}
559
560/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
561/// when dealing with C "tentative" external object definitions (C99 6.9.2).
562void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
563 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000564 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000565
Douglas Gregore21b9942009-01-07 16:34:42 +0000566 // FIXME: I don't think this will actually see all of the
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000567 // redefinitions. Can't we check this property on-the-fly?
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000568 for (IdentifierResolver::iterator I = IdResolver.begin(VD->getIdentifier()),
569 E = IdResolver.end();
570 I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000571 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000572 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
573
Steve Narofff855e6f2008-08-10 15:20:13 +0000574 // Handle the following case:
575 // int a[10];
576 // int a[]; - the code below makes sure we set the correct type.
577 // int a[11]; - this is an error, size isn't 10.
578 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
579 OldDecl->getType()->isConstantArrayType())
580 VD->setType(OldDecl->getType());
581
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000582 // Check for "tentative" definitions. We can't accomplish this in
583 // MergeVarDecl since the initializer hasn't been attached.
584 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
585 continue;
586
587 // Handle __private_extern__ just like extern.
588 if (OldDecl->getStorageClass() != VarDecl::Extern &&
589 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
590 VD->getStorageClass() != VarDecl::Extern &&
591 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000592 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000593 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000594 }
595 }
596 }
597}
598
Reid Spencer5f016e22007-07-11 17:01:13 +0000599/// MergeVarDecl - We just parsed a variable 'New' which has the same name
600/// and scope as a previous declaration 'Old'. Figure out how to resolve this
601/// situation, merging decls or emitting diagnostics as appropriate.
602///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000603/// Tentative definition rules (C99 6.9.2p2) are checked by
604/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
605/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000606///
Steve Naroffe8043c32008-04-01 23:04:06 +0000607VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000608 // Verify the old decl was also a variable.
609 VarDecl *Old = dyn_cast<VarDecl>(OldD);
610 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000611 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000612 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000613 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000614 return New;
615 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000616
617 MergeAttributes(New, Old);
618
Eli Friedman13ca96a2009-01-24 23:49:55 +0000619 // Merge the types
620 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
621 if (MergedT.isNull()) {
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000622 Diag(New->getLocation(), diag::err_redefinition_different_type)
623 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000624 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000625 return New;
626 }
Eli Friedman13ca96a2009-01-24 23:49:55 +0000627 New->setType(MergedT);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000628 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
629 if (New->getStorageClass() == VarDecl::Static &&
630 (Old->getStorageClass() == VarDecl::None ||
631 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000632 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000633 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000634 return New;
635 }
636 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
637 if (New->getStorageClass() != VarDecl::Static &&
638 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000639 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000640 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000641 return New;
642 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000643 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
644 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000645 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000646 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000647 }
648 return New;
649}
650
Chris Lattner04421082008-04-08 04:40:51 +0000651/// CheckParmsForFunctionDef - Check that the parameters of the given
652/// function are appropriate for the definition of a function. This
653/// takes care of any checks that cannot be performed on the
654/// declaration itself, e.g., that the types of each of the function
655/// parameters are complete.
656bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
657 bool HasInvalidParm = false;
658 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
659 ParmVarDecl *Param = FD->getParamDecl(p);
660
661 // C99 6.7.5.3p4: the parameters in a parameter type list in a
662 // function declarator that is part of a function definition of
663 // that function shall not have incomplete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000664 if (!Param->isInvalidDecl() &&
665 DiagnoseIncompleteType(Param->getLocation(), Param->getType(),
666 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattner04421082008-04-08 04:40:51 +0000667 Param->setInvalidDecl();
668 HasInvalidParm = true;
669 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000670
671 // C99 6.9.1p5: If the declarator includes a parameter type list, the
672 // declaration of each parameter shall include an identifier.
673 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
674 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000675 }
676
677 return HasInvalidParm;
678}
679
Reid Spencer5f016e22007-07-11 17:01:13 +0000680/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
681/// no declarator (e.g. "struct foo;") is parsed.
682Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000683 TagDecl *Tag
684 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
685 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
686 if (!Record->getDeclName() && Record->isDefinition() &&
687 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
688 return BuildAnonymousStructOrUnion(S, DS, Record);
689
690 // Microsoft allows unnamed struct/union fields. Don't complain
691 // about them.
692 // FIXME: Should we support Microsoft's extensions in this area?
693 if (Record->getDeclName() && getLangOptions().Microsoft)
694 return Tag;
695 }
696
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000697 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregor21282df2009-01-22 16:23:54 +0000698 // Warn about typedefs of enums without names, since this is an
699 // extension in both Microsoft an GNU.
Douglas Gregor8158f692009-01-17 02:55:50 +0000700 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
701 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor21282df2009-01-22 16:23:54 +0000702 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregoree159c12009-01-13 23:10:51 +0000703 << DS.getSourceRange();
704 return Tag;
705 }
706
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000707 // FIXME: This diagnostic is emitted even when various previous
708 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
709 // DeclSpec has no means of communicating this information, and the
710 // responsible parser functions are quite far apart.
711 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
712 << DS.getSourceRange();
713 return 0;
714 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000715
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000716 return Tag;
717}
718
719/// InjectAnonymousStructOrUnionMembers - Inject the members of the
720/// anonymous struct or union AnonRecord into the owning context Owner
721/// and scope S. This routine will be invoked just after we realize
722/// that an unnamed union or struct is actually an anonymous union or
723/// struct, e.g.,
724///
725/// @code
726/// union {
727/// int i;
728/// float f;
729/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
730/// // f into the surrounding scope.x
731/// @endcode
732///
733/// This routine is recursive, injecting the names of nested anonymous
734/// structs/unions into the owning context and scope as well.
735bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
736 RecordDecl *AnonRecord) {
737 bool Invalid = false;
738 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
739 FEnd = AnonRecord->field_end();
740 F != FEnd; ++F) {
741 if ((*F)->getDeclName()) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000742 Decl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
743 LookupOrdinaryName, true);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000744 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
745 // C++ [class.union]p2:
746 // The names of the members of an anonymous union shall be
747 // distinct from the names of any other entity in the
748 // scope in which the anonymous union is declared.
749 unsigned diagKind
750 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
751 : diag::err_anonymous_struct_member_redecl;
752 Diag((*F)->getLocation(), diagKind)
753 << (*F)->getDeclName();
754 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
755 Invalid = true;
756 } else {
757 // C++ [class.union]p2:
758 // For the purpose of name lookup, after the anonymous union
759 // definition, the members of the anonymous union are
760 // considered to have been defined in the scope in which the
761 // anonymous union is declared.
Douglas Gregor40f4e692009-01-20 16:54:50 +0000762 Owner->makeDeclVisibleInContext(*F);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000763 S->AddDecl(*F);
764 IdResolver.AddDecl(*F);
765 }
766 } else if (const RecordType *InnerRecordType
767 = (*F)->getType()->getAsRecordType()) {
768 RecordDecl *InnerRecord = InnerRecordType->getDecl();
769 if (InnerRecord->isAnonymousStructOrUnion())
770 Invalid = Invalid ||
771 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
772 }
773 }
774
775 return Invalid;
776}
777
778/// ActOnAnonymousStructOrUnion - Handle the declaration of an
779/// anonymous structure or union. Anonymous unions are a C++ feature
780/// (C++ [class.union]) and a GNU C extension; anonymous structures
781/// are a GNU C and GNU C++ extension.
782Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
783 RecordDecl *Record) {
784 DeclContext *Owner = Record->getDeclContext();
785
786 // Diagnose whether this anonymous struct/union is an extension.
787 if (Record->isUnion() && !getLangOptions().CPlusPlus)
788 Diag(Record->getLocation(), diag::ext_anonymous_union);
789 else if (!Record->isUnion())
790 Diag(Record->getLocation(), diag::ext_anonymous_struct);
791
792 // C and C++ require different kinds of checks for anonymous
793 // structs/unions.
794 bool Invalid = false;
795 if (getLangOptions().CPlusPlus) {
796 const char* PrevSpec = 0;
797 // C++ [class.union]p3:
798 // Anonymous unions declared in a named namespace or in the
799 // global namespace shall be declared static.
800 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
801 (isa<TranslationUnitDecl>(Owner) ||
802 (isa<NamespaceDecl>(Owner) &&
803 cast<NamespaceDecl>(Owner)->getDeclName()))) {
804 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
805 Invalid = true;
806
807 // Recover by adding 'static'.
808 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
809 }
810 // C++ [class.union]p3:
811 // A storage class is not allowed in a declaration of an
812 // anonymous union in a class scope.
813 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
814 isa<RecordDecl>(Owner)) {
815 Diag(DS.getStorageClassSpecLoc(),
816 diag::err_anonymous_union_with_storage_spec);
817 Invalid = true;
818
819 // Recover by removing the storage specifier.
820 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
821 PrevSpec);
822 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000823
824 // C++ [class.union]p2:
825 // The member-specification of an anonymous union shall only
826 // define non-static data members. [Note: nested types and
827 // functions cannot be declared within an anonymous union. ]
828 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
829 MemEnd = Record->decls_end();
830 Mem != MemEnd; ++Mem) {
831 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
832 // C++ [class.union]p3:
833 // An anonymous union shall not have private or protected
834 // members (clause 11).
835 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
836 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
837 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
838 Invalid = true;
839 }
840 } else if ((*Mem)->isImplicit()) {
841 // Any implicit members are fine.
842 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
843 if (!MemRecord->isAnonymousStructOrUnion() &&
844 MemRecord->getDeclName()) {
845 // This is a nested type declaration.
846 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
847 << (int)Record->isUnion();
848 Invalid = true;
849 }
850 } else {
851 // We have something that isn't a non-static data
852 // member. Complain about it.
853 unsigned DK = diag::err_anonymous_record_bad_member;
854 if (isa<TypeDecl>(*Mem))
855 DK = diag::err_anonymous_record_with_type;
856 else if (isa<FunctionDecl>(*Mem))
857 DK = diag::err_anonymous_record_with_function;
858 else if (isa<VarDecl>(*Mem))
859 DK = diag::err_anonymous_record_with_static;
860 Diag((*Mem)->getLocation(), DK)
861 << (int)Record->isUnion();
862 Invalid = true;
863 }
864 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000865 } else {
866 // FIXME: Check GNU C semantics
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000867 if (Record->isUnion() && !Owner->isRecord()) {
868 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
869 << (int)getLangOptions().CPlusPlus;
870 Invalid = true;
871 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000872 }
873
874 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000875 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
876 << (int)getLangOptions().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000877 Invalid = true;
878 }
879
880 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000881 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000882 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
883 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
884 /*IdentifierInfo=*/0,
885 Context.getTypeDeclType(Record),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000886 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000887 Anon->setAccess(AS_public);
888 if (getLangOptions().CPlusPlus)
889 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000890 } else {
891 VarDecl::StorageClass SC;
892 switch (DS.getStorageClassSpec()) {
893 default: assert(0 && "Unknown storage class!");
894 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
895 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
896 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
897 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
898 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
899 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
900 case DeclSpec::SCS_mutable:
901 // mutable can only appear on non-static class members, so it's always
902 // an error here
903 Diag(Record->getLocation(), diag::err_mutable_nonmember);
904 Invalid = true;
905 SC = VarDecl::None;
906 break;
907 }
908
909 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
910 /*IdentifierInfo=*/0,
911 Context.getTypeDeclType(Record),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000912 SC, DS.getSourceRange().getBegin());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000913 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000914 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000915
916 // Add the anonymous struct/union object to the current
917 // context. We'll be referencing this object when we refer to one of
918 // its members.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000919 Owner->addDecl(Anon);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000920
921 // Inject the members of the anonymous struct/union into the owning
922 // context and into the identifier resolver chain for name lookup
923 // purposes.
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000924 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
925 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000926
927 // Mark this as an anonymous struct/union type. Note that we do not
928 // do this until after we have already checked and injected the
929 // members of this anonymous struct/union type, because otherwise
930 // the members could be injected twice: once by DeclContext when it
931 // builds its lookup table, and once by
932 // InjectAnonymousStructOrUnionMembers.
933 Record->setAnonymousStructOrUnion(true);
934
935 if (Invalid)
936 Anon->setInvalidDecl();
937
938 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +0000939}
940
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000941bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
942 bool DirectInit) {
Steve Narofff0090632007-09-02 02:04:30 +0000943 // Get the type before calling CheckSingleAssignmentConstraints(), since
944 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000945 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +0000946
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000947 if (getLangOptions().CPlusPlus) {
948 // FIXME: I dislike this error message. A lot.
949 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
950 return Diag(Init->getSourceRange().getBegin(),
951 diag::err_typecheck_convert_incompatible)
952 << DeclType << Init->getType() << "initializing"
953 << Init->getSourceRange();
954
955 return false;
956 }
Douglas Gregor45920e82008-12-19 17:40:08 +0000957
Chris Lattner5cf216b2008-01-04 18:04:52 +0000958 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
959 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
960 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000961}
962
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000963bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000964 const ArrayType *AT = Context.getAsArrayType(DeclT);
965
966 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000967 // C99 6.7.8p14. We have an array of character type with unknown size
968 // being initialized to a string literal.
969 llvm::APSInt ConstVal(32);
970 ConstVal = strLiteral->getByteLength() + 1;
971 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000972 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000973 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000974 } else {
975 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000976 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000977 // FIXME: Avoid truncation for 64-bit length strings.
978 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000979 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000980 diag::warn_initializer_string_for_char_array_too_long)
981 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000982 }
983 // Set type from "char *" to "constant array of char".
984 strLiteral->setType(DeclT);
985 // For now, we always return false (meaning success).
986 return false;
987}
988
989StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000990 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000991 if (AT && AT->getElementType()->isCharType()) {
Anders Carlsson91b9f202009-01-24 17:47:50 +0000992 return dyn_cast<StringLiteral>(Init->IgnoreParens());
Steve Naroffa9960332008-01-25 00:51:06 +0000993 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000994 return 0;
995}
996
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000997bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
998 SourceLocation InitLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000999 DeclarationName InitEntity,
1000 bool DirectInit) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +00001001 if (DeclType->isDependentType() || Init->isTypeDependent())
1002 return false;
1003
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001004 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +00001005 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001006 // (8.3.2), shall be initialized by an object, or function, of
1007 // type T or by an object that can be converted into a T.
1008 if (DeclType->isReferenceType())
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001009 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001010
Steve Naroffca107302008-01-21 23:53:58 +00001011 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1012 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001013 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001014 return Diag(InitLoc, diag::err_variable_object_no_init)
1015 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +00001016
Steve Naroff2fdc3742007-12-10 22:44:33 +00001017 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1018 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001019 // FIXME: Handle wide strings
1020 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1021 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +00001022
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001023 // C++ [dcl.init]p14:
1024 // -- If the destination type is a (possibly cv-qualified) class
1025 // type:
1026 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1027 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1028 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1029
1030 // -- If the initialization is direct-initialization, or if it is
1031 // copy-initialization where the cv-unqualified version of the
1032 // source type is the same class as, or a derived class of, the
1033 // class of the destination, constructors are considered.
1034 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1035 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1036 CXXConstructorDecl *Constructor
1037 = PerformInitializationByConstructor(DeclType, &Init, 1,
1038 InitLoc, Init->getSourceRange(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001039 InitEntity,
1040 DirectInit? IK_Direct : IK_Copy);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001041 return Constructor == 0;
1042 }
1043
1044 // -- Otherwise (i.e., for the remaining copy-initialization
1045 // cases), user-defined conversion sequences that can
1046 // convert from the source type to the destination type or
1047 // (when a conversion function is used) to a derived class
1048 // thereof are enumerated as described in 13.3.1.4, and the
1049 // best one is chosen through overload resolution
1050 // (13.3). If the conversion cannot be done or is
1051 // ambiguous, the initialization is ill-formed. The
1052 // function selected is called with the initializer
1053 // expression as its argument; if the function is a
1054 // constructor, the call initializes a temporary of the
1055 // destination type.
1056 // FIXME: We're pretending to do copy elision here; return to
1057 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +00001058 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001059 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001060
Douglas Gregor61366e92008-12-24 00:01:03 +00001061 if (InitEntity)
1062 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1063 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1064 << Init->getType() << Init->getSourceRange();
1065 else
1066 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1067 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1068 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001069 }
1070
Steve Naroff1ac6fdd2008-09-29 20:07:05 +00001071 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +00001072 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001073 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1074 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +00001075
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001076 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregor930d8b52009-01-30 22:09:00 +00001077 }
Eli Friedmane6f058f2008-06-06 19:40:52 +00001078
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001079 bool hadError = CheckInitList(InitList, DeclType);
1080 Init = InitList;
1081 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +00001082}
1083
Douglas Gregor10bd3682008-11-17 22:58:34 +00001084/// GetNameForDeclarator - Determine the full declaration name for the
1085/// given Declarator.
1086DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1087 switch (D.getKind()) {
1088 case Declarator::DK_Abstract:
1089 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1090 return DeclarationName();
1091
1092 case Declarator::DK_Normal:
1093 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1094 return DeclarationName(D.getIdentifier());
1095
1096 case Declarator::DK_Constructor: {
1097 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1098 Ty = Context.getCanonicalType(Ty);
1099 return Context.DeclarationNames.getCXXConstructorName(Ty);
1100 }
1101
1102 case Declarator::DK_Destructor: {
1103 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1104 Ty = Context.getCanonicalType(Ty);
1105 return Context.DeclarationNames.getCXXDestructorName(Ty);
1106 }
1107
1108 case Declarator::DK_Conversion: {
1109 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1110 Ty = Context.getCanonicalType(Ty);
1111 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1112 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001113
1114 case Declarator::DK_Operator:
1115 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1116 return Context.DeclarationNames.getCXXOperatorName(
1117 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001118 }
1119
1120 assert(false && "Unknown name kind");
1121 return DeclarationName();
1122}
1123
Douglas Gregor584049d2008-12-15 23:53:10 +00001124/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1125/// functions Declaration and Definition are "nearly" matching. This
1126/// heuristic is used to improve diagnostics in the case where an
1127/// out-of-line member function definition doesn't match any
1128/// declaration within the class.
1129static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1130 FunctionDecl *Declaration,
1131 FunctionDecl *Definition) {
1132 if (Declaration->param_size() != Definition->param_size())
1133 return false;
1134 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1135 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1136 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1137
1138 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1139 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1140 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1141 return false;
1142 }
1143
1144 return true;
1145}
1146
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001147Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001148Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1149 bool IsFunctionDefinition) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001150 NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001151 DeclarationName Name = GetNameForDeclarator(D);
1152
Chris Lattnere80a59c2007-07-25 00:24:17 +00001153 // All of these full declarators require an identifier. If it doesn't have
1154 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001155 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001156 if (!D.getInvalidType()) // Reject this if we think it is valid.
1157 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001158 diag::err_declarator_need_ident)
1159 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001160 return 0;
1161 }
1162
Chris Lattner31e05722007-08-26 06:24:45 +00001163 // The scope passed in may not be a decl scope. Zip up the scope tree until
1164 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001165 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1166 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001167 S = S->getParent();
1168
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001169 DeclContext *DC;
1170 Decl *PrevDecl;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001171 NamedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001172 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001173
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001174 // See if this is a redefinition of a variable in the same scope.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001175 if (!D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid()) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001176 DC = CurContext;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001177 PrevDecl = LookupName(S, Name, LookupOrdinaryName);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001178 } else { // Something like "int foo::x;"
1179 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001180 PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001181
1182 // C++ 7.3.1.2p2:
1183 // Members (including explicit specializations of templates) of a named
1184 // namespace can also be defined outside that namespace by explicit
1185 // qualification of the name being defined, provided that the entity being
1186 // defined was already declared in the namespace and the definition appears
1187 // after the point of declaration in a namespace that encloses the
1188 // declarations namespace.
1189 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001190 // Note that we only check the context at this point. We don't yet
1191 // have enough information to make sure that PrevDecl is actually
1192 // the declaration we want to match. For example, given:
1193 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001194 // class X {
1195 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001196 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001197 // };
1198 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001199 // void X::f(int) { } // ill-formed
1200 //
1201 // In this case, PrevDecl will point to the overload set
1202 // containing the two f's declared in X, but neither of them
1203 // matches.
1204 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001205 // The qualifying scope doesn't enclose the original declaration.
1206 // Emit diagnostic based on current scope.
1207 SourceLocation L = D.getIdentifierLoc();
1208 SourceRange R = D.getCXXScopeSpec().getRange();
1209 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001210 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001211 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001212 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001213 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001214 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001215 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001216 }
1217 }
1218
Douglas Gregorf57172b2008-12-08 18:40:42 +00001219 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001220 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001221 InvalidDecl = InvalidDecl
1222 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001223 // Just pretend that we didn't see the previous declaration.
1224 PrevDecl = 0;
1225 }
1226
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001227 // In C++, the previous declaration we find might be a tag type
1228 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00001229 // tag type. Note that this does does not apply if we're declaring a
1230 // typedef (C++ [dcl.typedef]p4).
1231 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1232 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001233 PrevDecl = 0;
1234
Chris Lattner41af0932007-11-14 06:34:38 +00001235 QualType R = GetTypeForDeclarator(D, S);
1236 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1237
Reid Spencer5f016e22007-07-11 17:01:13 +00001238 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001239 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1240 InvalidDecl);
Chris Lattner41af0932007-11-14 06:34:38 +00001241 } else if (R.getTypePtr()->isFunctionType()) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001242 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1243 IsFunctionDefinition, InvalidDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001244 } else {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001245 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1246 InvalidDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001247 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001248
1249 if (New == 0)
1250 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001251
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001252 // Set the lexical context. If the declarator has a C++ scope specifier, the
1253 // lexical context will be different from the semantic context.
1254 New->setLexicalDeclContext(CurContext);
1255
Reid Spencer5f016e22007-07-11 17:01:13 +00001256 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001257 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001258 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001259 // If any semantic error occurred, mark the decl as invalid.
1260 if (D.getInvalidType() || InvalidDecl)
1261 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001262
1263 return New;
1264}
1265
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001266NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001267Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001268 QualType R, Decl* LastDeclarator,
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001269 Decl* PrevDecl, bool& InvalidDecl) {
1270 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1271 if (D.getCXXScopeSpec().isSet()) {
1272 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1273 << D.getCXXScopeSpec().getRange();
1274 InvalidDecl = true;
1275 // Pretend we didn't see the scope specifier.
1276 DC = 0;
1277 }
1278
1279 // Check that there are no default arguments (C++ only).
1280 if (getLangOptions().CPlusPlus)
1281 CheckExtraCXXDefaultArguments(D);
1282
1283 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1284 if (!NewTD) return 0;
1285
1286 // Handle attributes prior to checking for duplicates in MergeVarDecl
1287 ProcessDeclAttributes(NewTD, D);
1288 // Merge the decl with the existing one if appropriate. If the decl is
1289 // in an outer scope, it isn't the same thing.
1290 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1291 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1292 if (NewTD == 0) return 0;
1293 }
1294
1295 if (S->getFnParent() == 0) {
1296 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1297 // then it shall have block scope.
1298 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1299 if (NewTD->getUnderlyingType()->isVariableArrayType())
1300 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1301 else
1302 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1303
1304 InvalidDecl = true;
1305 }
1306 }
1307 return NewTD;
1308}
1309
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001310NamedDecl*
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001311Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001312 QualType R, Decl* LastDeclarator,
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001313 Decl* PrevDecl, bool& InvalidDecl) {
1314 DeclarationName Name = GetNameForDeclarator(D);
1315
1316 // Check that there are no default arguments (C++ only).
1317 if (getLangOptions().CPlusPlus)
1318 CheckExtraCXXDefaultArguments(D);
1319
1320 if (R.getTypePtr()->isObjCInterfaceType()) {
1321 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1322 << D.getIdentifier();
1323 InvalidDecl = true;
1324 }
1325
1326 VarDecl *NewVD;
1327 VarDecl::StorageClass SC;
1328 switch (D.getDeclSpec().getStorageClassSpec()) {
1329 default: assert(0 && "Unknown storage class!");
1330 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1331 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1332 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1333 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1334 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1335 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1336 case DeclSpec::SCS_mutable:
1337 // mutable can only appear on non-static class members, so it's always
1338 // an error here
1339 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1340 InvalidDecl = true;
1341 SC = VarDecl::None;
1342 break;
1343 }
1344
1345 IdentifierInfo *II = Name.getAsIdentifierInfo();
1346 if (!II) {
1347 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1348 << Name.getAsString();
1349 return 0;
1350 }
1351
1352 if (DC->isRecord()) {
1353 // This is a static data member for a C++ class.
1354 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1355 D.getIdentifierLoc(), II,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001356 R);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001357 } else {
1358 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1359 if (S->getFnParent() == 0) {
1360 // C99 6.9p2: The storage-class specifiers auto and register shall not
1361 // appear in the declaration specifiers in an external declaration.
1362 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1363 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1364 InvalidDecl = true;
1365 }
1366 }
1367 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001368 II, R, SC,
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001369 // FIXME: Move to DeclGroup...
1370 D.getDeclSpec().getSourceRange().getBegin());
1371 NewVD->setThreadSpecified(ThreadSpecified);
1372 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001373 NewVD->setNextDeclarator(LastDeclarator);
1374
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001375 // Handle attributes prior to checking for duplicates in MergeVarDecl
1376 ProcessDeclAttributes(NewVD, D);
1377
1378 // Handle GNU asm-label extension (encoded as an attribute).
1379 if (Expr *E = (Expr*) D.getAsmLabel()) {
1380 // The parser guarantees this is a string.
1381 StringLiteral *SE = cast<StringLiteral>(E);
1382 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1383 SE->getByteLength())));
1384 }
1385
1386 // Emit an error if an address space was applied to decl with local storage.
1387 // This includes arrays of objects with address space qualifiers, but not
1388 // automatic variables that point to other address spaces.
1389 // ISO/IEC TR 18037 S5.1.2
1390 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1391 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1392 InvalidDecl = true;
1393 }
1394 // Merge the decl with the existing one if appropriate. If the decl is
1395 // in an outer scope, it isn't the same thing.
1396 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1397 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1398 // The user tried to define a non-static data member
1399 // out-of-line (C++ [dcl.meaning]p1).
1400 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1401 << D.getCXXScopeSpec().getRange();
1402 NewVD->Destroy(Context);
1403 return 0;
1404 }
1405
1406 NewVD = MergeVarDecl(NewVD, PrevDecl);
1407 if (NewVD == 0) return 0;
1408
1409 if (D.getCXXScopeSpec().isSet()) {
1410 // No previous declaration in the qualifying scope.
1411 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1412 << Name << D.getCXXScopeSpec().getRange();
1413 InvalidDecl = true;
1414 }
1415 }
1416 return NewVD;
1417}
1418
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001419NamedDecl*
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001420Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001421 QualType R, Decl *LastDeclarator,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001422 Decl* PrevDecl, bool IsFunctionDefinition,
1423 bool& InvalidDecl) {
1424 assert(R.getTypePtr()->isFunctionType());
1425
1426 DeclarationName Name = GetNameForDeclarator(D);
1427 FunctionDecl::StorageClass SC = FunctionDecl::None;
1428 switch (D.getDeclSpec().getStorageClassSpec()) {
1429 default: assert(0 && "Unknown storage class!");
1430 case DeclSpec::SCS_auto:
1431 case DeclSpec::SCS_register:
1432 case DeclSpec::SCS_mutable:
1433 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1434 InvalidDecl = true;
1435 break;
1436 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1437 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1438 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
1439 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1440 }
1441
1442 bool isInline = D.getDeclSpec().isInlineSpecified();
1443 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1444 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1445
1446 FunctionDecl *NewFD;
1447 if (D.getKind() == Declarator::DK_Constructor) {
1448 // This is a C++ constructor declaration.
1449 assert(DC->isRecord() &&
1450 "Constructors can only be declared in a member context");
1451
1452 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1453
1454 // Create the new declaration
1455 NewFD = CXXConstructorDecl::Create(Context,
1456 cast<CXXRecordDecl>(DC),
1457 D.getIdentifierLoc(), Name, R,
1458 isExplicit, isInline,
1459 /*isImplicitlyDeclared=*/false);
1460
1461 if (InvalidDecl)
1462 NewFD->setInvalidDecl();
1463 } else if (D.getKind() == Declarator::DK_Destructor) {
1464 // This is a C++ destructor declaration.
1465 if (DC->isRecord()) {
1466 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1467
1468 NewFD = CXXDestructorDecl::Create(Context,
1469 cast<CXXRecordDecl>(DC),
1470 D.getIdentifierLoc(), Name, R,
1471 isInline,
1472 /*isImplicitlyDeclared=*/false);
1473
1474 if (InvalidDecl)
1475 NewFD->setInvalidDecl();
1476 } else {
1477 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1478
1479 // Create a FunctionDecl to satisfy the function definition parsing
1480 // code path.
1481 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001482 Name, R, SC, isInline,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001483 // FIXME: Move to DeclGroup...
1484 D.getDeclSpec().getSourceRange().getBegin());
1485 InvalidDecl = true;
1486 NewFD->setInvalidDecl();
1487 }
1488 } else if (D.getKind() == Declarator::DK_Conversion) {
1489 if (!DC->isRecord()) {
1490 Diag(D.getIdentifierLoc(),
1491 diag::err_conv_function_not_member);
1492 return 0;
1493 } else {
1494 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1495
1496 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1497 D.getIdentifierLoc(), Name, R,
1498 isInline, isExplicit);
1499
1500 if (InvalidDecl)
1501 NewFD->setInvalidDecl();
1502 }
1503 } else if (DC->isRecord()) {
1504 // This is a C++ method declaration.
1505 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1506 D.getIdentifierLoc(), Name, R,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001507 (SC == FunctionDecl::Static), isInline);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001508 } else {
1509 NewFD = FunctionDecl::Create(Context, DC,
1510 D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001511 Name, R, SC, isInline,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001512 // FIXME: Move to DeclGroup...
1513 D.getDeclSpec().getSourceRange().getBegin());
1514 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001515 NewFD->setNextDeclarator(LastDeclarator);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001516
1517 // Set the lexical context. If the declarator has a C++
1518 // scope specifier, the lexical context will be different
1519 // from the semantic context.
1520 NewFD->setLexicalDeclContext(CurContext);
1521
1522 // Handle GNU asm-label extension (encoded as an attribute).
1523 if (Expr *E = (Expr*) D.getAsmLabel()) {
1524 // The parser guarantees this is a string.
1525 StringLiteral *SE = cast<StringLiteral>(E);
1526 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1527 SE->getByteLength())));
1528 }
1529
1530 // Copy the parameter declarations from the declarator D to
1531 // the function declaration NewFD, if they are available.
1532 if (D.getNumTypeObjects() > 0) {
1533 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1534
1535 // Create Decl objects for each parameter, adding them to the
1536 // FunctionDecl.
1537 llvm::SmallVector<ParmVarDecl*, 16> Params;
1538
1539 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1540 // function that takes no arguments, not a function that takes a
1541 // single void argument.
1542 // We let through "const void" here because Sema::GetTypeForDeclarator
1543 // already checks for that case.
1544 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1545 FTI.ArgInfo[0].Param &&
1546 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1547 // empty arg list, don't push any params.
1548 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1549
1550 // In C++, the empty parameter-type-list must be spelled "void"; a
1551 // typedef of void is not permitted.
1552 if (getLangOptions().CPlusPlus &&
1553 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1554 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1555 }
1556 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1557 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1558 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1559 }
1560
1561 NewFD->setParams(Context, &Params[0], Params.size());
1562 } else if (R->getAsTypedefType()) {
1563 // When we're declaring a function with a typedef, as in the
1564 // following example, we'll need to synthesize (unnamed)
1565 // parameters for use in the declaration.
1566 //
1567 // @code
1568 // typedef void fn(int);
1569 // fn f;
1570 // @endcode
1571 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1572 if (!FT) {
1573 // This is a typedef of a function with no prototype, so we
1574 // don't need to do anything.
1575 } else if ((FT->getNumArgs() == 0) ||
1576 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1577 FT->getArgType(0)->isVoidType())) {
1578 // This is a zero-argument function. We don't need to do anything.
1579 } else {
1580 // Synthesize a parameter for each argument type.
1581 llvm::SmallVector<ParmVarDecl*, 16> Params;
1582 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1583 ArgType != FT->arg_type_end(); ++ArgType) {
1584 Params.push_back(ParmVarDecl::Create(Context, DC,
1585 SourceLocation(), 0,
1586 *ArgType, VarDecl::None,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001587 0));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001588 }
1589
1590 NewFD->setParams(Context, &Params[0], Params.size());
1591 }
1592 }
1593
1594 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1595 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1596 else if (isa<CXXDestructorDecl>(NewFD)) {
1597 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1598 Record->setUserDeclaredDestructor(true);
1599 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1600 // user-defined destructor.
1601 Record->setPOD(false);
1602 } else if (CXXConversionDecl *Conversion =
1603 dyn_cast<CXXConversionDecl>(NewFD))
1604 ActOnConversionDeclarator(Conversion);
1605
1606 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1607 if (NewFD->isOverloadedOperator() &&
1608 CheckOverloadedOperatorDeclaration(NewFD))
1609 NewFD->setInvalidDecl();
1610
1611 // Merge the decl with the existing one if appropriate. Since C functions
1612 // are in a flat namespace, make sure we consider decls in outer scopes.
1613 if (PrevDecl &&
1614 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1615 bool Redeclaration = false;
1616
1617 // If C++, determine whether NewFD is an overload of PrevDecl or
1618 // a declaration that requires merging. If it's an overload,
1619 // there's no more work to do here; we'll just add the new
1620 // function to the scope.
1621 OverloadedFunctionDecl::function_iterator MatchedDecl;
1622 if (!getLangOptions().CPlusPlus ||
1623 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1624 Decl *OldDecl = PrevDecl;
1625
1626 // If PrevDecl was an overloaded function, extract the
1627 // FunctionDecl that matched.
1628 if (isa<OverloadedFunctionDecl>(PrevDecl))
1629 OldDecl = *MatchedDecl;
1630
1631 // NewFD and PrevDecl represent declarations that need to be
1632 // merged.
1633 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1634
1635 if (NewFD == 0) return 0;
1636 if (Redeclaration) {
1637 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1638
1639 // An out-of-line member function declaration must also be a
1640 // definition (C++ [dcl.meaning]p1).
1641 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1642 !InvalidDecl) {
1643 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1644 << D.getCXXScopeSpec().getRange();
1645 NewFD->setInvalidDecl();
1646 }
1647 }
1648 }
1649
1650 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1651 // The user tried to provide an out-of-line definition for a
1652 // member function, but there was no such member function
1653 // declared (C++ [class.mfct]p2). For example:
1654 //
1655 // class X {
1656 // void f() const;
1657 // };
1658 //
1659 // void X::f() { } // ill-formed
1660 //
1661 // Complain about this problem, and attempt to suggest close
1662 // matches (e.g., those that differ only in cv-qualifiers and
1663 // whether the parameter types are references).
1664 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1665 << cast<CXXRecordDecl>(DC)->getDeclName()
1666 << D.getCXXScopeSpec().getRange();
1667 InvalidDecl = true;
1668
Douglas Gregord8635172009-02-02 21:35:47 +00001669 LookupResult Prev = LookupQualifiedName(DC, Name, LookupOrdinaryName,
1670 true);
1671 assert(!Prev.isAmbiguous() &&
1672 "Cannot have an ambiguity in previous-declaration lookup");
1673 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
1674 Func != FuncEnd; ++Func) {
1675 if (isa<CXXMethodDecl>(*Func) &&
1676 isNearlyMatchingMemberFunction(Context, cast<FunctionDecl>(*Func),
1677 NewFD))
1678 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001679 }
Douglas Gregord8635172009-02-02 21:35:47 +00001680
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001681 PrevDecl = 0;
1682 }
1683 }
Douglas Gregord8635172009-02-02 21:35:47 +00001684
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001685 // Handle attributes. We need to have merged decls when handling attributes
1686 // (for example to check for conflicts, etc).
1687 ProcessDeclAttributes(NewFD, D);
1688
1689 if (getLangOptions().CPlusPlus) {
1690 // In C++, check default arguments now that we have merged decls.
1691 CheckCXXDefaultArguments(NewFD);
1692
1693 // An out-of-line member function declaration must also be a
1694 // definition (C++ [dcl.meaning]p1).
1695 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1696 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1697 << D.getCXXScopeSpec().getRange();
1698 InvalidDecl = true;
1699 }
1700 }
1701 return NewFD;
1702}
1703
Steve Naroff6594a702008-10-27 11:34:16 +00001704void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001705 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1706 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001707}
1708
Eli Friedmanc594b322008-05-20 13:48:25 +00001709bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1710 switch (Init->getStmtClass()) {
1711 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001712 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001713 return true;
1714 case Expr::ParenExprClass: {
1715 const ParenExpr* PE = cast<ParenExpr>(Init);
1716 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1717 }
1718 case Expr::CompoundLiteralExprClass:
1719 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor1a49af92009-01-06 05:10:23 +00001720 case Expr::DeclRefExprClass:
1721 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001722 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001723 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1724 if (VD->hasGlobalStorage())
1725 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001726 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001727 return true;
1728 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001729 if (isa<FunctionDecl>(D))
1730 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001731 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001732 return true;
1733 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001734 case Expr::MemberExprClass: {
1735 const MemberExpr *M = cast<MemberExpr>(Init);
1736 if (M->isArrow())
1737 return CheckAddressConstantExpression(M->getBase());
1738 return CheckAddressConstantExpressionLValue(M->getBase());
1739 }
1740 case Expr::ArraySubscriptExprClass: {
1741 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1742 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1743 return CheckAddressConstantExpression(ASE->getBase()) ||
1744 CheckArithmeticConstantExpression(ASE->getIdx());
1745 }
1746 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001747 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001748 return false;
1749 case Expr::UnaryOperatorClass: {
1750 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1751
1752 // C99 6.6p9
1753 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001754 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001755
Steve Naroff6594a702008-10-27 11:34:16 +00001756 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001757 return true;
1758 }
1759 }
1760}
1761
1762bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1763 switch (Init->getStmtClass()) {
1764 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001765 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001766 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001767 case Expr::ParenExprClass:
1768 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001769 case Expr::StringLiteralClass:
1770 case Expr::ObjCStringLiteralClass:
1771 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001772 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001773 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001774 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1775 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1776 Builtin::BI__builtin___CFStringMakeConstantString)
1777 return false;
1778
Steve Naroff6594a702008-10-27 11:34:16 +00001779 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001780 return true;
1781
Eli Friedmanc594b322008-05-20 13:48:25 +00001782 case Expr::UnaryOperatorClass: {
1783 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1784
1785 // C99 6.6p9
1786 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1787 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1788
1789 if (Exp->getOpcode() == UnaryOperator::Extension)
1790 return CheckAddressConstantExpression(Exp->getSubExpr());
1791
Steve Naroff6594a702008-10-27 11:34:16 +00001792 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001793 return true;
1794 }
1795 case Expr::BinaryOperatorClass: {
1796 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1797 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1798
1799 Expr *PExp = Exp->getLHS();
1800 Expr *IExp = Exp->getRHS();
1801 if (IExp->getType()->isPointerType())
1802 std::swap(PExp, IExp);
1803
1804 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1805 return CheckAddressConstantExpression(PExp) ||
1806 CheckArithmeticConstantExpression(IExp);
1807 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001808 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001809 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001810 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001811 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1812 // Check for implicit promotion
1813 if (SubExpr->getType()->isFunctionType() ||
1814 SubExpr->getType()->isArrayType())
1815 return CheckAddressConstantExpressionLValue(SubExpr);
1816 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001817
1818 // Check for pointer->pointer cast
1819 if (SubExpr->getType()->isPointerType())
1820 return CheckAddressConstantExpression(SubExpr);
1821
Eli Friedmanc3f07642008-08-25 20:46:57 +00001822 if (SubExpr->getType()->isIntegralType()) {
1823 // Check for the special-case of a pointer->int->pointer cast;
1824 // this isn't standard, but some code requires it. See
1825 // PR2720 for an example.
1826 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1827 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1828 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1829 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1830 if (IntWidth >= PointerWidth) {
1831 return CheckAddressConstantExpression(SubCast->getSubExpr());
1832 }
1833 }
1834 }
1835 }
1836 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001837 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001838 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001839
Steve Naroff6594a702008-10-27 11:34:16 +00001840 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001841 return true;
1842 }
1843 case Expr::ConditionalOperatorClass: {
1844 // FIXME: Should we pedwarn here?
1845 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1846 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001847 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001848 return true;
1849 }
1850 if (CheckArithmeticConstantExpression(Exp->getCond()))
1851 return true;
1852 if (Exp->getLHS() &&
1853 CheckAddressConstantExpression(Exp->getLHS()))
1854 return true;
1855 return CheckAddressConstantExpression(Exp->getRHS());
1856 }
1857 case Expr::AddrLabelExprClass:
1858 return false;
1859 }
1860}
1861
Eli Friedman4caf0552008-06-09 05:05:07 +00001862static const Expr* FindExpressionBaseAddress(const Expr* E);
1863
1864static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1865 switch (E->getStmtClass()) {
1866 default:
1867 return E;
1868 case Expr::ParenExprClass: {
1869 const ParenExpr* PE = cast<ParenExpr>(E);
1870 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1871 }
1872 case Expr::MemberExprClass: {
1873 const MemberExpr *M = cast<MemberExpr>(E);
1874 if (M->isArrow())
1875 return FindExpressionBaseAddress(M->getBase());
1876 return FindExpressionBaseAddressLValue(M->getBase());
1877 }
1878 case Expr::ArraySubscriptExprClass: {
1879 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1880 return FindExpressionBaseAddress(ASE->getBase());
1881 }
1882 case Expr::UnaryOperatorClass: {
1883 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1884
1885 if (Exp->getOpcode() == UnaryOperator::Deref)
1886 return FindExpressionBaseAddress(Exp->getSubExpr());
1887
1888 return E;
1889 }
1890 }
1891}
1892
1893static const Expr* FindExpressionBaseAddress(const Expr* E) {
1894 switch (E->getStmtClass()) {
1895 default:
1896 return E;
1897 case Expr::ParenExprClass: {
1898 const ParenExpr* PE = cast<ParenExpr>(E);
1899 return FindExpressionBaseAddress(PE->getSubExpr());
1900 }
1901 case Expr::UnaryOperatorClass: {
1902 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1903
1904 // C99 6.6p9
1905 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1906 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1907
1908 if (Exp->getOpcode() == UnaryOperator::Extension)
1909 return FindExpressionBaseAddress(Exp->getSubExpr());
1910
1911 return E;
1912 }
1913 case Expr::BinaryOperatorClass: {
1914 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1915
1916 Expr *PExp = Exp->getLHS();
1917 Expr *IExp = Exp->getRHS();
1918 if (IExp->getType()->isPointerType())
1919 std::swap(PExp, IExp);
1920
1921 return FindExpressionBaseAddress(PExp);
1922 }
1923 case Expr::ImplicitCastExprClass: {
1924 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1925
1926 // Check for implicit promotion
1927 if (SubExpr->getType()->isFunctionType() ||
1928 SubExpr->getType()->isArrayType())
1929 return FindExpressionBaseAddressLValue(SubExpr);
1930
1931 // Check for pointer->pointer cast
1932 if (SubExpr->getType()->isPointerType())
1933 return FindExpressionBaseAddress(SubExpr);
1934
1935 // We assume that we have an arithmetic expression here;
1936 // if we don't, we'll figure it out later
1937 return 0;
1938 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001939 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001940 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1941
1942 // Check for pointer->pointer cast
1943 if (SubExpr->getType()->isPointerType())
1944 return FindExpressionBaseAddress(SubExpr);
1945
1946 // We assume that we have an arithmetic expression here;
1947 // if we don't, we'll figure it out later
1948 return 0;
1949 }
1950 }
1951}
1952
Anders Carlsson51fe9962008-11-22 21:04:56 +00001953bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001954 switch (Init->getStmtClass()) {
1955 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001956 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001957 return true;
1958 case Expr::ParenExprClass: {
1959 const ParenExpr* PE = cast<ParenExpr>(Init);
1960 return CheckArithmeticConstantExpression(PE->getSubExpr());
1961 }
1962 case Expr::FloatingLiteralClass:
1963 case Expr::IntegerLiteralClass:
1964 case Expr::CharacterLiteralClass:
1965 case Expr::ImaginaryLiteralClass:
1966 case Expr::TypesCompatibleExprClass:
1967 case Expr::CXXBoolLiteralExprClass:
1968 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001969 case Expr::CallExprClass:
1970 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001971 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001972
1973 // Allow any constant foldable calls to builtins.
1974 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001975 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001976
Steve Naroff6594a702008-10-27 11:34:16 +00001977 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001978 return true;
1979 }
Douglas Gregor1a49af92009-01-06 05:10:23 +00001980 case Expr::DeclRefExprClass:
1981 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001982 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1983 if (isa<EnumConstantDecl>(D))
1984 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001985 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001986 return true;
1987 }
1988 case Expr::CompoundLiteralExprClass:
1989 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1990 // but vectors are allowed to be magic.
1991 if (Init->getType()->isVectorType())
1992 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001993 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001994 return true;
1995 case Expr::UnaryOperatorClass: {
1996 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1997
1998 switch (Exp->getOpcode()) {
1999 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2000 // See C99 6.6p3.
2001 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002002 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002003 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002004 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00002005 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2006 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002007 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002008 return true;
2009 case UnaryOperator::Extension:
2010 case UnaryOperator::LNot:
2011 case UnaryOperator::Plus:
2012 case UnaryOperator::Minus:
2013 case UnaryOperator::Not:
2014 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2015 }
2016 }
Sebastian Redl05189992008-11-11 17:56:53 +00002017 case Expr::SizeOfAlignOfExprClass: {
2018 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002019 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00002020 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00002021 return false;
2022 // alignof always evaluates to a constant.
2023 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00002024 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00002025 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002026 return true;
2027 }
2028 return false;
2029 }
2030 case Expr::BinaryOperatorClass: {
2031 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2032
2033 if (Exp->getLHS()->getType()->isArithmeticType() &&
2034 Exp->getRHS()->getType()->isArithmeticType()) {
2035 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2036 CheckArithmeticConstantExpression(Exp->getRHS());
2037 }
2038
Eli Friedman4caf0552008-06-09 05:05:07 +00002039 if (Exp->getLHS()->getType()->isPointerType() &&
2040 Exp->getRHS()->getType()->isPointerType()) {
2041 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2042 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2043
2044 // Only allow a null (constant integer) base; we could
2045 // allow some additional cases if necessary, but this
2046 // is sufficient to cover offsetof-like constructs.
2047 if (!LHSBase && !RHSBase) {
2048 return CheckAddressConstantExpression(Exp->getLHS()) ||
2049 CheckAddressConstantExpression(Exp->getRHS());
2050 }
2051 }
2052
Steve Naroff6594a702008-10-27 11:34:16 +00002053 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002054 return true;
2055 }
2056 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002057 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002058 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00002059 if (SubExpr->getType()->isArithmeticType())
2060 return CheckArithmeticConstantExpression(SubExpr);
2061
Eli Friedmanb529d832008-09-02 09:37:00 +00002062 if (SubExpr->getType()->isPointerType()) {
2063 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2064 // If the pointer has a null base, this is an offsetof-like construct
Nuno Lopes83950812009-02-02 16:07:41 +00002065 return Base ? false : CheckAddressConstantExpression(SubExpr);
Eli Friedmanb529d832008-09-02 09:37:00 +00002066 }
2067
Steve Naroff6594a702008-10-27 11:34:16 +00002068 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00002069 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002070 }
2071 case Expr::ConditionalOperatorClass: {
2072 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00002073
2074 // If GNU extensions are disabled, we require all operands to be arithmetic
2075 // constant expressions.
2076 if (getLangOptions().NoExtensions) {
2077 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2078 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2079 CheckArithmeticConstantExpression(Exp->getRHS());
2080 }
2081
2082 // Otherwise, we have to emulate some of the behavior of fold here.
2083 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2084 // because it can constant fold things away. To retain compatibility with
2085 // GCC code, we see if we can fold the condition to a constant (which we
2086 // should always be able to do in theory). If so, we only require the
2087 // specified arm of the conditional to be a constant. This is a horrible
2088 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002089 Expr::EvalResult EvalResult;
2090 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2091 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002092 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00002093 // won't be able to either. Use it to emit the diagnostic though.
2094 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002095 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00002096 return Res;
2097 }
2098
2099 // Verify that the side following the condition is also a constant.
2100 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002101 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00002102 std::swap(TrueSide, FalseSide);
2103
2104 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00002105 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00002106
2107 // Okay, the evaluated side evaluates to a constant, so we accept this.
2108 // Check to see if the other side is obviously not a constant. If so,
2109 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002110 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00002111 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002112 diag::ext_typecheck_expression_not_constant_but_accepted)
2113 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00002114 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00002115 }
2116 }
2117}
2118
2119bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002120 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init))
2121 Init = DIE->getInit();
2122
Nuno Lopes9a979c32008-07-07 16:46:50 +00002123 Init = Init->IgnoreParens();
2124
Nate Begeman59b5da62009-01-18 03:20:47 +00002125 if (Init->isEvaluatable(Context))
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002126 return false;
2127
Eli Friedmanc594b322008-05-20 13:48:25 +00002128 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2129 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2130 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2131
Nuno Lopes9a979c32008-07-07 16:46:50 +00002132 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2133 return CheckForConstantInitializer(e->getInitializer(), DclT);
2134
Douglas Gregor3498bdb2009-01-29 17:44:32 +00002135 if (isa<ImplicitValueInitExpr>(Init)) {
2136 // FIXME: In C++, check for non-POD types.
2137 return false;
2138 }
2139
Eli Friedmanc594b322008-05-20 13:48:25 +00002140 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2141 unsigned numInits = Exp->getNumInits();
2142 for (unsigned i = 0; i < numInits; i++) {
2143 // FIXME: Need to get the type of the declaration for C++,
2144 // because it could be a reference?
Douglas Gregor4c678342009-01-28 21:54:33 +00002145
Eli Friedmanc594b322008-05-20 13:48:25 +00002146 if (CheckForConstantInitializer(Exp->getInit(i),
2147 Exp->getInit(i)->getType()))
2148 return true;
2149 }
2150 return false;
2151 }
2152
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002153 // FIXME: We can probably remove some of this code below, now that
2154 // Expr::Evaluate is doing the heavy lifting for scalars.
2155
Eli Friedmanc594b322008-05-20 13:48:25 +00002156 if (Init->isNullPointerConstant(Context))
2157 return false;
2158 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002159 QualType InitTy = Context.getCanonicalType(Init->getType())
2160 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002161 if (InitTy == Context.BoolTy) {
2162 // Special handling for pointers implicitly cast to bool;
2163 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2164 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2165 Expr* SubE = ICE->getSubExpr();
2166 if (SubE->getType()->isPointerType() ||
2167 SubE->getType()->isArrayType() ||
2168 SubE->getType()->isFunctionType()) {
2169 return CheckAddressConstantExpression(Init);
2170 }
2171 }
2172 } else if (InitTy->isIntegralType()) {
2173 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002174 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002175 SubE = CE->getSubExpr();
2176 // Special check for pointer cast to int; we allow as an extension
2177 // an address constant cast to an integer if the integer
2178 // is of an appropriate width (this sort of code is apparently used
2179 // in some places).
2180 // FIXME: Add pedwarn?
2181 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2182 if (SubE && (SubE->getType()->isPointerType() ||
2183 SubE->getType()->isArrayType() ||
2184 SubE->getType()->isFunctionType())) {
2185 unsigned IntWidth = Context.getTypeSize(Init->getType());
2186 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2187 if (IntWidth >= PointerWidth)
2188 return CheckAddressConstantExpression(Init);
2189 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002190 }
2191
2192 return CheckArithmeticConstantExpression(Init);
2193 }
2194
2195 if (Init->getType()->isPointerType())
2196 return CheckAddressConstantExpression(Init);
2197
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002198 // An array type at the top level that isn't an init-list must
2199 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002200 if (Init->getType()->isArrayType())
2201 return false;
2202
Nuno Lopes73419bf2008-09-01 18:42:41 +00002203 if (Init->getType()->isFunctionType())
2204 return false;
2205
Steve Naroff8af6a452008-10-02 17:12:56 +00002206 // Allow block exprs at top level.
2207 if (Init->getType()->isBlockPointerType())
2208 return false;
Nuno Lopes6ed2ef82009-01-15 16:44:45 +00002209
2210 // GCC cast to union extension
2211 // note: the validity of the cast expr is checked by CheckCastTypes()
2212 if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2213 QualType T = C->getType();
2214 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2215 }
2216
Steve Naroff6594a702008-10-27 11:34:16 +00002217 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002218 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002219}
2220
Sebastian Redl798d1192008-12-13 16:23:55 +00002221void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002222 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2223}
2224
2225/// AddInitializerToDecl - Adds the initializer Init to the
2226/// declaration dcl. If DirectInit is true, this is C++ direct
2227/// initialization rather than copy initialization.
2228void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002229 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002230 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002231 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002232
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002233 // If there is no declaration, there was an error parsing it. Just ignore
2234 // the initializer.
2235 if (RealDecl == 0) {
2236 delete Init;
2237 return;
2238 }
Steve Naroffbb204692007-09-12 14:07:44 +00002239
Steve Naroff410e3e22007-09-12 20:13:48 +00002240 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2241 if (!VDecl) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002242 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002243 RealDecl->setInvalidDecl();
2244 return;
2245 }
Steve Naroffbb204692007-09-12 14:07:44 +00002246 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002247 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002248 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002249 if (VDecl->isBlockVarDecl()) {
2250 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002251 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002252 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002253 VDecl->setInvalidDecl();
2254 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002255 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002256 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002257 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002258
2259 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2260 if (!getLangOptions().CPlusPlus) {
2261 if (SC == VarDecl::Static) // C99 6.7.8p4.
2262 CheckForConstantInitializer(Init, DclT);
2263 }
Steve Naroffbb204692007-09-12 14:07:44 +00002264 }
Steve Naroff248a7532008-04-15 22:42:06 +00002265 } else if (VDecl->isFileVarDecl()) {
2266 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002267 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002268 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002269 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002270 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002271 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002272
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002273 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2274 if (!getLangOptions().CPlusPlus) {
2275 // C99 6.7.8p4. All file scoped initializers need to be constant.
2276 CheckForConstantInitializer(Init, DclT);
2277 }
Steve Naroffbb204692007-09-12 14:07:44 +00002278 }
2279 // If the type changed, it means we had an incomplete type that was
2280 // completed by the initializer. For example:
2281 // int ary[] = { 1, 3, 5 };
2282 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002283 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002284 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002285 Init->setType(DclT);
2286 }
Steve Naroffbb204692007-09-12 14:07:44 +00002287
2288 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002289 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002290 return;
2291}
2292
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002293void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2294 Decl *RealDecl = static_cast<Decl *>(dcl);
2295
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002296 // If there is no declaration, there was an error parsing it. Just ignore it.
2297 if (RealDecl == 0)
2298 return;
2299
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002300 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2301 QualType Type = Var->getType();
2302 // C++ [dcl.init.ref]p3:
2303 // The initializer can be omitted for a reference only in a
2304 // parameter declaration (8.3.5), in the declaration of a
2305 // function return type, in the declaration of a class member
2306 // within its class declaration (9.2), and where the extern
2307 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002308 if (Type->isReferenceType() &&
2309 Var->getStorageClass() != VarDecl::Extern &&
2310 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002311 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002312 << Var->getDeclName()
2313 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002314 Var->setInvalidDecl();
2315 return;
2316 }
2317
2318 // C++ [dcl.init]p9:
2319 //
2320 // If no initializer is specified for an object, and the object
2321 // is of (possibly cv-qualified) non-POD class type (or array
2322 // thereof), the object shall be default-initialized; if the
2323 // object is of const-qualified type, the underlying class type
2324 // shall have a user-declared default constructor.
2325 if (getLangOptions().CPlusPlus) {
2326 QualType InitType = Type;
2327 if (const ArrayType *Array = Context.getAsArrayType(Type))
2328 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002329 if (Var->getStorageClass() != VarDecl::Extern &&
2330 Var->getStorageClass() != VarDecl::PrivateExtern &&
2331 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002332 const CXXConstructorDecl *Constructor
2333 = PerformInitializationByConstructor(InitType, 0, 0,
2334 Var->getLocation(),
2335 SourceRange(Var->getLocation(),
2336 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002337 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002338 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002339 if (!Constructor)
2340 Var->setInvalidDecl();
2341 }
2342 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002343
Douglas Gregor818ce482008-10-29 13:50:18 +00002344#if 0
2345 // FIXME: Temporarily disabled because we are not properly parsing
2346 // linkage specifications on declarations, e.g.,
2347 //
2348 // extern "C" const CGPoint CGPointerZero;
2349 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002350 // C++ [dcl.init]p9:
2351 //
2352 // If no initializer is specified for an object, and the
2353 // object is of (possibly cv-qualified) non-POD class type (or
2354 // array thereof), the object shall be default-initialized; if
2355 // the object is of const-qualified type, the underlying class
2356 // type shall have a user-declared default
2357 // constructor. Otherwise, if no initializer is specified for
2358 // an object, the object and its subobjects, if any, have an
2359 // indeterminate initial value; if the object or any of its
2360 // subobjects are of const-qualified type, the program is
2361 // ill-formed.
2362 //
2363 // This isn't technically an error in C, so we don't diagnose it.
2364 //
2365 // FIXME: Actually perform the POD/user-defined default
2366 // constructor check.
2367 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002368 Context.getCanonicalType(Type).isConstQualified() &&
2369 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002370 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2371 << Var->getName()
2372 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002373#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002374 }
2375}
2376
Reid Spencer5f016e22007-07-11 17:01:13 +00002377/// The declarators are chained together backwards, reverse the list.
2378Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2379 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002380 Decl *GroupDecl = static_cast<Decl*>(group);
2381 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002382 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002383
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002384 Decl *Group = dyn_cast<Decl>(GroupDecl);
2385 Decl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002386 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002387 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002388 else { // reverse the list.
2389 while (Group) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002390 Decl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002391 Group->setNextDeclarator(NewGroup);
2392 NewGroup = Group;
2393 Group = Next;
2394 }
2395 }
2396 // Perform semantic analysis that depends on having fully processed both
2397 // the declarator and initializer.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002398 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002399 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2400 if (!IDecl)
2401 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002402 QualType T = IDecl->getType();
2403
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002404 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002405 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002406
2407 // FIXME: This won't give the correct result for
2408 // int a[10][n];
2409 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002410 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002411 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2412 SizeRange;
2413
Eli Friedmanc5773c42008-02-15 18:16:39 +00002414 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002415 } else {
2416 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2417 // static storage duration, it shall not have a variable length array.
2418 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002419 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2420 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002421 IDecl->setInvalidDecl();
2422 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002423 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2424 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002425 IDecl->setInvalidDecl();
2426 }
2427 }
2428 } else if (T->isVariablyModifiedType()) {
2429 if (IDecl->isFileVarDecl()) {
2430 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2431 IDecl->setInvalidDecl();
2432 } else {
2433 if (IDecl->getStorageClass() == VarDecl::Extern) {
2434 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2435 IDecl->setInvalidDecl();
2436 }
Steve Naroffbb204692007-09-12 14:07:44 +00002437 }
2438 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002439
Steve Naroffbb204692007-09-12 14:07:44 +00002440 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2441 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002442 if (IDecl->isBlockVarDecl() &&
2443 IDecl->getStorageClass() != VarDecl::Extern) {
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002444 if (!IDecl->isInvalidDecl() &&
2445 DiagnoseIncompleteType(IDecl->getLocation(), T,
2446 diag::err_typecheck_decl_incomplete_type))
Steve Naroffbb204692007-09-12 14:07:44 +00002447 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00002448 }
2449 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2450 // object that has file scope without an initializer, and without a
2451 // storage-class specifier or with the storage-class specifier "static",
2452 // constitutes a tentative definition. Note: A tentative definition with
2453 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002454 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002455 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002456 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2457 // array to be completed. Don't issue a diagnostic.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002458 } else if (!IDecl->isInvalidDecl() &&
2459 DiagnoseIncompleteType(IDecl->getLocation(), T,
2460 diag::err_typecheck_decl_incomplete_type))
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002461 // C99 6.9.2p3: If the declaration of an identifier for an object is
2462 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2463 // declared type shall not be an incomplete type.
Steve Naroffbb204692007-09-12 14:07:44 +00002464 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00002465 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002466 if (IDecl->isFileVarDecl())
2467 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002468 }
2469 return NewGroup;
2470}
Steve Naroffe1223f72007-08-28 03:03:08 +00002471
Chris Lattner04421082008-04-08 04:40:51 +00002472/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2473/// to introduce parameters into function prototype scope.
2474Sema::DeclTy *
2475Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002476 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002477
Chris Lattner04421082008-04-08 04:40:51 +00002478 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002479 VarDecl::StorageClass StorageClass = VarDecl::None;
2480 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2481 StorageClass = VarDecl::Register;
2482 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002483 Diag(DS.getStorageClassSpecLoc(),
2484 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002485 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002486 }
2487 if (DS.isThreadSpecified()) {
2488 Diag(DS.getThreadSpecLoc(),
2489 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002490 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002491 }
2492
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002493 // Check that there are no default arguments inside the type of this
2494 // parameter (C++ only).
2495 if (getLangOptions().CPlusPlus)
2496 CheckExtraCXXDefaultArguments(D);
2497
Chris Lattner04421082008-04-08 04:40:51 +00002498 // In this context, we *do not* check D.getInvalidType(). If the declarator
2499 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2500 // though it will not reflect the user specified type.
2501 QualType parmDeclType = GetTypeForDeclarator(D, S);
2502
2503 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2504
Reid Spencer5f016e22007-07-11 17:01:13 +00002505 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2506 // Can this happen for params? We already checked that they don't conflict
2507 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002508 IdentifierInfo *II = D.getIdentifier();
Chris Lattnercf79b012009-01-21 02:38:50 +00002509 if (II) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +00002510 if (Decl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00002511 if (PrevDecl->isTemplateParameter()) {
2512 // Maybe we will complain about the shadowed template parameter.
2513 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2514 // Just pretend that we didn't see the previous declaration.
2515 PrevDecl = 0;
2516 } else if (S->isDeclScope(PrevDecl)) {
2517 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002518
Chris Lattnercf79b012009-01-21 02:38:50 +00002519 // Recover by removing the name
2520 II = 0;
2521 D.SetIdentifier(0, D.getIdentifierLoc());
2522 }
Chris Lattner04421082008-04-08 04:40:51 +00002523 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002524 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002525
2526 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2527 // Doing the promotion here has a win and a loss. The win is the type for
2528 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2529 // code generator). The loss is the orginal type isn't preserved. For example:
2530 //
2531 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2532 // int blockvardecl[5];
2533 // sizeof(parmvardecl); // size == 4
2534 // sizeof(blockvardecl); // size == 20
2535 // }
2536 //
2537 // For expressions, all implicit conversions are captured using the
2538 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2539 //
2540 // FIXME: If a source translation tool needs to see the original type, then
2541 // we need to consider storing both types (in ParmVarDecl)...
2542 //
Chris Lattnere6327742008-04-02 05:18:44 +00002543 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002544 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002545 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002546 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002547 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002548
Chris Lattner04421082008-04-08 04:40:51 +00002549 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2550 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002551 parmDeclType, StorageClass,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002552 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002553
Chris Lattner04421082008-04-08 04:40:51 +00002554 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002555 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002556
Douglas Gregor584049d2008-12-15 23:53:10 +00002557 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2558 if (D.getCXXScopeSpec().isSet()) {
2559 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2560 << D.getCXXScopeSpec().getRange();
2561 New->setInvalidDecl();
2562 }
2563
Douglas Gregor44b43212008-12-11 16:49:14 +00002564 // Add the parameter declaration into this scope.
2565 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002566 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002567 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002568
Chris Lattner3ff30c82008-06-29 00:02:00 +00002569 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002570 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002571
Reid Spencer5f016e22007-07-11 17:01:13 +00002572}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002573
Douglas Gregorbe109b32009-01-23 16:23:13 +00002574void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002575 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2576 "Not a function declarator!");
2577 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002578
Reid Spencer5f016e22007-07-11 17:01:13 +00002579 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2580 // for a K&R function.
2581 if (!FTI.hasPrototype) {
2582 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002583 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002584 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2585 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002586 // Implicitly declare the argument as type 'int' for lack of a better
2587 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002588 DeclSpec DS;
2589 const char* PrevSpec; // unused
2590 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2591 PrevSpec);
2592 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2593 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00002594 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002595 }
2596 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00002597 }
2598}
2599
2600Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2601 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2602 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2603 "Not a function declarator!");
2604 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2605
2606 if (FTI.hasPrototype) {
Chris Lattner04421082008-04-08 04:40:51 +00002607 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002608 }
2609
Douglas Gregor584049d2008-12-15 23:53:10 +00002610 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002611
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002612 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002613 ActOnDeclarator(ParentScope, D, 0,
2614 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002615}
2616
2617Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2618 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002619 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002620
2621 // See if this is a redefinition.
2622 const FunctionDecl *Definition;
2623 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002624 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002625 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002626 }
2627
Douglas Gregor44b43212008-12-11 16:49:14 +00002628 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002629
Chris Lattner04421082008-04-08 04:40:51 +00002630 // Check the validity of our function parameters
2631 CheckParmsForFunctionDef(FD);
2632
2633 // Introduce our parameters into the function scope
2634 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2635 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00002636 Param->setOwningFunction(FD);
2637
Chris Lattner04421082008-04-08 04:40:51 +00002638 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002639 if (Param->getIdentifier())
2640 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002641 }
Chris Lattner04421082008-04-08 04:40:51 +00002642
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002643 // Checking attributes of current function definition
2644 // dllimport attribute.
2645 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2646 // dllimport attribute cannot be applied to definition.
2647 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2648 Diag(FD->getLocation(),
2649 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2650 << "dllimport";
2651 FD->setInvalidDecl();
2652 return FD;
2653 } else {
2654 // If a symbol previously declared dllimport is later defined, the
2655 // attribute is ignored in subsequent references, and a warning is
2656 // emitted.
2657 Diag(FD->getLocation(),
2658 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2659 << FD->getNameAsCString() << "dllimport";
2660 }
2661 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 return FD;
2663}
2664
Sebastian Redl798d1192008-12-13 16:23:55 +00002665Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002666 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002667 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002668 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002669 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002670 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002671 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002672 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002673 } else
2674 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002675 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002676 // Verify and clean out per-function state.
2677
2678 // Check goto/label use.
2679 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2680 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2681 // Verify that we have no forward references left. If so, there was a goto
2682 // or address of a label taken, but no definition of it. Label fwd
2683 // definitions are indicated with a null substmt.
2684 if (I->second->getSubStmt() == 0) {
2685 LabelStmt *L = I->second;
2686 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002687 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002688
2689 // At this point, we have gotos that use the bogus label. Stitch it into
2690 // the function body so that they aren't leaked and that the AST is well
2691 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002692 if (Body) {
2693 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002694 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002695 } else {
2696 // The whole function wasn't parsed correctly, just delete this.
2697 delete L;
2698 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 }
2700 }
2701 LabelMap.clear();
2702
Steve Naroffd6d054d2007-11-11 23:20:51 +00002703 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002704}
2705
Reid Spencer5f016e22007-07-11 17:01:13 +00002706/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2707/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002708NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2709 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002710 // Extension in C99. Legal in C90, but warn about it.
2711 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002712 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002713 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002714 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002715
2716 // FIXME: handle stuff like:
2717 // void foo() { extern float X(); }
2718 // void bar() { X(); } <-- implicit decl for X in another scope.
2719
2720 // Set a Declarator for the implicit definition: int foo();
2721 const char *Dummy;
2722 DeclSpec DS;
2723 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2724 Error = Error; // Silence warning.
2725 assert(!Error && "Error setting up implicit decl!");
2726 Declarator D(DS, Declarator::BlockContext);
Chris Lattner5af2f352009-01-20 19:11:22 +00002727 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc, D));
Reid Spencer5f016e22007-07-11 17:01:13 +00002728 D.SetIdentifier(&II, Loc);
2729
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002730 // Insert this function into translation-unit scope.
2731
2732 DeclContext *PrevDC = CurContext;
2733 CurContext = Context.getTranslationUnitDecl();
2734
Steve Naroffe2ef8152008-04-04 14:32:09 +00002735 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002736 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002737 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002738
2739 CurContext = PrevDC;
2740
Steve Naroffe2ef8152008-04-04 14:32:09 +00002741 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002742}
2743
2744
Chris Lattner41af0932007-11-14 06:34:38 +00002745TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002746 Decl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002747 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002748 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002749
2750 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002751 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2752 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002753 D.getIdentifier(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002754 T);
2755 NewTD->setNextDeclarator(LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002756 if (D.getInvalidType())
2757 NewTD->setInvalidDecl();
2758 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002759}
2760
Steve Naroff08d92e42007-09-15 18:49:24 +00002761/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002762/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002763/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +00002764/// reference/declaration/definition of a tag.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002765Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002766 SourceLocation KWLoc, const CXXScopeSpec &SS,
2767 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +00002768 AttributeList *Attr,
2769 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002770 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002771 assert((Name != 0 || TK == TK_Definition) &&
2772 "Nameless record must be a definition!");
2773
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002774 TagDecl::TagKind Kind;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002775 switch (TagSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002776 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002777 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2778 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2779 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2780 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002781 }
2782
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002783 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002784 DeclContext *DC = CurContext;
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002785 DeclContext *LexicalContext = CurContext;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002786 Decl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002787
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002788 bool Invalid = false;
2789
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002790 if (Name && SS.isNotEmpty()) {
2791 // We have a nested-name tag ('struct foo::bar').
2792
2793 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002794 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002795 Name = 0;
2796 goto CreateNewDecl;
2797 }
2798
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002799 DC = static_cast<DeclContext*>(SS.getScopeRep());
2800 // Look-up name inside 'foo::'.
Steve Naroff3e8ffd22009-01-29 00:07:50 +00002801 PrevDecl = dyn_cast_or_null<TagDecl>(
Douglas Gregor4c921ae2009-01-30 01:04:22 +00002802 LookupQualifiedName(DC, Name, LookupTagName).getAsDecl());
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002803
2804 // A tag 'foo::bar' must already exist.
2805 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002806 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002807 Name = 0;
2808 goto CreateNewDecl;
2809 }
Chris Lattnercf79b012009-01-21 02:38:50 +00002810 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002811 // If this is a named struct, check to see if there was a previous forward
2812 // declaration or definition.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00002813 Decl *D = LookupName(S, Name, LookupTagName);
Steve Naroffa5189032009-01-29 18:09:31 +00002814 PrevDecl = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregor72de6672009-01-08 20:45:30 +00002815
2816 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2817 // FIXME: This makes sure that we ignore the contexts associated
2818 // with C structs, unions, and enums when looking for a matching
2819 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +00002820 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002821 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2822 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +00002823 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002824 }
2825
Douglas Gregorf57172b2008-12-08 18:40:42 +00002826 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002827 // Maybe we will complain about the shadowed template parameter.
2828 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2829 // Just pretend that we didn't see the previous declaration.
2830 PrevDecl = 0;
2831 }
2832
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002833 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002834 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002835 // If this is a use of a previous tag, or if the tag is already declared
2836 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002837 // rementions the tag), reuse the decl.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002838 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002839 // Make sure that this wasn't declared as an enum and now used as a
2840 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002841 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002842 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002843 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002844 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002845 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002846 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002847 Invalid = true;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002848 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002849 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002850
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002851 // FIXME: In the future, return a variant or some other clue
2852 // for the consumer of this Decl to know it doesn't own it.
2853 // For our current ASTs this shouldn't be a problem, but will
2854 // need to be changed with DeclGroups.
2855 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002856 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002857
2858 // Diagnose attempts to redefine a tag.
2859 if (TK == TK_Definition) {
2860 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2861 Diag(NameLoc, diag::err_redefinition) << Name;
2862 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002863 // If this is a redefinition, recover by making this
2864 // struct be anonymous, which will make any later
2865 // references get the previous definition.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002866 Name = 0;
2867 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002868 Invalid = true;
2869 } else {
2870 // If the type is currently being defined, complain
2871 // about a nested redefinition.
2872 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
2873 if (Tag->isBeingDefined()) {
2874 Diag(NameLoc, diag::err_nested_redefinition) << Name;
2875 Diag(PrevTagDecl->getLocation(),
2876 diag::note_previous_definition);
2877 Name = 0;
2878 PrevDecl = 0;
2879 Invalid = true;
2880 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002881 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002882
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002883 // Okay, this is definition of a previously declared or referenced
2884 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002885 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002886 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002887 // If we get here we have (another) forward declaration or we
2888 // have a definition. Just create a new decl.
2889 } else {
2890 // If we get here, this is a definition of a new tag type in a nested
2891 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2892 // new decl/type. We set PrevDecl to NULL so that the entities
2893 // have distinct types.
2894 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002895 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002896 // If we get here, we're going to create a new Decl. If PrevDecl
2897 // is non-NULL, it's a definition of the tag declared by
2898 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002899 } else {
Douglas Gregor66973122009-01-28 17:15:10 +00002900 // PrevDecl is a namespace, template, or anything else
2901 // that lives in the IDNS_Tag identifier namespace.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002902 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002903 // The tag name clashes with a namespace name, issue an error and
2904 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002905 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002906 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002907 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002908 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002909 Invalid = true;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002910 } else {
2911 // The existing declaration isn't relevant to us; we're in a
2912 // new scope, so clear out the previous declaration.
2913 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002914 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002915 }
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002916 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
2917 (Kind != TagDecl::TK_enum)) {
2918 // C++ [basic.scope.pdecl]p5:
2919 // -- for an elaborated-type-specifier of the form
2920 //
2921 // class-key identifier
2922 //
2923 // if the elaborated-type-specifier is used in the
2924 // decl-specifier-seq or parameter-declaration-clause of a
2925 // function defined in namespace scope, the identifier is
2926 // declared as a class-name in the namespace that contains
2927 // the declaration; otherwise, except as a friend
2928 // declaration, the identifier is declared in the smallest
2929 // non-class, non-function-prototype scope that contains the
2930 // declaration.
2931 //
2932 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
2933 // C structs and unions.
2934
2935 // Find the context where we'll be declaring the tag.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002936 // FIXME: We would like to maintain the current DeclContext as the
2937 // lexical context,
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002938 while (DC->isRecord())
2939 DC = DC->getParent();
2940 LexicalContext = DC;
2941
2942 // Find the scope where we'll be declaring the tag.
2943 while (S->isClassScope() ||
2944 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00002945 ((S->getFlags() & Scope::DeclScope) == 0) ||
2946 (S->getEntity() &&
2947 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002948 S = S->getParent();
Reid Spencer5f016e22007-07-11 17:01:13 +00002949 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002950
Chris Lattnercc98eac2008-12-17 07:13:27 +00002951CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002952
2953 // If there is an identifier, use the location of the identifier as the
2954 // location of the decl, otherwise use the location of the struct/union
2955 // keyword.
2956 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2957
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002958 // Otherwise, create a new declaration. If there is a previous
2959 // declaration of the same entity, the two will be linked via
2960 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00002961 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002962
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002963 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002964 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2965 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002966 New = EnumDecl::Create(Context, DC, Loc, Name,
2967 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002968 // If this is an undefined enum, warn.
2969 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002970 } else {
2971 // struct/union/class
2972
Reid Spencer5f016e22007-07-11 17:01:13 +00002973 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2974 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002975 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002976 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002977 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2978 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002979 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002980 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2981 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002982 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002983
2984 if (Kind != TagDecl::TK_enum) {
2985 // Handle #pragma pack: if the #pragma pack stack has non-default
2986 // alignment, make up a packed attribute for this decl. These
2987 // attributes are checked when the ASTContext lays out the
2988 // structure.
2989 //
2990 // It is important for implementing the correct semantics that this
2991 // happen here (in act on tag decl). The #pragma pack stack is
2992 // maintained as a result of parser callbacks which can occur at
2993 // many points during the parsing of a struct declaration (because
2994 // the #pragma tokens are effectively skipped over during the
2995 // parsing of the struct).
2996 if (unsigned Alignment = PackContext.getAlignment())
2997 New->addAttr(new PackedAttr(Alignment * 8));
2998 }
2999
Douglas Gregor66973122009-01-28 17:15:10 +00003000 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
3001 // C++ [dcl.typedef]p3:
3002 // [...] Similarly, in a given scope, a class or enumeration
3003 // shall not be declared with the same name as a typedef-name
3004 // that is declared in that scope and refers to a type other
3005 // than the class or enumeration itself.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00003006 LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true);
Douglas Gregor66973122009-01-28 17:15:10 +00003007 TypedefDecl *PrevTypedef = 0;
3008 if (Lookup.getKind() == LookupResult::Found)
3009 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
3010
3011 if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
3012 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
3013 Context.getCanonicalType(Context.getTypeDeclType(New))) {
3014 Diag(Loc, diag::err_tag_definition_of_typedef)
3015 << Context.getTypeDeclType(New)
3016 << PrevTypedef->getUnderlyingType();
3017 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
3018 Invalid = true;
3019 }
3020 }
3021
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003022 if (Invalid)
3023 New->setInvalidDecl();
3024
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003025 if (Attr)
3026 ProcessDeclAttributeList(New, Attr);
3027
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003028 // If we're declaring or defining a tag in function prototype scope
3029 // in C, note that this type can only be used within the function.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003030 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3031 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3032
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003033 // Set the lexical context. If the tag has a C++ scope specifier, the
3034 // lexical context will be different from the semantic context.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003035 New->setLexicalDeclContext(LexicalContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003036
3037 if (TK == TK_Definition)
3038 New->startDefinition();
Reid Spencer5f016e22007-07-11 17:01:13 +00003039
3040 // If this has an identifier, add it to the scope stack.
3041 if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003042 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003043
3044 // Add it to the decl chain.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003045 if (LexicalContext != CurContext) {
3046 // FIXME: PushOnScopeChains should not rely on CurContext!
3047 DeclContext *OldContext = CurContext;
3048 CurContext = LexicalContext;
3049 PushOnScopeChains(New, S);
3050 CurContext = OldContext;
3051 } else
3052 PushOnScopeChains(New, S);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003053 } else {
Douglas Gregor482b77d2009-01-12 23:27:07 +00003054 LexicalContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00003055 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00003056
Reid Spencer5f016e22007-07-11 17:01:13 +00003057 return New;
3058}
3059
Douglas Gregor72de6672009-01-08 20:45:30 +00003060void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3061 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3062
3063 // Enter the tag context.
3064 PushDeclContext(S, Tag);
3065
3066 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3067 FieldCollector->StartClass();
3068
3069 if (Record->getIdentifier()) {
3070 // C++ [class]p2:
3071 // [...] The class-name is also inserted into the scope of the
3072 // class itself; this is known as the injected-class-name. For
3073 // purposes of access checking, the injected-class-name is treated
3074 // as if it were a public member name.
3075 RecordDecl *InjectedClassName
3076 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3077 CurContext, Record->getLocation(),
3078 Record->getIdentifier(), Record);
3079 InjectedClassName->setImplicit();
3080 PushOnScopeChains(InjectedClassName, S);
3081 }
3082 }
3083}
3084
3085void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3086 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3087
3088 if (isa<CXXRecordDecl>(Tag))
3089 FieldCollector->FinishClass();
3090
3091 // Exit this scope of this tag's definition.
3092 PopDeclContext();
3093
3094 // Notify the consumer that we've defined a tag.
3095 Consumer.HandleTagDeclDefinition(Tag);
3096}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00003097
Chris Lattner1d353ba2008-11-12 21:17:48 +00003098/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3099/// types into constant array types in certain situations which would otherwise
3100/// be errors (for GCC compatibility).
3101static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3102 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00003103 // This method tries to turn a variable array into a constant
3104 // array even when the size isn't an ICE. This is necessary
3105 // for compatibility with code that depends on gcc's buggy
3106 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00003107 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3108 if (!VLATy) return QualType();
3109
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003110 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00003111 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003112 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00003113 return QualType();
3114
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003115 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3116 llvm::APSInt &Res = EvalResult.Val.getInt();
Nuno Lopes1dfa6e12009-02-02 22:32:08 +00003117 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3118 return Context.getConstantArrayType(VLATy->getElementType(),
3119 Res, ArrayType::Normal, 0);
3120 return QualType();
Eli Friedman1b76ada2008-06-03 21:01:11 +00003121}
3122
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003123bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00003124 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003125 // FIXME: 6.7.2.1p4 - verify the field type.
3126
3127 llvm::APSInt Value;
3128 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3129 return true;
3130
Chris Lattnercd087072008-12-12 04:56:04 +00003131 // Zero-width bitfield is ok for anonymous field.
3132 if (Value == 0 && FieldName)
3133 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3134
3135 if (Value.isNegative())
3136 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003137
3138 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3139 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00003140 if (TypeSize && Value.getZExtValue() > TypeSize)
3141 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3142 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003143
3144 return false;
3145}
3146
Steve Naroff08d92e42007-09-15 18:49:24 +00003147/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00003148/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00003149Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00003150 SourceLocation DeclStart,
3151 Declarator &D, ExprTy *BitfieldWidth) {
3152 IdentifierInfo *II = D.getIdentifier();
3153 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00003154 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00003155 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003156 if (II) Loc = D.getIdentifierLoc();
3157
3158 // FIXME: Unnamed fields can be handled in various different ways, for
3159 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00003160
Reid Spencer5f016e22007-07-11 17:01:13 +00003161 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00003162 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3163 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00003164
Reid Spencer5f016e22007-07-11 17:01:13 +00003165 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3166 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00003167 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00003168 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003169 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003170 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003171 T = FixedTy;
3172 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003173 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00003174 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00003175 InvalidDecl = true;
3176 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003177 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003178
3179 if (BitWidth) {
3180 if (VerifyBitField(Loc, II, T, BitWidth))
3181 InvalidDecl = true;
3182 } else {
3183 // Not a bitfield.
3184
3185 // validate II.
3186
3187 }
3188
Reid Spencer5f016e22007-07-11 17:01:13 +00003189 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003190 FieldDecl *NewFD;
3191
Douglas Gregor44b43212008-12-11 16:49:14 +00003192 NewFD = FieldDecl::Create(Context, Record,
3193 Loc, II, T, BitWidth,
3194 D.getDeclSpec().getStorageClassSpec() ==
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003195 DeclSpec::SCS_mutable);
Douglas Gregor44b43212008-12-11 16:49:14 +00003196
Douglas Gregor72de6672009-01-08 20:45:30 +00003197 if (II) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +00003198 Decl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregor72de6672009-01-08 20:45:30 +00003199 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3200 && !isa<TagDecl>(PrevDecl)) {
3201 Diag(Loc, diag::err_duplicate_member) << II;
3202 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3203 NewFD->setInvalidDecl();
3204 Record->setInvalidDecl();
3205 }
3206 }
3207
Sebastian Redl64b45f72009-01-05 20:52:13 +00003208 if (getLangOptions().CPlusPlus) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003209 CheckExtraCXXDefaultArguments(D);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003210 if (!T->isPODType())
3211 cast<CXXRecordDecl>(Record)->setPOD(false);
3212 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003213
Chris Lattner3ff30c82008-06-29 00:02:00 +00003214 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00003215
Steve Naroff5912a352007-08-28 20:14:24 +00003216 if (D.getInvalidType() || InvalidDecl)
3217 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003218
Douglas Gregor72de6672009-01-08 20:45:30 +00003219 if (II) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003220 PushOnScopeChains(NewFD, S);
Douglas Gregor72de6672009-01-08 20:45:30 +00003221 } else
Douglas Gregor482b77d2009-01-12 23:27:07 +00003222 Record->addDecl(NewFD);
Douglas Gregor44b43212008-12-11 16:49:14 +00003223
Steve Naroff5912a352007-08-28 20:14:24 +00003224 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003225}
3226
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003227/// TranslateIvarVisibility - Translate visibility from a token ID to an
3228/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003229static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003230TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00003231 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00003232 default: assert(0 && "Unknown visitibility kind");
3233 case tok::objc_private: return ObjCIvarDecl::Private;
3234 case tok::objc_public: return ObjCIvarDecl::Public;
3235 case tok::objc_protected: return ObjCIvarDecl::Protected;
3236 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00003237 }
3238}
3239
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003240/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3241/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003242Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003243 SourceLocation DeclStart,
3244 Declarator &D, ExprTy *BitfieldWidth,
3245 tok::ObjCKeywordKind Visibility) {
Douglas Gregor72de6672009-01-08 20:45:30 +00003246
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003247 IdentifierInfo *II = D.getIdentifier();
3248 Expr *BitWidth = (Expr*)BitfieldWidth;
3249 SourceLocation Loc = DeclStart;
3250 if (II) Loc = D.getIdentifierLoc();
3251
3252 // FIXME: Unnamed fields can be handled in various different ways, for
3253 // example, unnamed unions inject all members into the struct namespace!
3254
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003255 QualType T = GetTypeForDeclarator(D, S);
3256 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3257 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003258
3259 if (BitWidth) {
3260 // TODO: Validate.
3261 //printf("WARNING: BITFIELDS IGNORED!\n");
3262
3263 // 6.7.2.1p3
3264 // 6.7.2.1p4
3265
3266 } else {
3267 // Not a bitfield.
3268
3269 // validate II.
3270
3271 }
3272
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003273 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3274 // than a variably modified type.
3275 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00003276 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003277 InvalidDecl = true;
3278 }
3279
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003280 // Get the visibility (access control) for this ivar.
3281 ObjCIvarDecl::AccessControl ac =
3282 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3283 : ObjCIvarDecl::None;
3284
3285 // Construct the decl.
3286 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00003287 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003288
Douglas Gregor72de6672009-01-08 20:45:30 +00003289 if (II) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +00003290 Decl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregor72de6672009-01-08 20:45:30 +00003291 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3292 && !isa<TagDecl>(PrevDecl)) {
3293 Diag(Loc, diag::err_duplicate_member) << II;
3294 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3295 NewID->setInvalidDecl();
3296 }
3297 }
3298
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003299 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00003300 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003301
3302 if (D.getInvalidType() || InvalidDecl)
3303 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003304
Douglas Gregor72de6672009-01-08 20:45:30 +00003305 if (II) {
3306 // FIXME: When interfaces are DeclContexts, we'll need to add
3307 // these to the interface.
3308 S->AddDecl(NewID);
3309 IdResolver.AddDecl(NewID);
3310 }
3311
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003312 return NewID;
3313}
3314
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00003315void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003316 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00003317 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00003318 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00003319 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00003320 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3321 assert(EnclosingDecl && "missing record or interface decl");
3322 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3323
Reid Spencer5f016e22007-07-11 17:01:13 +00003324 // Verify that all the fields are okay.
3325 unsigned NumNamedMembers = 0;
3326 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003327
Reid Spencer5f016e22007-07-11 17:01:13 +00003328 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff74216642007-09-14 22:20:54 +00003329 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3330 assert(FD && "missing field decl");
3331
Reid Spencer5f016e22007-07-11 17:01:13 +00003332 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003333 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003334
Douglas Gregor72de6672009-01-08 20:45:30 +00003335 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003336 // Remember all fields written by the user.
3337 RecFields.push_back(FD);
3338 }
Steve Narofff13271f2007-09-14 23:09:53 +00003339
Reid Spencer5f016e22007-07-11 17:01:13 +00003340 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003341 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003342 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003343 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003344 FD->setInvalidDecl();
3345 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003346 continue;
3347 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003348 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3349 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003350 if (!Record) { // Incomplete ivar type is always an error.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003351 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3352 diag::err_field_incomplete);
Steve Naroff74216642007-09-14 22:20:54 +00003353 FD->setInvalidDecl();
3354 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003355 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003356 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003357 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003358 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003359 !FDTy->isArrayType()) { //... may have incomplete array type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003360 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3361 diag::err_field_incomplete);
Steve Naroff74216642007-09-14 22:20:54 +00003362 FD->setInvalidDecl();
3363 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003364 continue;
3365 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003366 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003367 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003368 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003369 FD->setInvalidDecl();
3370 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003371 continue;
3372 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003373 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003374 if (Record)
3375 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003376 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003377 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3378 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003379 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003380 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3381 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003382 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003383 Record->setHasFlexibleArrayMember(true);
3384 } else {
3385 // If this is a struct/class and this is not the last element, reject
3386 // it. Note that GCC supports variable sized arrays in the middle of
3387 // structures.
3388 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003389 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003390 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003391 FD->setInvalidDecl();
3392 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003393 continue;
3394 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003395 // We support flexible arrays at the end of structs in other structs
3396 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003397 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003398 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003399 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003400 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003401 }
3402 }
3403 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003404 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003405 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003406 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003407 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003408 FD->setInvalidDecl();
3409 EnclosingDecl->setInvalidDecl();
3410 continue;
3411 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003412 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00003413 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00003414 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003415 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003416
Reid Spencer5f016e22007-07-11 17:01:13 +00003417 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003418 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003419 Record->completeDefinition(Context);
Chris Lattnere1e79852008-02-06 00:51:33 +00003420 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003421 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003422 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003423 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003424 // Must enforce the rule that ivars in the base classes may not be
3425 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003426 if (ID->getSuperClass()) {
3427 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3428 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3429 ObjCIvarDecl* Ivar = (*IVI);
3430 IdentifierInfo *II = Ivar->getIdentifier();
3431 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3432 if (prevIvar) {
3433 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregor72de6672009-01-08 20:45:30 +00003434 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003435 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003436 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003437 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003438 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003439 else if (ObjCImplementationDecl *IMPDecl =
3440 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003441 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3442 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003443 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003444 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003445 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003446
3447 if (Attr)
3448 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003449}
3450
Steve Naroff08d92e42007-09-15 18:49:24 +00003451Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003452 DeclTy *lastEnumConst,
3453 SourceLocation IdLoc, IdentifierInfo *Id,
3454 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003455 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003456 EnumConstantDecl *LastEnumConst =
3457 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3458 Expr *Val = static_cast<Expr*>(val);
3459
Chris Lattner31e05722007-08-26 06:24:45 +00003460 // The scope passed in may not be a decl scope. Zip up the scope tree until
3461 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003462 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003463
Reid Spencer5f016e22007-07-11 17:01:13 +00003464 // Verify that there isn't already something declared with this name in this
3465 // scope.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00003466 Decl *PrevDecl = LookupName(S, Id, LookupOrdinaryName);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003467 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003468 // Maybe we will complain about the shadowed template parameter.
3469 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3470 // Just pretend that we didn't see the previous declaration.
3471 PrevDecl = 0;
3472 }
3473
3474 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003475 // When in C++, we may get a TagDecl with the same name; in this case the
3476 // enum constant will 'hide' the tag.
3477 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3478 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003479 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003480 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003481 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003482 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003483 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003484 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003485 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003486 return 0;
3487 }
3488 }
3489
3490 llvm::APSInt EnumVal(32);
3491 QualType EltTy;
3492 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003493 // Make sure to promote the operand type to int.
3494 UsualUnaryConversions(Val);
3495
Reid Spencer5f016e22007-07-11 17:01:13 +00003496 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3497 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003498 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003499 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003500 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003501 } else {
3502 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003503 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003504 }
3505
3506 if (!Val) {
3507 if (LastEnumConst) {
3508 // Assign the last value + 1.
3509 EnumVal = LastEnumConst->getInitVal();
3510 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003511
3512 // Check for overflow on increment.
3513 if (EnumVal < LastEnumConst->getInitVal())
3514 Diag(IdLoc, diag::warn_enum_value_overflow);
3515
Chris Lattnerb7416f92007-08-27 17:37:24 +00003516 EltTy = LastEnumConst->getType();
3517 } else {
3518 // First value, set to zero.
3519 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003520 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003521 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003522 }
3523
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003524 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003525 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003526 Val, EnumVal);
Reid Spencer5f016e22007-07-11 17:01:13 +00003527
3528 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003529 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003530
Reid Spencer5f016e22007-07-11 17:01:13 +00003531 return New;
3532}
3533
Steve Naroff02408c62008-08-07 14:08:16 +00003534// FIXME: For consistency with ActOnFields(), we should have the parser
3535// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003536void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003537 DeclTy **Elements, unsigned NumElements) {
3538 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00003539 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003540
Chris Lattnere37f0be2007-08-28 05:10:31 +00003541 // TODO: If the result value doesn't fit in an int, it must be a long or long
3542 // long value. ISO C does not support this, but GCC does as an extension,
3543 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003544 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003545
Chris Lattnerac609682007-08-28 06:15:15 +00003546 // Verify that all the values are okay, compute the size of the values, and
3547 // reverse the list.
3548 unsigned NumNegativeBits = 0;
3549 unsigned NumPositiveBits = 0;
3550
3551 // Keep track of whether all elements have type int.
3552 bool AllElementsInt = true;
3553
Reid Spencer5f016e22007-07-11 17:01:13 +00003554 for (unsigned i = 0; i != NumElements; ++i) {
3555 EnumConstantDecl *ECD =
3556 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3557 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003558
3559 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003560 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003561 assert(InitVal.getBitWidth() >= IntWidth &&
3562 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003563 if (InitVal.getBitWidth() > IntWidth) {
3564 llvm::APSInt V(InitVal);
3565 V.trunc(IntWidth);
3566 V.extend(InitVal.getBitWidth());
3567 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003568 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3569 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003570 }
Chris Lattnerac609682007-08-28 06:15:15 +00003571
3572 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003573 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003574 NumPositiveBits = std::max(NumPositiveBits,
3575 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003576 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003577 NumNegativeBits = std::max(NumNegativeBits,
3578 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003579
Chris Lattnerac609682007-08-28 06:15:15 +00003580 // Keep track of whether every enum element has type int (very commmon).
3581 if (AllElementsInt)
3582 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003583 }
3584
Chris Lattnerac609682007-08-28 06:15:15 +00003585 // Figure out the type that should be used for this enum.
3586 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3587 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003588 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003589
3590 if (NumNegativeBits) {
3591 // If there is a negative value, figure out the smallest integer type (of
3592 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003593 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003594 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003595 BestWidth = IntWidth;
3596 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003597 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003598
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003599 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003600 BestType = Context.LongTy;
3601 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003602 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003603
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003604 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003605 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3606 BestType = Context.LongLongTy;
3607 }
3608 }
3609 } else {
3610 // If there is no negative value, figure out which of uint, ulong, ulonglong
3611 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003612 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003613 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003614 BestWidth = IntWidth;
3615 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003616 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003617 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003618 } else {
3619 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003620 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003621 "How could an initializer get larger than ULL?");
3622 BestType = Context.UnsignedLongLongTy;
3623 }
3624 }
3625
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003626 // Loop over all of the enumerator constants, changing their types to match
3627 // the type of the enum if needed.
3628 for (unsigned i = 0; i != NumElements; ++i) {
3629 EnumConstantDecl *ECD =
3630 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3631 if (!ECD) continue; // Already issued a diagnostic.
3632
3633 // Standard C says the enumerators have int type, but we allow, as an
3634 // extension, the enumerators to be larger than int size. If each
3635 // enumerator value fits in an int, type it as an int, otherwise type it the
3636 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3637 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003638 if (ECD->getType() == Context.IntTy) {
3639 // Make sure the init value is signed.
3640 llvm::APSInt IV = ECD->getInitVal();
3641 IV.setIsSigned(true);
3642 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003643
3644 if (getLangOptions().CPlusPlus)
3645 // C++ [dcl.enum]p4: Following the closing brace of an
3646 // enum-specifier, each enumerator has the type of its
3647 // enumeration.
3648 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003649 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003650 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003651
3652 // Determine whether the value fits into an int.
3653 llvm::APSInt InitVal = ECD->getInitVal();
3654 bool FitsInInt;
3655 if (InitVal.isUnsigned() || !InitVal.isNegative())
3656 FitsInInt = InitVal.getActiveBits() < IntWidth;
3657 else
3658 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3659
3660 // If it fits into an integer type, force it. Otherwise force it to match
3661 // the enum decl type.
3662 QualType NewTy;
3663 unsigned NewWidth;
3664 bool NewSign;
3665 if (FitsInInt) {
3666 NewTy = Context.IntTy;
3667 NewWidth = IntWidth;
3668 NewSign = true;
3669 } else if (ECD->getType() == BestType) {
3670 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003671 if (getLangOptions().CPlusPlus)
3672 // C++ [dcl.enum]p4: Following the closing brace of an
3673 // enum-specifier, each enumerator has the type of its
3674 // enumeration.
3675 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003676 continue;
3677 } else {
3678 NewTy = BestType;
3679 NewWidth = BestWidth;
3680 NewSign = BestType->isSignedIntegerType();
3681 }
3682
3683 // Adjust the APSInt value.
3684 InitVal.extOrTrunc(NewWidth);
3685 InitVal.setIsSigned(NewSign);
3686 ECD->setInitVal(InitVal);
3687
3688 // Adjust the Expr initializer and type.
Chris Lattner13fd4162009-01-15 19:19:42 +00003689 if (ECD->getInitExpr())
3690 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3691 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003692 if (getLangOptions().CPlusPlus)
3693 // C++ [dcl.enum]p4: Following the closing brace of an
3694 // enum-specifier, each enumerator has the type of its
3695 // enumeration.
3696 ECD->setType(EnumType);
3697 else
3698 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003699 }
Chris Lattnerac609682007-08-28 06:15:15 +00003700
Douglas Gregor44b43212008-12-11 16:49:14 +00003701 Enum->completeDefinition(Context, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00003702}
3703
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003704Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003705 ExprArg expr) {
3706 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3707
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003708 return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003709}
3710
Douglas Gregorf44515a2008-12-16 22:23:02 +00003711
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003712void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3713 ExprTy *alignment, SourceLocation PragmaLoc,
3714 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3715 Expr *Alignment = static_cast<Expr *>(alignment);
3716
3717 // If specified then alignment must be a "small" power of two.
3718 unsigned AlignmentVal = 0;
3719 if (Alignment) {
3720 llvm::APSInt Val;
3721 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3722 !Val.isPowerOf2() ||
3723 Val.getZExtValue() > 16) {
3724 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3725 delete Alignment;
3726 return; // Ignore
3727 }
3728
3729 AlignmentVal = (unsigned) Val.getZExtValue();
3730 }
3731
3732 switch (Kind) {
3733 case Action::PPK_Default: // pack([n])
3734 PackContext.setAlignment(AlignmentVal);
3735 break;
3736
3737 case Action::PPK_Show: // pack(show)
3738 // Show the current alignment, making sure to show the right value
3739 // for the default.
3740 AlignmentVal = PackContext.getAlignment();
3741 // FIXME: This should come from the target.
3742 if (AlignmentVal == 0)
3743 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003744 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003745 break;
3746
3747 case Action::PPK_Push: // pack(push [, id] [, [n])
3748 PackContext.push(Name);
3749 // Set the new alignment if specified.
3750 if (Alignment)
3751 PackContext.setAlignment(AlignmentVal);
3752 break;
3753
3754 case Action::PPK_Pop: // pack(pop [, id] [, n])
3755 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3756 // "#pragma pack(pop, identifier, n) is undefined"
3757 if (Alignment && Name)
3758 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3759
3760 // Do the pop.
3761 if (!PackContext.pop(Name)) {
3762 // If a name was specified then failure indicates the name
3763 // wasn't found. Otherwise failure indicates the stack was
3764 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003765 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3766 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003767
3768 // FIXME: Warn about popping named records as MSVC does.
3769 } else {
3770 // Pop succeeded, set the new alignment if specified.
3771 if (Alignment)
3772 PackContext.setAlignment(AlignmentVal);
3773 }
3774 break;
3775
3776 default:
3777 assert(0 && "Invalid #pragma pack kind.");
3778 }
3779}
3780
3781bool PragmaPackStack::pop(IdentifierInfo *Name) {
3782 if (Stack.empty())
3783 return false;
3784
3785 // If name is empty just pop top.
3786 if (!Name) {
3787 Alignment = Stack.back().first;
3788 Stack.pop_back();
3789 return true;
3790 }
3791
3792 // Otherwise, find the named record.
3793 for (unsigned i = Stack.size(); i != 0; ) {
3794 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003795 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003796 // Found it, pop up to and including this record.
3797 Alignment = Stack[i].first;
3798 Stack.erase(Stack.begin() + i, Stack.end());
3799 return true;
3800 }
3801 }
3802
3803 return false;
3804}