blob: e0cb526c6012ce304595886e21310dc8c576c4fa [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"
Chris Lattner20c6b3b2009-01-27 18:30:58 +000021#include "clang/Basic/DiagnosticSema.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregore267ff32008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Douglas Gregore267ff32008-12-11 20:41:00 +000031
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
Douglas Gregor2def4832008-11-17 20:34:05 +000034Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000035 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000036 DeclContext *DC = 0;
37 if (SS) {
38 if (SS->isInvalid())
39 return 0;
40 DC = static_cast<DeclContext*>(SS->getScopeRep());
41 }
Steve Naroff939837f2009-01-28 15:51:12 +000042 LookupResult Result = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC);
Steve Naroffb327ce02008-04-02 14:35:35 +000043
Douglas Gregor7176fff2009-01-15 00:26:24 +000044 Decl *IIDecl = 0;
45 switch (Result.getKind()) {
46 case LookupResult::NotFound:
47 case LookupResult::FoundOverloaded:
48 case LookupResult::AmbiguousBaseSubobjectTypes:
49 case LookupResult::AmbiguousBaseSubobjects:
50 // FIXME: In the event of an ambiguous lookup, we could visit all of
51 // the entities found to determine whether they are all types. This
52 // might provide better diagnostics.
53 return 0;
54
55 case LookupResult::Found:
56 IIDecl = Result.getAsDecl();
57 break;
58 }
59
60 if (isa<TypedefDecl>(IIDecl) ||
61 isa<ObjCInterfaceDecl>(IIDecl) ||
62 isa<TagDecl>(IIDecl) ||
63 isa<TemplateTypeParmDecl>(IIDecl))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000064 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000065 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000066}
67
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000068DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000069 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000070 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000071 if (MD->isOutOfLineDefinition())
72 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000073
74 // A C++ inline method is parsed *after* the topmost class it was declared in
75 // is fully parsed (it's "complete").
76 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000077 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000078 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
79 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000080 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000081 DC = RD;
82
83 // Return the declaration context of the topmost class the inline method is
84 // declared in.
85 return DC;
86 }
87
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000088 if (isa<ObjCMethodDecl>(DC))
89 return Context.getTranslationUnitDecl();
90
Douglas Gregor4afa39d2009-01-20 01:17:11 +000091 if (Decl *D = dyn_cast<Decl>(DC))
92 return D->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000093
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000094 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000095}
96
Douglas Gregor44b43212008-12-11 16:49:14 +000097void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000098 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +000099 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +0000100 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +0000101 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000102}
103
Chris Lattnerb048c982008-04-06 04:47:34 +0000104void Sema::PopDeclContext() {
105 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +0000106
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000107 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000108}
109
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000110/// Add this decl to the scope shadowed decl chains.
111void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000112 // Move up the scope chain until we find the nearest enclosing
113 // non-transparent context. The declaration will be introduced into this
114 // scope.
115 while (S->getEntity() &&
116 ((DeclContext *)S->getEntity())->isTransparentContext())
117 S = S->getParent();
118
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000119 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000120
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000121 // Add scoped declarations into their context, so that they can be
122 // found later. Declarations without a context won't be inserted
123 // into any context.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000124 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000125
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000126 // C++ [basic.scope]p4:
127 // -- exactly one declaration shall declare a class name or
128 // enumeration name that is not a typedef name and the other
129 // declarations shall all refer to the same object or
130 // enumerator, or all refer to functions and function templates;
131 // in this case the class name or enumeration name is hidden.
132 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
133 // We are pushing the name of a tag (enum or class).
Douglas Gregore21b9942009-01-07 16:34:42 +0000134 if (CurContext->getLookupContext()
135 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000136 // We're pushing the tag into the current context, which might
137 // require some reshuffling in the identifier resolver.
138 IdentifierResolver::iterator
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000139 I = IdResolver.begin(TD->getDeclName(), CurContext,
140 false/*LookInParentCtx*/),
141 IEnd = IdResolver.end();
142 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
143 NamedDecl *PrevDecl = *I;
144 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
145 PrevDecl = *I, ++I) {
146 if (TD->declarationReplaces(*I)) {
147 // This is a redeclaration. Remove it from the chain and
148 // break out, so that we'll add in the shadowed
149 // declaration.
150 S->RemoveDecl(*I);
151 if (PrevDecl == *I) {
152 IdResolver.RemoveDecl(*I);
153 IdResolver.AddDecl(TD);
154 return;
155 } else {
156 IdResolver.RemoveDecl(*I);
157 break;
158 }
159 }
160 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000161
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000162 // There is already a declaration with the same name in the same
163 // scope, which is not a tag declaration. It must be found
164 // before we find the new declaration, so insert the new
165 // declaration at the end of the chain.
166 IdResolver.AddShadowedDecl(TD, PrevDecl);
167
168 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000169 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000170 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000171 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000172 // We are pushing the name of a function, which might be an
173 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000174 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregorce356072009-01-06 23:51:29 +0000175 DeclContext *DC = FD->getDeclContext()->getLookupContext();
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000176 IdentifierResolver::iterator Redecl
Douglas Gregor074149e2009-01-05 19:45:36 +0000177 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000178 false/*LookInParentCtx*/),
179 IdResolver.end(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000180 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000181 FD));
182 if (Redecl != IdResolver.end()) {
183 // There is already a declaration of a function on our
184 // IdResolver chain. Replace it with this declaration.
185 S->RemoveDecl(*Redecl);
186 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000187 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000188 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000189
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000190 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000191}
192
Steve Naroffb216c882007-10-09 22:01:59 +0000193void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000194 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000195 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
196 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000197
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
199 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000200 Decl *TmpD = static_cast<Decl*>(*I);
201 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000202
Douglas Gregor44b43212008-12-11 16:49:14 +0000203 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
204 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000205
Douglas Gregor44b43212008-12-11 16:49:14 +0000206 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000207
Douglas Gregor44b43212008-12-11 16:49:14 +0000208 // Remove this name from our lexical scope.
209 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000210 }
211}
212
Steve Naroffe8043c32008-04-01 23:04:06 +0000213/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
214/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000215ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000216 // The third "scope" argument is 0 since we aren't enabling lazy built-in
217 // creation from this context.
Steve Naroff133147d2009-01-28 16:09:22 +0000218 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000219
Steve Naroffb327ce02008-04-02 14:35:35 +0000220 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000221}
222
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000223/// getNonFieldDeclScope - Retrieves the innermost scope, starting
224/// from S, where a non-field would be declared. This routine copes
225/// with the difference between C and C++ scoping rules in structs and
226/// unions. For example, the following code is well-formed in C but
227/// ill-formed in C++:
228/// @code
229/// struct S6 {
230/// enum { BAR } e;
231/// };
232///
233/// void test_S6() {
234/// struct S6 a;
235/// a.e = BAR;
236/// }
237/// @endcode
238/// For the declaration of BAR, this routine will return a different
239/// scope. The scope S will be the scope of the unnamed enumeration
240/// within S6. In C++, this routine will return the scope associated
241/// with S6, because the enumeration's scope is a transparent
242/// context but structures can contain non-field names. In C, this
243/// routine will return the translation unit scope, since the
244/// enumeration's scope is a transparent context and structures cannot
245/// contain non-field names.
246Scope *Sema::getNonFieldDeclScope(Scope *S) {
247 while (((S->getFlags() & Scope::DeclScope) == 0) ||
248 (S->getEntity() &&
249 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
250 (S->isClassScope() && !getLangOptions().CPlusPlus))
251 S = S->getParent();
252 return S;
253}
254
Steve Naroffe8043c32008-04-01 23:04:06 +0000255/// LookupDecl - Look up the inner-most declaration in the specified
Douglas Gregorf780abc2008-12-30 03:27:21 +0000256/// namespace. NamespaceNameOnly - during lookup only namespace names
257/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
258/// 'When looking up a namespace-name in a using-directive or
259/// namespace-alias-definition, only namespace names are considered.'
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000260///
261/// Note: The use of this routine is deprecated. Please use
262/// LookupName, LookupQualifiedName, or LookupParsedName instead.
263Sema::LookupResult
264Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
265 const DeclContext *LookupCtx,
Steve Naroff133147d2009-01-28 16:09:22 +0000266 bool LookInParent) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000267 LookupCriteria::NameKind Kind;
268 if (NSI == Decl::IDNS_Ordinary) {
Steve Naroff133147d2009-01-28 16:09:22 +0000269 Kind = LookupCriteria::Ordinary;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000270 } else if (NSI == Decl::IDNS_Tag)
271 Kind = LookupCriteria::Tag;
Chris Lattner95d58f32009-01-16 19:44:00 +0000272 else {
273 assert(NSI == Decl::IDNS_Member &&"Unable to grok LookupDecl NSI argument");
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000274 Kind = LookupCriteria::Member;
Chris Lattner95d58f32009-01-16 19:44:00 +0000275 }
276
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000277 if (LookupCtx)
278 return LookupQualifiedName(const_cast<DeclContext *>(LookupCtx), Name,
279 LookupCriteria(Kind, !LookInParent,
280 getLangOptions().CPlusPlus));
Douglas Gregor72de6672009-01-08 20:45:30 +0000281
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000282 // Unqualified lookup
283 return LookupName(S, Name,
284 LookupCriteria(Kind, !LookInParent,
285 getLangOptions().CPlusPlus));
Reid Spencer5f016e22007-07-11 17:01:13 +0000286}
287
Chris Lattner95e2c712008-05-05 22:18:14 +0000288void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000289 if (!Context.getBuiltinVaListType().isNull())
290 return;
291
292 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000293 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000294 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000295 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
296}
297
Reid Spencer5f016e22007-07-11 17:01:13 +0000298/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
299/// lazily create a decl for it.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000300NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
301 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000302 Builtin::ID BID = (Builtin::ID)bid;
303
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000304 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000305 InitBuiltinVaListType();
306
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000307 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000308 FunctionDecl *New = FunctionDecl::Create(Context,
309 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000310 SourceLocation(), II, R,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000311 FunctionDecl::Extern, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000312
Chris Lattner95e2c712008-05-05 22:18:14 +0000313 // Create Decl objects for each parameter, adding them to the
314 // FunctionDecl.
315 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
316 llvm::SmallVector<ParmVarDecl*, 16> Params;
317 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
318 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000319 FT->getArgType(i), VarDecl::None, 0));
Ted Kremenekfc767612009-01-14 00:42:25 +0000320 New->setParams(Context, &Params[0], Params.size());
Chris Lattner95e2c712008-05-05 22:18:14 +0000321 }
322
323
324
Chris Lattner7f925cc2008-04-11 07:00:53 +0000325 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000326 // FIXME: This is hideous. We need to teach PushOnScopeChains to
327 // relate Scopes to DeclContexts, and probably eliminate CurContext
328 // entirely, but we're not there yet.
329 DeclContext *SavedContext = CurContext;
330 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000331 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000332 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 return New;
334}
335
Sebastian Redlc42e1182008-11-11 11:37:55 +0000336/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
337/// everything from the standard library is defined.
338NamespaceDecl *Sema::GetStdNamespace() {
339 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000340 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000341 DeclContext *Global = Context.getTranslationUnitDecl();
Steve Naroff939837f2009-01-28 15:51:12 +0000342 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Ordinary, 0, Global);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000343 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
344 }
345 return StdNamespace;
346}
347
Reid Spencer5f016e22007-07-11 17:01:13 +0000348/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
349/// and scope as a previous declaration 'Old'. Figure out how to resolve this
350/// situation, merging decls or emitting diagnostics as appropriate.
351///
Steve Naroffe8043c32008-04-01 23:04:06 +0000352TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000353 bool objc_types = false;
Steve Naroff2b255c42008-09-09 14:32:20 +0000354 // Allow multiple definitions for ObjC built-in typedefs.
355 // FIXME: Verify the underlying types are equivalent!
356 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000357 const IdentifierInfo *TypeID = New->getIdentifier();
358 switch (TypeID->getLength()) {
359 default: break;
360 case 2:
361 if (!TypeID->isStr("id"))
362 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000363 Context.setObjCIdType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000364 objc_types = true;
365 break;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000366 case 5:
367 if (!TypeID->isStr("Class"))
368 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000369 Context.setObjCClassType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000370 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000371 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000372 case 3:
373 if (!TypeID->isStr("SEL"))
374 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000375 Context.setObjCSelType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000376 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000377 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000378 case 8:
379 if (!TypeID->isStr("Protocol"))
380 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000381 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000382 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000383 return New;
384 }
385 // Fall through - the typedef name was not a builtin type.
386 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 // Verify the old decl was also a typedef.
388 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
389 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000390 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000391 << New->getDeclName();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000392 if (!objc_types)
393 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 return New;
395 }
396
Chris Lattner99cb9972008-07-25 18:44:27 +0000397 // If the typedef types are not identical, reject them in all languages and
398 // with any extensions enabled.
399 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
400 Context.getCanonicalType(Old->getUnderlyingType()) !=
401 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000402 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000403 << New->getUnderlyingType() << Old->getUnderlyingType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000404 if (!objc_types)
405 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000406 return New;
Chris Lattner99cb9972008-07-25 18:44:27 +0000407 }
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000408 if (objc_types) return New;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000409 if (getLangOptions().Microsoft) return New;
410
Douglas Gregorbbe27432008-11-21 16:29:06 +0000411 // C++ [dcl.typedef]p2:
412 // In a given non-class scope, a typedef specifier can be used to
413 // redefine the name of any type declared in that scope to refer
414 // to the type to which it already refers.
415 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
416 return New;
417
418 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000419 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
420 // *either* declaration is in a system header. The code below implements
421 // this adhoc compatibility rule. FIXME: The following code will not
422 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000423 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
424 SourceManager &SrcMgr = Context.getSourceManager();
425 if (SrcMgr.isInSystemHeader(Old->getLocation()))
426 return New;
427 if (SrcMgr.isInSystemHeader(New->getLocation()))
428 return New;
429 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000430
Chris Lattner08631c52008-11-23 21:45:46 +0000431 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000432 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 return New;
434}
435
Chris Lattner6b6b5372008-06-26 18:38:35 +0000436/// DeclhasAttr - returns true if decl Declaration already has the target
437/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000438static bool DeclHasAttr(const Decl *decl, const Attr *target) {
439 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
440 if (attr->getKind() == target->getKind())
441 return true;
442
443 return false;
444}
445
446/// MergeAttributes - append attributes from the Old decl to the New one.
447static void MergeAttributes(Decl *New, Decl *Old) {
448 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
449
Chris Lattnerddee4232008-03-03 03:28:21 +0000450 while (attr) {
451 tmp = attr;
452 attr = attr->getNext();
453
454 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000455 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000456 New->addAttr(tmp);
457 } else {
458 tmp->setNext(0);
459 delete(tmp);
460 }
461 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000462
463 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000464}
465
Chris Lattner04421082008-04-08 04:40:51 +0000466/// MergeFunctionDecl - We just parsed a function 'New' from
467/// declarator D which has the same name and scope as a previous
468/// declaration 'Old'. Figure out how to resolve this situation,
469/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000470/// Redeclaration will be set true if this New is a redeclaration OldD.
471///
472/// In C++, New and Old must be declarations that are not
473/// overloaded. Use IsOverload to determine whether New and Old are
474/// overloaded, and to select the Old declaration that New should be
475/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000476FunctionDecl *
477Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000478 assert(!isa<OverloadedFunctionDecl>(OldD) &&
479 "Cannot merge with an overloaded function declaration");
480
Douglas Gregorf0097952008-04-21 02:02:58 +0000481 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000482 // Verify the old decl was also a function.
483 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
484 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000485 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000486 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000487 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000488 return New;
489 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000490
491 // Determine whether the previous declaration was a definition,
492 // implicit declaration, or a declaration.
493 diag::kind PrevDiag;
494 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000495 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000496 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000497 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000498 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000499 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000500
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000501 QualType OldQType = Context.getCanonicalType(Old->getType());
502 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000503
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000504 if (getLangOptions().CPlusPlus) {
505 // (C++98 13.1p2):
506 // Certain function declarations cannot be overloaded:
507 // -- Function declarations that differ only in the return type
508 // cannot be overloaded.
509 QualType OldReturnType
510 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
511 QualType NewReturnType
512 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
513 if (OldReturnType != NewReturnType) {
514 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
515 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000516 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000517 return New;
518 }
519
520 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
521 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
522 if (OldMethod && NewMethod) {
523 // -- Member function declarations with the same name and the
524 // same parameter types cannot be overloaded if any of them
525 // is a static member function declaration.
526 if (OldMethod->isStatic() || NewMethod->isStatic()) {
527 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
528 Diag(Old->getLocation(), PrevDiag);
529 return New;
530 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000531
532 // C++ [class.mem]p1:
533 // [...] A member shall not be declared twice in the
534 // member-specification, except that a nested class or member
535 // class template can be declared and then later defined.
536 if (OldMethod->getLexicalDeclContext() ==
537 NewMethod->getLexicalDeclContext()) {
538 unsigned NewDiag;
539 if (isa<CXXConstructorDecl>(OldMethod))
540 NewDiag = diag::err_constructor_redeclared;
541 else if (isa<CXXDestructorDecl>(NewMethod))
542 NewDiag = diag::err_destructor_redeclared;
543 else if (isa<CXXConversionDecl>(NewMethod))
544 NewDiag = diag::err_conv_function_redeclared;
545 else
546 NewDiag = diag::err_member_redeclared;
547
548 Diag(New->getLocation(), NewDiag);
549 Diag(Old->getLocation(), PrevDiag);
550 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000551 }
552
553 // (C++98 8.3.5p3):
554 // All declarations for a function shall agree exactly in both the
555 // return type and the parameter-type-list.
556 if (OldQType == NewQType) {
557 // We have a redeclaration.
558 MergeAttributes(New, Old);
559 Redeclaration = true;
560 return MergeCXXFunctionDecl(New, Old);
561 }
562
563 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000564 }
Chris Lattner04421082008-04-08 04:40:51 +0000565
566 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000567 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000568 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000569 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000570 MergeAttributes(New, Old);
571 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000572 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000573 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000574
Steve Naroff837618c2008-01-16 15:01:34 +0000575 // A function that has already been declared has been redeclared or defined
576 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000577
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
579 // TODO: This is totally simplistic. It should handle merging functions
580 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000581 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000582 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000583 return New;
584}
585
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000586/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000587static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000588 if (VD->isFileVarDecl())
589 return (!VD->getInit() &&
590 (VD->getStorageClass() == VarDecl::None ||
591 VD->getStorageClass() == VarDecl::Static));
592 return false;
593}
594
595/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
596/// when dealing with C "tentative" external object definitions (C99 6.9.2).
597void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
598 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000599 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000600
Douglas Gregore21b9942009-01-07 16:34:42 +0000601 // FIXME: I don't think this will actually see all of the
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000602 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000603 for (IdentifierResolver::iterator
604 I = IdResolver.begin(VD->getIdentifier(),
605 VD->getDeclContext(), false/*LookInParentCtx*/),
606 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000607 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000608 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
609
Steve Narofff855e6f2008-08-10 15:20:13 +0000610 // Handle the following case:
611 // int a[10];
612 // int a[]; - the code below makes sure we set the correct type.
613 // int a[11]; - this is an error, size isn't 10.
614 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
615 OldDecl->getType()->isConstantArrayType())
616 VD->setType(OldDecl->getType());
617
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000618 // Check for "tentative" definitions. We can't accomplish this in
619 // MergeVarDecl since the initializer hasn't been attached.
620 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
621 continue;
622
623 // Handle __private_extern__ just like extern.
624 if (OldDecl->getStorageClass() != VarDecl::Extern &&
625 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
626 VD->getStorageClass() != VarDecl::Extern &&
627 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000628 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000629 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000630 }
631 }
632 }
633}
634
Reid Spencer5f016e22007-07-11 17:01:13 +0000635/// MergeVarDecl - We just parsed a variable 'New' which has the same name
636/// and scope as a previous declaration 'Old'. Figure out how to resolve this
637/// situation, merging decls or emitting diagnostics as appropriate.
638///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000639/// Tentative definition rules (C99 6.9.2p2) are checked by
640/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
641/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000642///
Steve Naroffe8043c32008-04-01 23:04:06 +0000643VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000644 // Verify the old decl was also a variable.
645 VarDecl *Old = dyn_cast<VarDecl>(OldD);
646 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000647 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000648 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000649 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000650 return New;
651 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000652
653 MergeAttributes(New, Old);
654
Eli Friedman13ca96a2009-01-24 23:49:55 +0000655 // Merge the types
656 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
657 if (MergedT.isNull()) {
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000658 Diag(New->getLocation(), diag::err_redefinition_different_type)
659 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000660 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000661 return New;
662 }
Eli Friedman13ca96a2009-01-24 23:49:55 +0000663 New->setType(MergedT);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000664 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
665 if (New->getStorageClass() == VarDecl::Static &&
666 (Old->getStorageClass() == VarDecl::None ||
667 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000668 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000669 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000670 return New;
671 }
672 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
673 if (New->getStorageClass() != VarDecl::Static &&
674 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000675 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000676 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000677 return New;
678 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000679 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
680 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000681 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000682 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000683 }
684 return New;
685}
686
Chris Lattner04421082008-04-08 04:40:51 +0000687/// CheckParmsForFunctionDef - Check that the parameters of the given
688/// function are appropriate for the definition of a function. This
689/// takes care of any checks that cannot be performed on the
690/// declaration itself, e.g., that the types of each of the function
691/// parameters are complete.
692bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
693 bool HasInvalidParm = false;
694 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
695 ParmVarDecl *Param = FD->getParamDecl(p);
696
697 // C99 6.7.5.3p4: the parameters in a parameter type list in a
698 // function declarator that is part of a function definition of
699 // that function shall not have incomplete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000700 if (!Param->isInvalidDecl() &&
701 DiagnoseIncompleteType(Param->getLocation(), Param->getType(),
702 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattner04421082008-04-08 04:40:51 +0000703 Param->setInvalidDecl();
704 HasInvalidParm = true;
705 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000706
707 // C99 6.9.1p5: If the declarator includes a parameter type list, the
708 // declaration of each parameter shall include an identifier.
709 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
710 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000711 }
712
713 return HasInvalidParm;
714}
715
Reid Spencer5f016e22007-07-11 17:01:13 +0000716/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
717/// no declarator (e.g. "struct foo;") is parsed.
718Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000719 TagDecl *Tag
720 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
721 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
722 if (!Record->getDeclName() && Record->isDefinition() &&
723 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
724 return BuildAnonymousStructOrUnion(S, DS, Record);
725
726 // Microsoft allows unnamed struct/union fields. Don't complain
727 // about them.
728 // FIXME: Should we support Microsoft's extensions in this area?
729 if (Record->getDeclName() && getLangOptions().Microsoft)
730 return Tag;
731 }
732
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000733 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregor21282df2009-01-22 16:23:54 +0000734 // Warn about typedefs of enums without names, since this is an
735 // extension in both Microsoft an GNU.
Douglas Gregor8158f692009-01-17 02:55:50 +0000736 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
737 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor21282df2009-01-22 16:23:54 +0000738 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregoree159c12009-01-13 23:10:51 +0000739 << DS.getSourceRange();
740 return Tag;
741 }
742
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000743 // FIXME: This diagnostic is emitted even when various previous
744 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
745 // DeclSpec has no means of communicating this information, and the
746 // responsible parser functions are quite far apart.
747 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
748 << DS.getSourceRange();
749 return 0;
750 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000751
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000752 return Tag;
753}
754
755/// InjectAnonymousStructOrUnionMembers - Inject the members of the
756/// anonymous struct or union AnonRecord into the owning context Owner
757/// and scope S. This routine will be invoked just after we realize
758/// that an unnamed union or struct is actually an anonymous union or
759/// struct, e.g.,
760///
761/// @code
762/// union {
763/// int i;
764/// float f;
765/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
766/// // f into the surrounding scope.x
767/// @endcode
768///
769/// This routine is recursive, injecting the names of nested anonymous
770/// structs/unions into the owning context and scope as well.
771bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
772 RecordDecl *AnonRecord) {
773 bool Invalid = false;
774 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
775 FEnd = AnonRecord->field_end();
776 F != FEnd; ++F) {
777 if ((*F)->getDeclName()) {
778 Decl *PrevDecl = LookupDecl((*F)->getDeclName(), Decl::IDNS_Ordinary,
Steve Naroff133147d2009-01-28 16:09:22 +0000779 S, Owner, false);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000780 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
781 // C++ [class.union]p2:
782 // The names of the members of an anonymous union shall be
783 // distinct from the names of any other entity in the
784 // scope in which the anonymous union is declared.
785 unsigned diagKind
786 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
787 : diag::err_anonymous_struct_member_redecl;
788 Diag((*F)->getLocation(), diagKind)
789 << (*F)->getDeclName();
790 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
791 Invalid = true;
792 } else {
793 // C++ [class.union]p2:
794 // For the purpose of name lookup, after the anonymous union
795 // definition, the members of the anonymous union are
796 // considered to have been defined in the scope in which the
797 // anonymous union is declared.
Douglas Gregor40f4e692009-01-20 16:54:50 +0000798 Owner->makeDeclVisibleInContext(*F);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000799 S->AddDecl(*F);
800 IdResolver.AddDecl(*F);
801 }
802 } else if (const RecordType *InnerRecordType
803 = (*F)->getType()->getAsRecordType()) {
804 RecordDecl *InnerRecord = InnerRecordType->getDecl();
805 if (InnerRecord->isAnonymousStructOrUnion())
806 Invalid = Invalid ||
807 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
808 }
809 }
810
811 return Invalid;
812}
813
814/// ActOnAnonymousStructOrUnion - Handle the declaration of an
815/// anonymous structure or union. Anonymous unions are a C++ feature
816/// (C++ [class.union]) and a GNU C extension; anonymous structures
817/// are a GNU C and GNU C++ extension.
818Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
819 RecordDecl *Record) {
820 DeclContext *Owner = Record->getDeclContext();
821
822 // Diagnose whether this anonymous struct/union is an extension.
823 if (Record->isUnion() && !getLangOptions().CPlusPlus)
824 Diag(Record->getLocation(), diag::ext_anonymous_union);
825 else if (!Record->isUnion())
826 Diag(Record->getLocation(), diag::ext_anonymous_struct);
827
828 // C and C++ require different kinds of checks for anonymous
829 // structs/unions.
830 bool Invalid = false;
831 if (getLangOptions().CPlusPlus) {
832 const char* PrevSpec = 0;
833 // C++ [class.union]p3:
834 // Anonymous unions declared in a named namespace or in the
835 // global namespace shall be declared static.
836 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
837 (isa<TranslationUnitDecl>(Owner) ||
838 (isa<NamespaceDecl>(Owner) &&
839 cast<NamespaceDecl>(Owner)->getDeclName()))) {
840 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
841 Invalid = true;
842
843 // Recover by adding 'static'.
844 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
845 }
846 // C++ [class.union]p3:
847 // A storage class is not allowed in a declaration of an
848 // anonymous union in a class scope.
849 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
850 isa<RecordDecl>(Owner)) {
851 Diag(DS.getStorageClassSpecLoc(),
852 diag::err_anonymous_union_with_storage_spec);
853 Invalid = true;
854
855 // Recover by removing the storage specifier.
856 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
857 PrevSpec);
858 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000859
860 // C++ [class.union]p2:
861 // The member-specification of an anonymous union shall only
862 // define non-static data members. [Note: nested types and
863 // functions cannot be declared within an anonymous union. ]
864 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
865 MemEnd = Record->decls_end();
866 Mem != MemEnd; ++Mem) {
867 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
868 // C++ [class.union]p3:
869 // An anonymous union shall not have private or protected
870 // members (clause 11).
871 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
872 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
873 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
874 Invalid = true;
875 }
876 } else if ((*Mem)->isImplicit()) {
877 // Any implicit members are fine.
878 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
879 if (!MemRecord->isAnonymousStructOrUnion() &&
880 MemRecord->getDeclName()) {
881 // This is a nested type declaration.
882 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
883 << (int)Record->isUnion();
884 Invalid = true;
885 }
886 } else {
887 // We have something that isn't a non-static data
888 // member. Complain about it.
889 unsigned DK = diag::err_anonymous_record_bad_member;
890 if (isa<TypeDecl>(*Mem))
891 DK = diag::err_anonymous_record_with_type;
892 else if (isa<FunctionDecl>(*Mem))
893 DK = diag::err_anonymous_record_with_function;
894 else if (isa<VarDecl>(*Mem))
895 DK = diag::err_anonymous_record_with_static;
896 Diag((*Mem)->getLocation(), DK)
897 << (int)Record->isUnion();
898 Invalid = true;
899 }
900 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000901 } else {
902 // FIXME: Check GNU C semantics
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000903 if (Record->isUnion() && !Owner->isRecord()) {
904 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
905 << (int)getLangOptions().CPlusPlus;
906 Invalid = true;
907 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000908 }
909
910 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000911 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
912 << (int)getLangOptions().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000913 Invalid = true;
914 }
915
916 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000917 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000918 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
919 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
920 /*IdentifierInfo=*/0,
921 Context.getTypeDeclType(Record),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000922 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000923 Anon->setAccess(AS_public);
924 if (getLangOptions().CPlusPlus)
925 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000926 } else {
927 VarDecl::StorageClass SC;
928 switch (DS.getStorageClassSpec()) {
929 default: assert(0 && "Unknown storage class!");
930 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
931 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
932 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
933 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
934 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
935 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
936 case DeclSpec::SCS_mutable:
937 // mutable can only appear on non-static class members, so it's always
938 // an error here
939 Diag(Record->getLocation(), diag::err_mutable_nonmember);
940 Invalid = true;
941 SC = VarDecl::None;
942 break;
943 }
944
945 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
946 /*IdentifierInfo=*/0,
947 Context.getTypeDeclType(Record),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000948 SC, DS.getSourceRange().getBegin());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000949 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000950 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000951
952 // Add the anonymous struct/union object to the current
953 // context. We'll be referencing this object when we refer to one of
954 // its members.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000955 Owner->addDecl(Anon);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000956
957 // Inject the members of the anonymous struct/union into the owning
958 // context and into the identifier resolver chain for name lookup
959 // purposes.
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000960 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
961 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000962
963 // Mark this as an anonymous struct/union type. Note that we do not
964 // do this until after we have already checked and injected the
965 // members of this anonymous struct/union type, because otherwise
966 // the members could be injected twice: once by DeclContext when it
967 // builds its lookup table, and once by
968 // InjectAnonymousStructOrUnionMembers.
969 Record->setAnonymousStructOrUnion(true);
970
971 if (Invalid)
972 Anon->setInvalidDecl();
973
974 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +0000975}
976
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000977bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
978 bool DirectInit) {
Steve Narofff0090632007-09-02 02:04:30 +0000979 // Get the type before calling CheckSingleAssignmentConstraints(), since
980 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000981 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +0000982
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000983 if (getLangOptions().CPlusPlus) {
984 // FIXME: I dislike this error message. A lot.
985 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
986 return Diag(Init->getSourceRange().getBegin(),
987 diag::err_typecheck_convert_incompatible)
988 << DeclType << Init->getType() << "initializing"
989 << Init->getSourceRange();
990
991 return false;
992 }
Douglas Gregor45920e82008-12-19 17:40:08 +0000993
Chris Lattner5cf216b2008-01-04 18:04:52 +0000994 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
995 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
996 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000997}
998
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000999bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001000 const ArrayType *AT = Context.getAsArrayType(DeclT);
1001
1002 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001003 // C99 6.7.8p14. We have an array of character type with unknown size
1004 // being initialized to a string literal.
1005 llvm::APSInt ConstVal(32);
1006 ConstVal = strLiteral->getByteLength() + 1;
1007 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +00001008 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001009 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001010 } else {
1011 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001012 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001013 // FIXME: Avoid truncation for 64-bit length strings.
1014 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001015 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001016 diag::warn_initializer_string_for_char_array_too_long)
1017 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001018 }
1019 // Set type from "char *" to "constant array of char".
1020 strLiteral->setType(DeclT);
1021 // For now, we always return false (meaning success).
1022 return false;
1023}
1024
1025StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001026 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +00001027 if (AT && AT->getElementType()->isCharType()) {
Anders Carlsson91b9f202009-01-24 17:47:50 +00001028 return dyn_cast<StringLiteral>(Init->IgnoreParens());
Steve Naroffa9960332008-01-25 00:51:06 +00001029 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001030 return 0;
1031}
1032
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001033bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1034 SourceLocation InitLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001035 DeclarationName InitEntity,
1036 bool DirectInit) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +00001037 if (DeclType->isDependentType() || Init->isTypeDependent())
1038 return false;
1039
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001040 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +00001041 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001042 // (8.3.2), shall be initialized by an object, or function, of
1043 // type T or by an object that can be converted into a T.
1044 if (DeclType->isReferenceType())
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001045 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001046
Steve Naroffca107302008-01-21 23:53:58 +00001047 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1048 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001049 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001050 return Diag(InitLoc, diag::err_variable_object_no_init)
1051 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +00001052
Steve Naroff2fdc3742007-12-10 22:44:33 +00001053 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1054 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001055 // FIXME: Handle wide strings
1056 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1057 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +00001058
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001059 // C++ [dcl.init]p14:
1060 // -- If the destination type is a (possibly cv-qualified) class
1061 // type:
1062 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1063 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1064 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1065
1066 // -- If the initialization is direct-initialization, or if it is
1067 // copy-initialization where the cv-unqualified version of the
1068 // source type is the same class as, or a derived class of, the
1069 // class of the destination, constructors are considered.
1070 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1071 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1072 CXXConstructorDecl *Constructor
1073 = PerformInitializationByConstructor(DeclType, &Init, 1,
1074 InitLoc, Init->getSourceRange(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001075 InitEntity,
1076 DirectInit? IK_Direct : IK_Copy);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001077 return Constructor == 0;
1078 }
1079
1080 // -- Otherwise (i.e., for the remaining copy-initialization
1081 // cases), user-defined conversion sequences that can
1082 // convert from the source type to the destination type or
1083 // (when a conversion function is used) to a derived class
1084 // thereof are enumerated as described in 13.3.1.4, and the
1085 // best one is chosen through overload resolution
1086 // (13.3). If the conversion cannot be done or is
1087 // ambiguous, the initialization is ill-formed. The
1088 // function selected is called with the initializer
1089 // expression as its argument; if the function is a
1090 // constructor, the call initializes a temporary of the
1091 // destination type.
1092 // FIXME: We're pretending to do copy elision here; return to
1093 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +00001094 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001095 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001096
Douglas Gregor61366e92008-12-24 00:01:03 +00001097 if (InitEntity)
1098 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1099 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1100 << Init->getType() << Init->getSourceRange();
1101 else
1102 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1103 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1104 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001105 }
1106
Steve Naroff1ac6fdd2008-09-29 20:07:05 +00001107 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +00001108 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001109 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1110 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +00001111
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001112 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregor64bffa92008-11-05 16:20:31 +00001113 } else if (getLangOptions().CPlusPlus) {
1114 // C++ [dcl.init]p14:
1115 // [...] If the class is an aggregate (8.5.1), and the initializer
1116 // is a brace-enclosed list, see 8.5.1.
1117 //
1118 // Note: 8.5.1 is handled below; here, we diagnose the case where
1119 // we have an initializer list and a destination type that is not
1120 // an aggregate.
1121 // FIXME: In C++0x, this is yet another form of initialization.
1122 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1123 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1124 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001125 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00001126 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +00001127 }
Steve Naroff2fdc3742007-12-10 22:44:33 +00001128 }
Eli Friedmane6f058f2008-06-06 19:40:52 +00001129
Steve Naroff0cca7492008-05-01 22:18:59 +00001130 InitListChecker CheckInitList(this, InitList, DeclType);
1131 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +00001132}
1133
Douglas Gregor10bd3682008-11-17 22:58:34 +00001134/// GetNameForDeclarator - Determine the full declaration name for the
1135/// given Declarator.
1136DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1137 switch (D.getKind()) {
1138 case Declarator::DK_Abstract:
1139 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1140 return DeclarationName();
1141
1142 case Declarator::DK_Normal:
1143 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1144 return DeclarationName(D.getIdentifier());
1145
1146 case Declarator::DK_Constructor: {
1147 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1148 Ty = Context.getCanonicalType(Ty);
1149 return Context.DeclarationNames.getCXXConstructorName(Ty);
1150 }
1151
1152 case Declarator::DK_Destructor: {
1153 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1154 Ty = Context.getCanonicalType(Ty);
1155 return Context.DeclarationNames.getCXXDestructorName(Ty);
1156 }
1157
1158 case Declarator::DK_Conversion: {
1159 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1160 Ty = Context.getCanonicalType(Ty);
1161 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1162 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001163
1164 case Declarator::DK_Operator:
1165 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1166 return Context.DeclarationNames.getCXXOperatorName(
1167 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001168 }
1169
1170 assert(false && "Unknown name kind");
1171 return DeclarationName();
1172}
1173
Douglas Gregor584049d2008-12-15 23:53:10 +00001174/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1175/// functions Declaration and Definition are "nearly" matching. This
1176/// heuristic is used to improve diagnostics in the case where an
1177/// out-of-line member function definition doesn't match any
1178/// declaration within the class.
1179static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1180 FunctionDecl *Declaration,
1181 FunctionDecl *Definition) {
1182 if (Declaration->param_size() != Definition->param_size())
1183 return false;
1184 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1185 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1186 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1187
1188 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1189 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1190 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1191 return false;
1192 }
1193
1194 return true;
1195}
1196
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001197Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001198Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1199 bool IsFunctionDefinition) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001200 NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001201 DeclarationName Name = GetNameForDeclarator(D);
1202
Chris Lattnere80a59c2007-07-25 00:24:17 +00001203 // All of these full declarators require an identifier. If it doesn't have
1204 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001205 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001206 if (!D.getInvalidType()) // Reject this if we think it is valid.
1207 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001208 diag::err_declarator_need_ident)
1209 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001210 return 0;
1211 }
1212
Chris Lattner31e05722007-08-26 06:24:45 +00001213 // The scope passed in may not be a decl scope. Zip up the scope tree until
1214 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001215 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1216 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001217 S = S->getParent();
1218
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001219 DeclContext *DC;
1220 Decl *PrevDecl;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001221 NamedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001222 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001223
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001224 // See if this is a redefinition of a variable in the same scope.
1225 if (!D.getCXXScopeSpec().isSet()) {
1226 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +00001227 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001228 } else { // Something like "int foo::x;"
1229 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001230 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001231
1232 // C++ 7.3.1.2p2:
1233 // Members (including explicit specializations of templates) of a named
1234 // namespace can also be defined outside that namespace by explicit
1235 // qualification of the name being defined, provided that the entity being
1236 // defined was already declared in the namespace and the definition appears
1237 // after the point of declaration in a namespace that encloses the
1238 // declarations namespace.
1239 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001240 // Note that we only check the context at this point. We don't yet
1241 // have enough information to make sure that PrevDecl is actually
1242 // the declaration we want to match. For example, given:
1243 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001244 // class X {
1245 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001246 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001247 // };
1248 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001249 // void X::f(int) { } // ill-formed
1250 //
1251 // In this case, PrevDecl will point to the overload set
1252 // containing the two f's declared in X, but neither of them
1253 // matches.
1254 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001255 // The qualifying scope doesn't enclose the original declaration.
1256 // Emit diagnostic based on current scope.
1257 SourceLocation L = D.getIdentifierLoc();
1258 SourceRange R = D.getCXXScopeSpec().getRange();
1259 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001260 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001261 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001262 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001263 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001264 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001265 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001266 }
1267 }
1268
Douglas Gregorf57172b2008-12-08 18:40:42 +00001269 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001270 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001271 InvalidDecl = InvalidDecl
1272 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001273 // Just pretend that we didn't see the previous declaration.
1274 PrevDecl = 0;
1275 }
1276
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001277 // In C++, the previous declaration we find might be a tag type
1278 // (class or enum). In this case, the new declaration will hide the
1279 // tag type.
1280 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1281 PrevDecl = 0;
1282
Chris Lattner41af0932007-11-14 06:34:38 +00001283 QualType R = GetTypeForDeclarator(D, S);
1284 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1285
Reid Spencer5f016e22007-07-11 17:01:13 +00001286 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001287 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1288 InvalidDecl);
Chris Lattner41af0932007-11-14 06:34:38 +00001289 } else if (R.getTypePtr()->isFunctionType()) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001290 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1291 IsFunctionDefinition, InvalidDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001292 } else {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001293 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1294 InvalidDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001296
1297 if (New == 0)
1298 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001299
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001300 // Set the lexical context. If the declarator has a C++ scope specifier, the
1301 // lexical context will be different from the semantic context.
1302 New->setLexicalDeclContext(CurContext);
1303
Reid Spencer5f016e22007-07-11 17:01:13 +00001304 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001305 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001306 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001307 // If any semantic error occurred, mark the decl as invalid.
1308 if (D.getInvalidType() || InvalidDecl)
1309 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001310
1311 return New;
1312}
1313
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001314NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001315Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001316 QualType R, Decl* LastDeclarator,
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001317 Decl* PrevDecl, bool& InvalidDecl) {
1318 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1319 if (D.getCXXScopeSpec().isSet()) {
1320 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1321 << D.getCXXScopeSpec().getRange();
1322 InvalidDecl = true;
1323 // Pretend we didn't see the scope specifier.
1324 DC = 0;
1325 }
1326
1327 // Check that there are no default arguments (C++ only).
1328 if (getLangOptions().CPlusPlus)
1329 CheckExtraCXXDefaultArguments(D);
1330
1331 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1332 if (!NewTD) return 0;
1333
1334 // Handle attributes prior to checking for duplicates in MergeVarDecl
1335 ProcessDeclAttributes(NewTD, D);
1336 // Merge the decl with the existing one if appropriate. If the decl is
1337 // in an outer scope, it isn't the same thing.
1338 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1339 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1340 if (NewTD == 0) return 0;
1341 }
1342
1343 if (S->getFnParent() == 0) {
1344 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1345 // then it shall have block scope.
1346 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1347 if (NewTD->getUnderlyingType()->isVariableArrayType())
1348 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1349 else
1350 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1351
1352 InvalidDecl = true;
1353 }
1354 }
1355 return NewTD;
1356}
1357
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001358NamedDecl*
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001359Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001360 QualType R, Decl* LastDeclarator,
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001361 Decl* PrevDecl, bool& InvalidDecl) {
1362 DeclarationName Name = GetNameForDeclarator(D);
1363
1364 // Check that there are no default arguments (C++ only).
1365 if (getLangOptions().CPlusPlus)
1366 CheckExtraCXXDefaultArguments(D);
1367
1368 if (R.getTypePtr()->isObjCInterfaceType()) {
1369 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1370 << D.getIdentifier();
1371 InvalidDecl = true;
1372 }
1373
1374 VarDecl *NewVD;
1375 VarDecl::StorageClass SC;
1376 switch (D.getDeclSpec().getStorageClassSpec()) {
1377 default: assert(0 && "Unknown storage class!");
1378 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1379 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1380 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1381 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1382 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1383 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1384 case DeclSpec::SCS_mutable:
1385 // mutable can only appear on non-static class members, so it's always
1386 // an error here
1387 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1388 InvalidDecl = true;
1389 SC = VarDecl::None;
1390 break;
1391 }
1392
1393 IdentifierInfo *II = Name.getAsIdentifierInfo();
1394 if (!II) {
1395 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1396 << Name.getAsString();
1397 return 0;
1398 }
1399
1400 if (DC->isRecord()) {
1401 // This is a static data member for a C++ class.
1402 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1403 D.getIdentifierLoc(), II,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001404 R);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001405 } else {
1406 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1407 if (S->getFnParent() == 0) {
1408 // C99 6.9p2: The storage-class specifiers auto and register shall not
1409 // appear in the declaration specifiers in an external declaration.
1410 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1411 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1412 InvalidDecl = true;
1413 }
1414 }
1415 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001416 II, R, SC,
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001417 // FIXME: Move to DeclGroup...
1418 D.getDeclSpec().getSourceRange().getBegin());
1419 NewVD->setThreadSpecified(ThreadSpecified);
1420 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001421 NewVD->setNextDeclarator(LastDeclarator);
1422
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001423 // Handle attributes prior to checking for duplicates in MergeVarDecl
1424 ProcessDeclAttributes(NewVD, D);
1425
1426 // Handle GNU asm-label extension (encoded as an attribute).
1427 if (Expr *E = (Expr*) D.getAsmLabel()) {
1428 // The parser guarantees this is a string.
1429 StringLiteral *SE = cast<StringLiteral>(E);
1430 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1431 SE->getByteLength())));
1432 }
1433
1434 // Emit an error if an address space was applied to decl with local storage.
1435 // This includes arrays of objects with address space qualifiers, but not
1436 // automatic variables that point to other address spaces.
1437 // ISO/IEC TR 18037 S5.1.2
1438 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1439 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1440 InvalidDecl = true;
1441 }
1442 // Merge the decl with the existing one if appropriate. If the decl is
1443 // in an outer scope, it isn't the same thing.
1444 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1445 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1446 // The user tried to define a non-static data member
1447 // out-of-line (C++ [dcl.meaning]p1).
1448 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1449 << D.getCXXScopeSpec().getRange();
1450 NewVD->Destroy(Context);
1451 return 0;
1452 }
1453
1454 NewVD = MergeVarDecl(NewVD, PrevDecl);
1455 if (NewVD == 0) return 0;
1456
1457 if (D.getCXXScopeSpec().isSet()) {
1458 // No previous declaration in the qualifying scope.
1459 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1460 << Name << D.getCXXScopeSpec().getRange();
1461 InvalidDecl = true;
1462 }
1463 }
1464 return NewVD;
1465}
1466
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001467NamedDecl*
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001468Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001469 QualType R, Decl *LastDeclarator,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001470 Decl* PrevDecl, bool IsFunctionDefinition,
1471 bool& InvalidDecl) {
1472 assert(R.getTypePtr()->isFunctionType());
1473
1474 DeclarationName Name = GetNameForDeclarator(D);
1475 FunctionDecl::StorageClass SC = FunctionDecl::None;
1476 switch (D.getDeclSpec().getStorageClassSpec()) {
1477 default: assert(0 && "Unknown storage class!");
1478 case DeclSpec::SCS_auto:
1479 case DeclSpec::SCS_register:
1480 case DeclSpec::SCS_mutable:
1481 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1482 InvalidDecl = true;
1483 break;
1484 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1485 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1486 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
1487 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1488 }
1489
1490 bool isInline = D.getDeclSpec().isInlineSpecified();
1491 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1492 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1493
1494 FunctionDecl *NewFD;
1495 if (D.getKind() == Declarator::DK_Constructor) {
1496 // This is a C++ constructor declaration.
1497 assert(DC->isRecord() &&
1498 "Constructors can only be declared in a member context");
1499
1500 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1501
1502 // Create the new declaration
1503 NewFD = CXXConstructorDecl::Create(Context,
1504 cast<CXXRecordDecl>(DC),
1505 D.getIdentifierLoc(), Name, R,
1506 isExplicit, isInline,
1507 /*isImplicitlyDeclared=*/false);
1508
1509 if (InvalidDecl)
1510 NewFD->setInvalidDecl();
1511 } else if (D.getKind() == Declarator::DK_Destructor) {
1512 // This is a C++ destructor declaration.
1513 if (DC->isRecord()) {
1514 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1515
1516 NewFD = CXXDestructorDecl::Create(Context,
1517 cast<CXXRecordDecl>(DC),
1518 D.getIdentifierLoc(), Name, R,
1519 isInline,
1520 /*isImplicitlyDeclared=*/false);
1521
1522 if (InvalidDecl)
1523 NewFD->setInvalidDecl();
1524 } else {
1525 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1526
1527 // Create a FunctionDecl to satisfy the function definition parsing
1528 // code path.
1529 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001530 Name, R, SC, isInline,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001531 // FIXME: Move to DeclGroup...
1532 D.getDeclSpec().getSourceRange().getBegin());
1533 InvalidDecl = true;
1534 NewFD->setInvalidDecl();
1535 }
1536 } else if (D.getKind() == Declarator::DK_Conversion) {
1537 if (!DC->isRecord()) {
1538 Diag(D.getIdentifierLoc(),
1539 diag::err_conv_function_not_member);
1540 return 0;
1541 } else {
1542 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1543
1544 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1545 D.getIdentifierLoc(), Name, R,
1546 isInline, isExplicit);
1547
1548 if (InvalidDecl)
1549 NewFD->setInvalidDecl();
1550 }
1551 } else if (DC->isRecord()) {
1552 // This is a C++ method declaration.
1553 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1554 D.getIdentifierLoc(), Name, R,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001555 (SC == FunctionDecl::Static), isInline);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001556 } else {
1557 NewFD = FunctionDecl::Create(Context, DC,
1558 D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001559 Name, R, SC, isInline,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001560 // FIXME: Move to DeclGroup...
1561 D.getDeclSpec().getSourceRange().getBegin());
1562 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001563 NewFD->setNextDeclarator(LastDeclarator);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001564
1565 // Set the lexical context. If the declarator has a C++
1566 // scope specifier, the lexical context will be different
1567 // from the semantic context.
1568 NewFD->setLexicalDeclContext(CurContext);
1569
1570 // Handle GNU asm-label extension (encoded as an attribute).
1571 if (Expr *E = (Expr*) D.getAsmLabel()) {
1572 // The parser guarantees this is a string.
1573 StringLiteral *SE = cast<StringLiteral>(E);
1574 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1575 SE->getByteLength())));
1576 }
1577
1578 // Copy the parameter declarations from the declarator D to
1579 // the function declaration NewFD, if they are available.
1580 if (D.getNumTypeObjects() > 0) {
1581 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1582
1583 // Create Decl objects for each parameter, adding them to the
1584 // FunctionDecl.
1585 llvm::SmallVector<ParmVarDecl*, 16> Params;
1586
1587 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1588 // function that takes no arguments, not a function that takes a
1589 // single void argument.
1590 // We let through "const void" here because Sema::GetTypeForDeclarator
1591 // already checks for that case.
1592 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1593 FTI.ArgInfo[0].Param &&
1594 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1595 // empty arg list, don't push any params.
1596 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1597
1598 // In C++, the empty parameter-type-list must be spelled "void"; a
1599 // typedef of void is not permitted.
1600 if (getLangOptions().CPlusPlus &&
1601 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1602 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1603 }
1604 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1605 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1606 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1607 }
1608
1609 NewFD->setParams(Context, &Params[0], Params.size());
1610 } else if (R->getAsTypedefType()) {
1611 // When we're declaring a function with a typedef, as in the
1612 // following example, we'll need to synthesize (unnamed)
1613 // parameters for use in the declaration.
1614 //
1615 // @code
1616 // typedef void fn(int);
1617 // fn f;
1618 // @endcode
1619 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1620 if (!FT) {
1621 // This is a typedef of a function with no prototype, so we
1622 // don't need to do anything.
1623 } else if ((FT->getNumArgs() == 0) ||
1624 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1625 FT->getArgType(0)->isVoidType())) {
1626 // This is a zero-argument function. We don't need to do anything.
1627 } else {
1628 // Synthesize a parameter for each argument type.
1629 llvm::SmallVector<ParmVarDecl*, 16> Params;
1630 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1631 ArgType != FT->arg_type_end(); ++ArgType) {
1632 Params.push_back(ParmVarDecl::Create(Context, DC,
1633 SourceLocation(), 0,
1634 *ArgType, VarDecl::None,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001635 0));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001636 }
1637
1638 NewFD->setParams(Context, &Params[0], Params.size());
1639 }
1640 }
1641
1642 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1643 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1644 else if (isa<CXXDestructorDecl>(NewFD)) {
1645 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1646 Record->setUserDeclaredDestructor(true);
1647 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1648 // user-defined destructor.
1649 Record->setPOD(false);
1650 } else if (CXXConversionDecl *Conversion =
1651 dyn_cast<CXXConversionDecl>(NewFD))
1652 ActOnConversionDeclarator(Conversion);
1653
1654 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1655 if (NewFD->isOverloadedOperator() &&
1656 CheckOverloadedOperatorDeclaration(NewFD))
1657 NewFD->setInvalidDecl();
1658
1659 // Merge the decl with the existing one if appropriate. Since C functions
1660 // are in a flat namespace, make sure we consider decls in outer scopes.
1661 if (PrevDecl &&
1662 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1663 bool Redeclaration = false;
1664
1665 // If C++, determine whether NewFD is an overload of PrevDecl or
1666 // a declaration that requires merging. If it's an overload,
1667 // there's no more work to do here; we'll just add the new
1668 // function to the scope.
1669 OverloadedFunctionDecl::function_iterator MatchedDecl;
1670 if (!getLangOptions().CPlusPlus ||
1671 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1672 Decl *OldDecl = PrevDecl;
1673
1674 // If PrevDecl was an overloaded function, extract the
1675 // FunctionDecl that matched.
1676 if (isa<OverloadedFunctionDecl>(PrevDecl))
1677 OldDecl = *MatchedDecl;
1678
1679 // NewFD and PrevDecl represent declarations that need to be
1680 // merged.
1681 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1682
1683 if (NewFD == 0) return 0;
1684 if (Redeclaration) {
1685 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1686
1687 // An out-of-line member function declaration must also be a
1688 // definition (C++ [dcl.meaning]p1).
1689 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1690 !InvalidDecl) {
1691 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1692 << D.getCXXScopeSpec().getRange();
1693 NewFD->setInvalidDecl();
1694 }
1695 }
1696 }
1697
1698 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1699 // The user tried to provide an out-of-line definition for a
1700 // member function, but there was no such member function
1701 // declared (C++ [class.mfct]p2). For example:
1702 //
1703 // class X {
1704 // void f() const;
1705 // };
1706 //
1707 // void X::f() { } // ill-formed
1708 //
1709 // Complain about this problem, and attempt to suggest close
1710 // matches (e.g., those that differ only in cv-qualifiers and
1711 // whether the parameter types are references).
1712 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1713 << cast<CXXRecordDecl>(DC)->getDeclName()
1714 << D.getCXXScopeSpec().getRange();
1715 InvalidDecl = true;
1716
1717 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1718 if (!PrevDecl) {
1719 // Nothing to suggest.
1720 } else if (OverloadedFunctionDecl *Ovl
1721 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1722 for (OverloadedFunctionDecl::function_iterator
1723 Func = Ovl->function_begin(),
1724 FuncEnd = Ovl->function_end();
1725 Func != FuncEnd; ++Func) {
1726 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1727 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1728
1729 }
1730 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1731 // Suggest this no matter how mismatched it is; it's the only
1732 // thing we have.
1733 unsigned diag;
1734 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1735 diag = diag::note_member_def_close_match;
1736 else if (Method->getBody())
1737 diag = diag::note_previous_definition;
1738 else
1739 diag = diag::note_previous_declaration;
1740 Diag(Method->getLocation(), diag);
1741 }
1742
1743 PrevDecl = 0;
1744 }
1745 }
1746 // Handle attributes. We need to have merged decls when handling attributes
1747 // (for example to check for conflicts, etc).
1748 ProcessDeclAttributes(NewFD, D);
1749
1750 if (getLangOptions().CPlusPlus) {
1751 // In C++, check default arguments now that we have merged decls.
1752 CheckCXXDefaultArguments(NewFD);
1753
1754 // An out-of-line member function declaration must also be a
1755 // definition (C++ [dcl.meaning]p1).
1756 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1757 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1758 << D.getCXXScopeSpec().getRange();
1759 InvalidDecl = true;
1760 }
1761 }
1762 return NewFD;
1763}
1764
Steve Naroff6594a702008-10-27 11:34:16 +00001765void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001766 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1767 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001768}
1769
Eli Friedmanc594b322008-05-20 13:48:25 +00001770bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1771 switch (Init->getStmtClass()) {
1772 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001773 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001774 return true;
1775 case Expr::ParenExprClass: {
1776 const ParenExpr* PE = cast<ParenExpr>(Init);
1777 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1778 }
1779 case Expr::CompoundLiteralExprClass:
1780 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor1a49af92009-01-06 05:10:23 +00001781 case Expr::DeclRefExprClass:
1782 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001783 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001784 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1785 if (VD->hasGlobalStorage())
1786 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001787 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001788 return true;
1789 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001790 if (isa<FunctionDecl>(D))
1791 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001792 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001793 return true;
1794 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001795 case Expr::MemberExprClass: {
1796 const MemberExpr *M = cast<MemberExpr>(Init);
1797 if (M->isArrow())
1798 return CheckAddressConstantExpression(M->getBase());
1799 return CheckAddressConstantExpressionLValue(M->getBase());
1800 }
1801 case Expr::ArraySubscriptExprClass: {
1802 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1803 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1804 return CheckAddressConstantExpression(ASE->getBase()) ||
1805 CheckArithmeticConstantExpression(ASE->getIdx());
1806 }
1807 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001808 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001809 return false;
1810 case Expr::UnaryOperatorClass: {
1811 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1812
1813 // C99 6.6p9
1814 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001815 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001816
Steve Naroff6594a702008-10-27 11:34:16 +00001817 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001818 return true;
1819 }
1820 }
1821}
1822
1823bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1824 switch (Init->getStmtClass()) {
1825 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001826 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001827 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001828 case Expr::ParenExprClass:
1829 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001830 case Expr::StringLiteralClass:
1831 case Expr::ObjCStringLiteralClass:
1832 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001833 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001834 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001835 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1836 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1837 Builtin::BI__builtin___CFStringMakeConstantString)
1838 return false;
1839
Steve Naroff6594a702008-10-27 11:34:16 +00001840 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001841 return true;
1842
Eli Friedmanc594b322008-05-20 13:48:25 +00001843 case Expr::UnaryOperatorClass: {
1844 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1845
1846 // C99 6.6p9
1847 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1848 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1849
1850 if (Exp->getOpcode() == UnaryOperator::Extension)
1851 return CheckAddressConstantExpression(Exp->getSubExpr());
1852
Steve Naroff6594a702008-10-27 11:34:16 +00001853 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001854 return true;
1855 }
1856 case Expr::BinaryOperatorClass: {
1857 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1858 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1859
1860 Expr *PExp = Exp->getLHS();
1861 Expr *IExp = Exp->getRHS();
1862 if (IExp->getType()->isPointerType())
1863 std::swap(PExp, IExp);
1864
1865 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1866 return CheckAddressConstantExpression(PExp) ||
1867 CheckArithmeticConstantExpression(IExp);
1868 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001869 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001870 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001871 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001872 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1873 // Check for implicit promotion
1874 if (SubExpr->getType()->isFunctionType() ||
1875 SubExpr->getType()->isArrayType())
1876 return CheckAddressConstantExpressionLValue(SubExpr);
1877 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001878
1879 // Check for pointer->pointer cast
1880 if (SubExpr->getType()->isPointerType())
1881 return CheckAddressConstantExpression(SubExpr);
1882
Eli Friedmanc3f07642008-08-25 20:46:57 +00001883 if (SubExpr->getType()->isIntegralType()) {
1884 // Check for the special-case of a pointer->int->pointer cast;
1885 // this isn't standard, but some code requires it. See
1886 // PR2720 for an example.
1887 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1888 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1889 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1890 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1891 if (IntWidth >= PointerWidth) {
1892 return CheckAddressConstantExpression(SubCast->getSubExpr());
1893 }
1894 }
1895 }
1896 }
1897 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001898 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001899 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001900
Steve Naroff6594a702008-10-27 11:34:16 +00001901 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001902 return true;
1903 }
1904 case Expr::ConditionalOperatorClass: {
1905 // FIXME: Should we pedwarn here?
1906 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1907 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001908 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001909 return true;
1910 }
1911 if (CheckArithmeticConstantExpression(Exp->getCond()))
1912 return true;
1913 if (Exp->getLHS() &&
1914 CheckAddressConstantExpression(Exp->getLHS()))
1915 return true;
1916 return CheckAddressConstantExpression(Exp->getRHS());
1917 }
1918 case Expr::AddrLabelExprClass:
1919 return false;
1920 }
1921}
1922
Eli Friedman4caf0552008-06-09 05:05:07 +00001923static const Expr* FindExpressionBaseAddress(const Expr* E);
1924
1925static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1926 switch (E->getStmtClass()) {
1927 default:
1928 return E;
1929 case Expr::ParenExprClass: {
1930 const ParenExpr* PE = cast<ParenExpr>(E);
1931 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1932 }
1933 case Expr::MemberExprClass: {
1934 const MemberExpr *M = cast<MemberExpr>(E);
1935 if (M->isArrow())
1936 return FindExpressionBaseAddress(M->getBase());
1937 return FindExpressionBaseAddressLValue(M->getBase());
1938 }
1939 case Expr::ArraySubscriptExprClass: {
1940 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1941 return FindExpressionBaseAddress(ASE->getBase());
1942 }
1943 case Expr::UnaryOperatorClass: {
1944 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1945
1946 if (Exp->getOpcode() == UnaryOperator::Deref)
1947 return FindExpressionBaseAddress(Exp->getSubExpr());
1948
1949 return E;
1950 }
1951 }
1952}
1953
1954static const Expr* FindExpressionBaseAddress(const Expr* E) {
1955 switch (E->getStmtClass()) {
1956 default:
1957 return E;
1958 case Expr::ParenExprClass: {
1959 const ParenExpr* PE = cast<ParenExpr>(E);
1960 return FindExpressionBaseAddress(PE->getSubExpr());
1961 }
1962 case Expr::UnaryOperatorClass: {
1963 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1964
1965 // C99 6.6p9
1966 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1967 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1968
1969 if (Exp->getOpcode() == UnaryOperator::Extension)
1970 return FindExpressionBaseAddress(Exp->getSubExpr());
1971
1972 return E;
1973 }
1974 case Expr::BinaryOperatorClass: {
1975 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1976
1977 Expr *PExp = Exp->getLHS();
1978 Expr *IExp = Exp->getRHS();
1979 if (IExp->getType()->isPointerType())
1980 std::swap(PExp, IExp);
1981
1982 return FindExpressionBaseAddress(PExp);
1983 }
1984 case Expr::ImplicitCastExprClass: {
1985 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1986
1987 // Check for implicit promotion
1988 if (SubExpr->getType()->isFunctionType() ||
1989 SubExpr->getType()->isArrayType())
1990 return FindExpressionBaseAddressLValue(SubExpr);
1991
1992 // Check for pointer->pointer cast
1993 if (SubExpr->getType()->isPointerType())
1994 return FindExpressionBaseAddress(SubExpr);
1995
1996 // We assume that we have an arithmetic expression here;
1997 // if we don't, we'll figure it out later
1998 return 0;
1999 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002000 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00002001 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2002
2003 // Check for pointer->pointer cast
2004 if (SubExpr->getType()->isPointerType())
2005 return FindExpressionBaseAddress(SubExpr);
2006
2007 // We assume that we have an arithmetic expression here;
2008 // if we don't, we'll figure it out later
2009 return 0;
2010 }
2011 }
2012}
2013
Anders Carlsson51fe9962008-11-22 21:04:56 +00002014bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00002015 switch (Init->getStmtClass()) {
2016 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002017 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002018 return true;
2019 case Expr::ParenExprClass: {
2020 const ParenExpr* PE = cast<ParenExpr>(Init);
2021 return CheckArithmeticConstantExpression(PE->getSubExpr());
2022 }
2023 case Expr::FloatingLiteralClass:
2024 case Expr::IntegerLiteralClass:
2025 case Expr::CharacterLiteralClass:
2026 case Expr::ImaginaryLiteralClass:
2027 case Expr::TypesCompatibleExprClass:
2028 case Expr::CXXBoolLiteralExprClass:
2029 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00002030 case Expr::CallExprClass:
2031 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002032 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002033
2034 // Allow any constant foldable calls to builtins.
2035 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00002036 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002037
Steve Naroff6594a702008-10-27 11:34:16 +00002038 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002039 return true;
2040 }
Douglas Gregor1a49af92009-01-06 05:10:23 +00002041 case Expr::DeclRefExprClass:
2042 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002043 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2044 if (isa<EnumConstantDecl>(D))
2045 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002046 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002047 return true;
2048 }
2049 case Expr::CompoundLiteralExprClass:
2050 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2051 // but vectors are allowed to be magic.
2052 if (Init->getType()->isVectorType())
2053 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002054 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002055 return true;
2056 case Expr::UnaryOperatorClass: {
2057 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2058
2059 switch (Exp->getOpcode()) {
2060 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2061 // See C99 6.6p3.
2062 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002063 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002064 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002065 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00002066 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2067 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002068 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002069 return true;
2070 case UnaryOperator::Extension:
2071 case UnaryOperator::LNot:
2072 case UnaryOperator::Plus:
2073 case UnaryOperator::Minus:
2074 case UnaryOperator::Not:
2075 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2076 }
2077 }
Sebastian Redl05189992008-11-11 17:56:53 +00002078 case Expr::SizeOfAlignOfExprClass: {
2079 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002080 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00002081 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00002082 return false;
2083 // alignof always evaluates to a constant.
2084 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00002085 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00002086 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002087 return true;
2088 }
2089 return false;
2090 }
2091 case Expr::BinaryOperatorClass: {
2092 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2093
2094 if (Exp->getLHS()->getType()->isArithmeticType() &&
2095 Exp->getRHS()->getType()->isArithmeticType()) {
2096 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2097 CheckArithmeticConstantExpression(Exp->getRHS());
2098 }
2099
Eli Friedman4caf0552008-06-09 05:05:07 +00002100 if (Exp->getLHS()->getType()->isPointerType() &&
2101 Exp->getRHS()->getType()->isPointerType()) {
2102 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2103 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2104
2105 // Only allow a null (constant integer) base; we could
2106 // allow some additional cases if necessary, but this
2107 // is sufficient to cover offsetof-like constructs.
2108 if (!LHSBase && !RHSBase) {
2109 return CheckAddressConstantExpression(Exp->getLHS()) ||
2110 CheckAddressConstantExpression(Exp->getRHS());
2111 }
2112 }
2113
Steve Naroff6594a702008-10-27 11:34:16 +00002114 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002115 return true;
2116 }
2117 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002118 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002119 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00002120 if (SubExpr->getType()->isArithmeticType())
2121 return CheckArithmeticConstantExpression(SubExpr);
2122
Eli Friedmanb529d832008-09-02 09:37:00 +00002123 if (SubExpr->getType()->isPointerType()) {
2124 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2125 // If the pointer has a null base, this is an offsetof-like construct
2126 if (!Base)
2127 return CheckAddressConstantExpression(SubExpr);
2128 }
2129
Steve Naroff6594a702008-10-27 11:34:16 +00002130 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00002131 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002132 }
2133 case Expr::ConditionalOperatorClass: {
2134 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00002135
2136 // If GNU extensions are disabled, we require all operands to be arithmetic
2137 // constant expressions.
2138 if (getLangOptions().NoExtensions) {
2139 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2140 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2141 CheckArithmeticConstantExpression(Exp->getRHS());
2142 }
2143
2144 // Otherwise, we have to emulate some of the behavior of fold here.
2145 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2146 // because it can constant fold things away. To retain compatibility with
2147 // GCC code, we see if we can fold the condition to a constant (which we
2148 // should always be able to do in theory). If so, we only require the
2149 // specified arm of the conditional to be a constant. This is a horrible
2150 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002151 Expr::EvalResult EvalResult;
2152 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2153 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002154 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00002155 // won't be able to either. Use it to emit the diagnostic though.
2156 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002157 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00002158 return Res;
2159 }
2160
2161 // Verify that the side following the condition is also a constant.
2162 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002163 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00002164 std::swap(TrueSide, FalseSide);
2165
2166 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00002167 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00002168
2169 // Okay, the evaluated side evaluates to a constant, so we accept this.
2170 // Check to see if the other side is obviously not a constant. If so,
2171 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002172 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00002173 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002174 diag::ext_typecheck_expression_not_constant_but_accepted)
2175 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00002176 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00002177 }
2178 }
2179}
2180
2181bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002182 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init))
2183 Init = DIE->getInit();
2184
Nuno Lopes9a979c32008-07-07 16:46:50 +00002185 Init = Init->IgnoreParens();
2186
Nate Begeman59b5da62009-01-18 03:20:47 +00002187 if (Init->isEvaluatable(Context))
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002188 return false;
2189
Eli Friedmanc594b322008-05-20 13:48:25 +00002190 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2191 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2192 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2193
Nuno Lopes9a979c32008-07-07 16:46:50 +00002194 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2195 return CheckForConstantInitializer(e->getInitializer(), DclT);
2196
Eli Friedmanc594b322008-05-20 13:48:25 +00002197 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2198 unsigned numInits = Exp->getNumInits();
2199 for (unsigned i = 0; i < numInits; i++) {
2200 // FIXME: Need to get the type of the declaration for C++,
2201 // because it could be a reference?
2202 if (CheckForConstantInitializer(Exp->getInit(i),
2203 Exp->getInit(i)->getType()))
2204 return true;
2205 }
2206 return false;
2207 }
2208
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002209 // FIXME: We can probably remove some of this code below, now that
2210 // Expr::Evaluate is doing the heavy lifting for scalars.
2211
Eli Friedmanc594b322008-05-20 13:48:25 +00002212 if (Init->isNullPointerConstant(Context))
2213 return false;
2214 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002215 QualType InitTy = Context.getCanonicalType(Init->getType())
2216 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002217 if (InitTy == Context.BoolTy) {
2218 // Special handling for pointers implicitly cast to bool;
2219 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2220 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2221 Expr* SubE = ICE->getSubExpr();
2222 if (SubE->getType()->isPointerType() ||
2223 SubE->getType()->isArrayType() ||
2224 SubE->getType()->isFunctionType()) {
2225 return CheckAddressConstantExpression(Init);
2226 }
2227 }
2228 } else if (InitTy->isIntegralType()) {
2229 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002230 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002231 SubE = CE->getSubExpr();
2232 // Special check for pointer cast to int; we allow as an extension
2233 // an address constant cast to an integer if the integer
2234 // is of an appropriate width (this sort of code is apparently used
2235 // in some places).
2236 // FIXME: Add pedwarn?
2237 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2238 if (SubE && (SubE->getType()->isPointerType() ||
2239 SubE->getType()->isArrayType() ||
2240 SubE->getType()->isFunctionType())) {
2241 unsigned IntWidth = Context.getTypeSize(Init->getType());
2242 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2243 if (IntWidth >= PointerWidth)
2244 return CheckAddressConstantExpression(Init);
2245 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002246 }
2247
2248 return CheckArithmeticConstantExpression(Init);
2249 }
2250
2251 if (Init->getType()->isPointerType())
2252 return CheckAddressConstantExpression(Init);
2253
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002254 // An array type at the top level that isn't an init-list must
2255 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002256 if (Init->getType()->isArrayType())
2257 return false;
2258
Nuno Lopes73419bf2008-09-01 18:42:41 +00002259 if (Init->getType()->isFunctionType())
2260 return false;
2261
Steve Naroff8af6a452008-10-02 17:12:56 +00002262 // Allow block exprs at top level.
2263 if (Init->getType()->isBlockPointerType())
2264 return false;
Nuno Lopes6ed2ef82009-01-15 16:44:45 +00002265
2266 // GCC cast to union extension
2267 // note: the validity of the cast expr is checked by CheckCastTypes()
2268 if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2269 QualType T = C->getType();
2270 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2271 }
2272
Steve Naroff6594a702008-10-27 11:34:16 +00002273 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002274 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002275}
2276
Sebastian Redl798d1192008-12-13 16:23:55 +00002277void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002278 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2279}
2280
2281/// AddInitializerToDecl - Adds the initializer Init to the
2282/// declaration dcl. If DirectInit is true, this is C++ direct
2283/// initialization rather than copy initialization.
2284void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002285 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002286 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002287 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002288
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002289 // If there is no declaration, there was an error parsing it. Just ignore
2290 // the initializer.
2291 if (RealDecl == 0) {
2292 delete Init;
2293 return;
2294 }
Steve Naroffbb204692007-09-12 14:07:44 +00002295
Steve Naroff410e3e22007-09-12 20:13:48 +00002296 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2297 if (!VDecl) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002298 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002299 RealDecl->setInvalidDecl();
2300 return;
2301 }
Steve Naroffbb204692007-09-12 14:07:44 +00002302 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002303 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002304 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002305 if (VDecl->isBlockVarDecl()) {
2306 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002307 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002308 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002309 VDecl->setInvalidDecl();
2310 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002311 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002312 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002313 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002314
2315 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2316 if (!getLangOptions().CPlusPlus) {
2317 if (SC == VarDecl::Static) // C99 6.7.8p4.
2318 CheckForConstantInitializer(Init, DclT);
2319 }
Steve Naroffbb204692007-09-12 14:07:44 +00002320 }
Steve Naroff248a7532008-04-15 22:42:06 +00002321 } else if (VDecl->isFileVarDecl()) {
2322 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002323 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002324 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002325 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002326 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002327 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002328
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002329 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2330 if (!getLangOptions().CPlusPlus) {
2331 // C99 6.7.8p4. All file scoped initializers need to be constant.
2332 CheckForConstantInitializer(Init, DclT);
2333 }
Steve Naroffbb204692007-09-12 14:07:44 +00002334 }
2335 // If the type changed, it means we had an incomplete type that was
2336 // completed by the initializer. For example:
2337 // int ary[] = { 1, 3, 5 };
2338 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002339 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002340 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002341 Init->setType(DclT);
2342 }
Steve Naroffbb204692007-09-12 14:07:44 +00002343
2344 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002345 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002346 return;
2347}
2348
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002349void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2350 Decl *RealDecl = static_cast<Decl *>(dcl);
2351
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002352 // If there is no declaration, there was an error parsing it. Just ignore it.
2353 if (RealDecl == 0)
2354 return;
2355
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002356 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2357 QualType Type = Var->getType();
2358 // C++ [dcl.init.ref]p3:
2359 // The initializer can be omitted for a reference only in a
2360 // parameter declaration (8.3.5), in the declaration of a
2361 // function return type, in the declaration of a class member
2362 // within its class declaration (9.2), and where the extern
2363 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002364 if (Type->isReferenceType() &&
2365 Var->getStorageClass() != VarDecl::Extern &&
2366 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002367 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002368 << Var->getDeclName()
2369 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002370 Var->setInvalidDecl();
2371 return;
2372 }
2373
2374 // C++ [dcl.init]p9:
2375 //
2376 // If no initializer is specified for an object, and the object
2377 // is of (possibly cv-qualified) non-POD class type (or array
2378 // thereof), the object shall be default-initialized; if the
2379 // object is of const-qualified type, the underlying class type
2380 // shall have a user-declared default constructor.
2381 if (getLangOptions().CPlusPlus) {
2382 QualType InitType = Type;
2383 if (const ArrayType *Array = Context.getAsArrayType(Type))
2384 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002385 if (Var->getStorageClass() != VarDecl::Extern &&
2386 Var->getStorageClass() != VarDecl::PrivateExtern &&
2387 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002388 const CXXConstructorDecl *Constructor
2389 = PerformInitializationByConstructor(InitType, 0, 0,
2390 Var->getLocation(),
2391 SourceRange(Var->getLocation(),
2392 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002393 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002394 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002395 if (!Constructor)
2396 Var->setInvalidDecl();
2397 }
2398 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002399
Douglas Gregor818ce482008-10-29 13:50:18 +00002400#if 0
2401 // FIXME: Temporarily disabled because we are not properly parsing
2402 // linkage specifications on declarations, e.g.,
2403 //
2404 // extern "C" const CGPoint CGPointerZero;
2405 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002406 // C++ [dcl.init]p9:
2407 //
2408 // If no initializer is specified for an object, and the
2409 // object is of (possibly cv-qualified) non-POD class type (or
2410 // array thereof), the object shall be default-initialized; if
2411 // the object is of const-qualified type, the underlying class
2412 // type shall have a user-declared default
2413 // constructor. Otherwise, if no initializer is specified for
2414 // an object, the object and its subobjects, if any, have an
2415 // indeterminate initial value; if the object or any of its
2416 // subobjects are of const-qualified type, the program is
2417 // ill-formed.
2418 //
2419 // This isn't technically an error in C, so we don't diagnose it.
2420 //
2421 // FIXME: Actually perform the POD/user-defined default
2422 // constructor check.
2423 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002424 Context.getCanonicalType(Type).isConstQualified() &&
2425 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002426 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2427 << Var->getName()
2428 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002429#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002430 }
2431}
2432
Reid Spencer5f016e22007-07-11 17:01:13 +00002433/// The declarators are chained together backwards, reverse the list.
2434Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2435 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002436 Decl *GroupDecl = static_cast<Decl*>(group);
2437 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002438 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002439
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002440 Decl *Group = dyn_cast<Decl>(GroupDecl);
2441 Decl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002442 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002443 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002444 else { // reverse the list.
2445 while (Group) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002446 Decl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002447 Group->setNextDeclarator(NewGroup);
2448 NewGroup = Group;
2449 Group = Next;
2450 }
2451 }
2452 // Perform semantic analysis that depends on having fully processed both
2453 // the declarator and initializer.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002454 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002455 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2456 if (!IDecl)
2457 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002458 QualType T = IDecl->getType();
2459
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002460 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002461 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002462
2463 // FIXME: This won't give the correct result for
2464 // int a[10][n];
2465 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002466 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002467 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2468 SizeRange;
2469
Eli Friedmanc5773c42008-02-15 18:16:39 +00002470 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002471 } else {
2472 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2473 // static storage duration, it shall not have a variable length array.
2474 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002475 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2476 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002477 IDecl->setInvalidDecl();
2478 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002479 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2480 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002481 IDecl->setInvalidDecl();
2482 }
2483 }
2484 } else if (T->isVariablyModifiedType()) {
2485 if (IDecl->isFileVarDecl()) {
2486 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2487 IDecl->setInvalidDecl();
2488 } else {
2489 if (IDecl->getStorageClass() == VarDecl::Extern) {
2490 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2491 IDecl->setInvalidDecl();
2492 }
Steve Naroffbb204692007-09-12 14:07:44 +00002493 }
2494 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002495
Steve Naroffbb204692007-09-12 14:07:44 +00002496 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2497 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002498 if (IDecl->isBlockVarDecl() &&
2499 IDecl->getStorageClass() != VarDecl::Extern) {
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002500 if (!IDecl->isInvalidDecl() &&
2501 DiagnoseIncompleteType(IDecl->getLocation(), T,
2502 diag::err_typecheck_decl_incomplete_type))
Steve Naroffbb204692007-09-12 14:07:44 +00002503 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00002504 }
2505 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2506 // object that has file scope without an initializer, and without a
2507 // storage-class specifier or with the storage-class specifier "static",
2508 // constitutes a tentative definition. Note: A tentative definition with
2509 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002510 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002511 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002512 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2513 // array to be completed. Don't issue a diagnostic.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002514 } else if (!IDecl->isInvalidDecl() &&
2515 DiagnoseIncompleteType(IDecl->getLocation(), T,
2516 diag::err_typecheck_decl_incomplete_type))
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002517 // C99 6.9.2p3: If the declaration of an identifier for an object is
2518 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2519 // declared type shall not be an incomplete type.
Steve Naroffbb204692007-09-12 14:07:44 +00002520 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00002521 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002522 if (IDecl->isFileVarDecl())
2523 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002524 }
2525 return NewGroup;
2526}
Steve Naroffe1223f72007-08-28 03:03:08 +00002527
Chris Lattner04421082008-04-08 04:40:51 +00002528/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2529/// to introduce parameters into function prototype scope.
2530Sema::DeclTy *
2531Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002532 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002533
Chris Lattner04421082008-04-08 04:40:51 +00002534 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002535 VarDecl::StorageClass StorageClass = VarDecl::None;
2536 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2537 StorageClass = VarDecl::Register;
2538 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002539 Diag(DS.getStorageClassSpecLoc(),
2540 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002541 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002542 }
2543 if (DS.isThreadSpecified()) {
2544 Diag(DS.getThreadSpecLoc(),
2545 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002546 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002547 }
2548
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002549 // Check that there are no default arguments inside the type of this
2550 // parameter (C++ only).
2551 if (getLangOptions().CPlusPlus)
2552 CheckExtraCXXDefaultArguments(D);
2553
Chris Lattner04421082008-04-08 04:40:51 +00002554 // In this context, we *do not* check D.getInvalidType(). If the declarator
2555 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2556 // though it will not reflect the user specified type.
2557 QualType parmDeclType = GetTypeForDeclarator(D, S);
2558
2559 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2560
Reid Spencer5f016e22007-07-11 17:01:13 +00002561 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2562 // Can this happen for params? We already checked that they don't conflict
2563 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002564 IdentifierInfo *II = D.getIdentifier();
Chris Lattnercf79b012009-01-21 02:38:50 +00002565 if (II) {
2566 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
2567 if (PrevDecl->isTemplateParameter()) {
2568 // Maybe we will complain about the shadowed template parameter.
2569 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2570 // Just pretend that we didn't see the previous declaration.
2571 PrevDecl = 0;
2572 } else if (S->isDeclScope(PrevDecl)) {
2573 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002574
Chris Lattnercf79b012009-01-21 02:38:50 +00002575 // Recover by removing the name
2576 II = 0;
2577 D.SetIdentifier(0, D.getIdentifierLoc());
2578 }
Chris Lattner04421082008-04-08 04:40:51 +00002579 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002580 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002581
2582 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2583 // Doing the promotion here has a win and a loss. The win is the type for
2584 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2585 // code generator). The loss is the orginal type isn't preserved. For example:
2586 //
2587 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2588 // int blockvardecl[5];
2589 // sizeof(parmvardecl); // size == 4
2590 // sizeof(blockvardecl); // size == 20
2591 // }
2592 //
2593 // For expressions, all implicit conversions are captured using the
2594 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2595 //
2596 // FIXME: If a source translation tool needs to see the original type, then
2597 // we need to consider storing both types (in ParmVarDecl)...
2598 //
Chris Lattnere6327742008-04-02 05:18:44 +00002599 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002600 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002601 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002602 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002603 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002604
Chris Lattner04421082008-04-08 04:40:51 +00002605 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2606 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002607 parmDeclType, StorageClass,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002608 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002609
Chris Lattner04421082008-04-08 04:40:51 +00002610 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002611 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002612
Douglas Gregor584049d2008-12-15 23:53:10 +00002613 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2614 if (D.getCXXScopeSpec().isSet()) {
2615 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2616 << D.getCXXScopeSpec().getRange();
2617 New->setInvalidDecl();
2618 }
2619
Douglas Gregor44b43212008-12-11 16:49:14 +00002620 // Add the parameter declaration into this scope.
2621 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002622 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002623 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002624
Chris Lattner3ff30c82008-06-29 00:02:00 +00002625 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002627
Reid Spencer5f016e22007-07-11 17:01:13 +00002628}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002629
Douglas Gregorbe109b32009-01-23 16:23:13 +00002630void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002631 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2632 "Not a function declarator!");
2633 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002634
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2636 // for a K&R function.
2637 if (!FTI.hasPrototype) {
2638 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002639 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002640 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2641 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002642 // Implicitly declare the argument as type 'int' for lack of a better
2643 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002644 DeclSpec DS;
2645 const char* PrevSpec; // unused
2646 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2647 PrevSpec);
2648 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2649 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00002650 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002651 }
2652 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00002653 }
2654}
2655
2656Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2657 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2658 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2659 "Not a function declarator!");
2660 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2661
2662 if (FTI.hasPrototype) {
Chris Lattner04421082008-04-08 04:40:51 +00002663 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002664 }
2665
Douglas Gregor584049d2008-12-15 23:53:10 +00002666 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002667
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002668 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002669 ActOnDeclarator(ParentScope, D, 0,
2670 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002671}
2672
2673Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2674 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002675 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002676
2677 // See if this is a redefinition.
2678 const FunctionDecl *Definition;
2679 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002680 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002681 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002682 }
2683
Douglas Gregor44b43212008-12-11 16:49:14 +00002684 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002685
Chris Lattner04421082008-04-08 04:40:51 +00002686 // Check the validity of our function parameters
2687 CheckParmsForFunctionDef(FD);
2688
2689 // Introduce our parameters into the function scope
2690 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2691 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00002692 Param->setOwningFunction(FD);
2693
Chris Lattner04421082008-04-08 04:40:51 +00002694 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002695 if (Param->getIdentifier())
2696 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002697 }
Chris Lattner04421082008-04-08 04:40:51 +00002698
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002699 // Checking attributes of current function definition
2700 // dllimport attribute.
2701 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2702 // dllimport attribute cannot be applied to definition.
2703 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2704 Diag(FD->getLocation(),
2705 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2706 << "dllimport";
2707 FD->setInvalidDecl();
2708 return FD;
2709 } else {
2710 // If a symbol previously declared dllimport is later defined, the
2711 // attribute is ignored in subsequent references, and a warning is
2712 // emitted.
2713 Diag(FD->getLocation(),
2714 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2715 << FD->getNameAsCString() << "dllimport";
2716 }
2717 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002718 return FD;
2719}
2720
Sebastian Redl798d1192008-12-13 16:23:55 +00002721Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002722 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002723 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002724 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002725 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002726 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002727 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002728 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002729 } else
2730 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002731 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002732 // Verify and clean out per-function state.
2733
2734 // Check goto/label use.
2735 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2736 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2737 // Verify that we have no forward references left. If so, there was a goto
2738 // or address of a label taken, but no definition of it. Label fwd
2739 // definitions are indicated with a null substmt.
2740 if (I->second->getSubStmt() == 0) {
2741 LabelStmt *L = I->second;
2742 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002743 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002744
2745 // At this point, we have gotos that use the bogus label. Stitch it into
2746 // the function body so that they aren't leaked and that the AST is well
2747 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002748 if (Body) {
2749 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002750 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002751 } else {
2752 // The whole function wasn't parsed correctly, just delete this.
2753 delete L;
2754 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002755 }
2756 }
2757 LabelMap.clear();
2758
Steve Naroffd6d054d2007-11-11 23:20:51 +00002759 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002760}
2761
Reid Spencer5f016e22007-07-11 17:01:13 +00002762/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2763/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002764NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2765 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002766 // Extension in C99. Legal in C90, but warn about it.
2767 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002768 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002769 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002770 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002771
2772 // FIXME: handle stuff like:
2773 // void foo() { extern float X(); }
2774 // void bar() { X(); } <-- implicit decl for X in another scope.
2775
2776 // Set a Declarator for the implicit definition: int foo();
2777 const char *Dummy;
2778 DeclSpec DS;
2779 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2780 Error = Error; // Silence warning.
2781 assert(!Error && "Error setting up implicit decl!");
2782 Declarator D(DS, Declarator::BlockContext);
Chris Lattner5af2f352009-01-20 19:11:22 +00002783 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc, D));
Reid Spencer5f016e22007-07-11 17:01:13 +00002784 D.SetIdentifier(&II, Loc);
2785
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002786 // Insert this function into translation-unit scope.
2787
2788 DeclContext *PrevDC = CurContext;
2789 CurContext = Context.getTranslationUnitDecl();
2790
Steve Naroffe2ef8152008-04-04 14:32:09 +00002791 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002792 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002793 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002794
2795 CurContext = PrevDC;
2796
Steve Naroffe2ef8152008-04-04 14:32:09 +00002797 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002798}
2799
2800
Chris Lattner41af0932007-11-14 06:34:38 +00002801TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002802 Decl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002803 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002804 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002805
2806 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002807 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2808 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002809 D.getIdentifier(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002810 T);
2811 NewTD->setNextDeclarator(LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002812 if (D.getInvalidType())
2813 NewTD->setInvalidDecl();
2814 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002815}
2816
Steve Naroff08d92e42007-09-15 18:49:24 +00002817/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002818/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002819/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +00002820/// reference/declaration/definition of a tag.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002821Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002822 SourceLocation KWLoc, const CXXScopeSpec &SS,
2823 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +00002824 AttributeList *Attr,
2825 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002826 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002827 assert((Name != 0 || TK == TK_Definition) &&
2828 "Nameless record must be a definition!");
2829
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002830 TagDecl::TagKind Kind;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002831 switch (TagSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002832 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002833 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2834 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2835 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2836 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002837 }
2838
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002839 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002840 DeclContext *DC = CurContext;
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002841 DeclContext *LexicalContext = CurContext;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002842 Decl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002843
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002844 bool Invalid = false;
2845
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002846 if (Name && SS.isNotEmpty()) {
2847 // We have a nested-name tag ('struct foo::bar').
2848
2849 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002850 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002851 Name = 0;
2852 goto CreateNewDecl;
2853 }
2854
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002855 DC = static_cast<DeclContext*>(SS.getScopeRep());
2856 // Look-up name inside 'foo::'.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002857 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC)
2858 .getAsDecl());
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002859
2860 // A tag 'foo::bar' must already exist.
2861 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002862 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002863 Name = 0;
2864 goto CreateNewDecl;
2865 }
Chris Lattnercf79b012009-01-21 02:38:50 +00002866 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002867 // If this is a named struct, check to see if there was a previous forward
2868 // declaration or definition.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002869 PrevDecl = dyn_cast_or_null<NamedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S)
Chris Lattnercf79b012009-01-21 02:38:50 +00002870 .getAsDecl());
Douglas Gregor72de6672009-01-08 20:45:30 +00002871
2872 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2873 // FIXME: This makes sure that we ignore the contexts associated
2874 // with C structs, unions, and enums when looking for a matching
2875 // tag declaration or definition. See the similar lookup tweak
2876 // in Sema::LookupDecl; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002877 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2878 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +00002879 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002880 }
2881
Douglas Gregorf57172b2008-12-08 18:40:42 +00002882 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002883 // Maybe we will complain about the shadowed template parameter.
2884 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2885 // Just pretend that we didn't see the previous declaration.
2886 PrevDecl = 0;
2887 }
2888
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002889 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002890 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2891 "unexpected Decl type");
2892 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002893 // If this is a use of a previous tag, or if the tag is already declared
2894 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002895 // rementions the tag), reuse the decl.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002896 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002897 // Make sure that this wasn't declared as an enum and now used as a
2898 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002899 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002900 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002901 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002902 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002903 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002904 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002905 Invalid = true;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002906 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002907 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002908
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002909 // FIXME: In the future, return a variant or some other clue
2910 // for the consumer of this Decl to know it doesn't own it.
2911 // For our current ASTs this shouldn't be a problem, but will
2912 // need to be changed with DeclGroups.
2913 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002914 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002915
2916 // Diagnose attempts to redefine a tag.
2917 if (TK == TK_Definition) {
2918 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2919 Diag(NameLoc, diag::err_redefinition) << Name;
2920 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002921 // If this is a redefinition, recover by making this
2922 // struct be anonymous, which will make any later
2923 // references get the previous definition.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002924 Name = 0;
2925 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002926 Invalid = true;
2927 } else {
2928 // If the type is currently being defined, complain
2929 // about a nested redefinition.
2930 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
2931 if (Tag->isBeingDefined()) {
2932 Diag(NameLoc, diag::err_nested_redefinition) << Name;
2933 Diag(PrevTagDecl->getLocation(),
2934 diag::note_previous_definition);
2935 Name = 0;
2936 PrevDecl = 0;
2937 Invalid = true;
2938 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002939 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002940
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002941 // Okay, this is definition of a previously declared or referenced
2942 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002943 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002944 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002945 // If we get here we have (another) forward declaration or we
2946 // have a definition. Just create a new decl.
2947 } else {
2948 // If we get here, this is a definition of a new tag type in a nested
2949 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2950 // new decl/type. We set PrevDecl to NULL so that the entities
2951 // have distinct types.
2952 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002953 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002954 // If we get here, we're going to create a new Decl. If PrevDecl
2955 // is non-NULL, it's a definition of the tag declared by
2956 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002957 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002958 // PrevDecl is a namespace.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002959 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002960 // The tag name clashes with a namespace name, issue an error and
2961 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002962 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002963 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002964 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002965 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002966 Invalid = true;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002967 } else {
2968 // The existing declaration isn't relevant to us; we're in a
2969 // new scope, so clear out the previous declaration.
2970 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002971 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002972 }
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002973 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
2974 (Kind != TagDecl::TK_enum)) {
2975 // C++ [basic.scope.pdecl]p5:
2976 // -- for an elaborated-type-specifier of the form
2977 //
2978 // class-key identifier
2979 //
2980 // if the elaborated-type-specifier is used in the
2981 // decl-specifier-seq or parameter-declaration-clause of a
2982 // function defined in namespace scope, the identifier is
2983 // declared as a class-name in the namespace that contains
2984 // the declaration; otherwise, except as a friend
2985 // declaration, the identifier is declared in the smallest
2986 // non-class, non-function-prototype scope that contains the
2987 // declaration.
2988 //
2989 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
2990 // C structs and unions.
2991
2992 // Find the context where we'll be declaring the tag.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002993 // FIXME: We would like to maintain the current DeclContext as the
2994 // lexical context,
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002995 while (DC->isRecord())
2996 DC = DC->getParent();
2997 LexicalContext = DC;
2998
2999 // Find the scope where we'll be declaring the tag.
3000 while (S->isClassScope() ||
3001 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003002 ((S->getFlags() & Scope::DeclScope) == 0) ||
3003 (S->getEntity() &&
3004 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003005 S = S->getParent();
Reid Spencer5f016e22007-07-11 17:01:13 +00003006 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00003007
Chris Lattnercc98eac2008-12-17 07:13:27 +00003008CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00003009
3010 // If there is an identifier, use the location of the identifier as the
3011 // location of the decl, otherwise use the location of the struct/union
3012 // keyword.
3013 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3014
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003015 // Otherwise, create a new declaration. If there is a previous
3016 // declaration of the same entity, the two will be linked via
3017 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00003018 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003019
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003020 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003021 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3022 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003023 New = EnumDecl::Create(Context, DC, Loc, Name,
3024 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003025 // If this is an undefined enum, warn.
3026 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003027 } else {
3028 // struct/union/class
3029
Reid Spencer5f016e22007-07-11 17:01:13 +00003030 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3031 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003032 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00003033 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003034 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
3035 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003036 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003037 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
3038 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003039 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003040
3041 if (Kind != TagDecl::TK_enum) {
3042 // Handle #pragma pack: if the #pragma pack stack has non-default
3043 // alignment, make up a packed attribute for this decl. These
3044 // attributes are checked when the ASTContext lays out the
3045 // structure.
3046 //
3047 // It is important for implementing the correct semantics that this
3048 // happen here (in act on tag decl). The #pragma pack stack is
3049 // maintained as a result of parser callbacks which can occur at
3050 // many points during the parsing of a struct declaration (because
3051 // the #pragma tokens are effectively skipped over during the
3052 // parsing of the struct).
3053 if (unsigned Alignment = PackContext.getAlignment())
3054 New->addAttr(new PackedAttr(Alignment * 8));
3055 }
3056
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003057 if (Invalid)
3058 New->setInvalidDecl();
3059
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003060 if (Attr)
3061 ProcessDeclAttributeList(New, Attr);
3062
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003063 // If we're declaring or defining a tag in function prototype scope
3064 // in C, note that this type can only be used within the function.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003065 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3066 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3067
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003068 // Set the lexical context. If the tag has a C++ scope specifier, the
3069 // lexical context will be different from the semantic context.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003070 New->setLexicalDeclContext(LexicalContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003071
3072 if (TK == TK_Definition)
3073 New->startDefinition();
Reid Spencer5f016e22007-07-11 17:01:13 +00003074
3075 // If this has an identifier, add it to the scope stack.
3076 if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003077 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003078
3079 // Add it to the decl chain.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003080 if (LexicalContext != CurContext) {
3081 // FIXME: PushOnScopeChains should not rely on CurContext!
3082 DeclContext *OldContext = CurContext;
3083 CurContext = LexicalContext;
3084 PushOnScopeChains(New, S);
3085 CurContext = OldContext;
3086 } else
3087 PushOnScopeChains(New, S);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003088 } else {
Douglas Gregor482b77d2009-01-12 23:27:07 +00003089 LexicalContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00003090 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00003091
Reid Spencer5f016e22007-07-11 17:01:13 +00003092 return New;
3093}
3094
Douglas Gregor72de6672009-01-08 20:45:30 +00003095void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3096 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3097
3098 // Enter the tag context.
3099 PushDeclContext(S, Tag);
3100
3101 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3102 FieldCollector->StartClass();
3103
3104 if (Record->getIdentifier()) {
3105 // C++ [class]p2:
3106 // [...] The class-name is also inserted into the scope of the
3107 // class itself; this is known as the injected-class-name. For
3108 // purposes of access checking, the injected-class-name is treated
3109 // as if it were a public member name.
3110 RecordDecl *InjectedClassName
3111 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3112 CurContext, Record->getLocation(),
3113 Record->getIdentifier(), Record);
3114 InjectedClassName->setImplicit();
3115 PushOnScopeChains(InjectedClassName, S);
3116 }
3117 }
3118}
3119
3120void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3121 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3122
3123 if (isa<CXXRecordDecl>(Tag))
3124 FieldCollector->FinishClass();
3125
3126 // Exit this scope of this tag's definition.
3127 PopDeclContext();
3128
3129 // Notify the consumer that we've defined a tag.
3130 Consumer.HandleTagDeclDefinition(Tag);
3131}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00003132
Chris Lattner1d353ba2008-11-12 21:17:48 +00003133/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3134/// types into constant array types in certain situations which would otherwise
3135/// be errors (for GCC compatibility).
3136static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3137 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00003138 // This method tries to turn a variable array into a constant
3139 // array even when the size isn't an ICE. This is necessary
3140 // for compatibility with code that depends on gcc's buggy
3141 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00003142 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3143 if (!VLATy) return QualType();
3144
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003145 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00003146 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003147 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00003148 return QualType();
3149
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003150 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3151 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00003152 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3153 return Context.getConstantArrayType(VLATy->getElementType(),
3154 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003155 return QualType();
3156}
3157
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003158bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00003159 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003160 // FIXME: 6.7.2.1p4 - verify the field type.
3161
3162 llvm::APSInt Value;
3163 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3164 return true;
3165
Chris Lattnercd087072008-12-12 04:56:04 +00003166 // Zero-width bitfield is ok for anonymous field.
3167 if (Value == 0 && FieldName)
3168 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3169
3170 if (Value.isNegative())
3171 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003172
3173 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3174 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00003175 if (TypeSize && Value.getZExtValue() > TypeSize)
3176 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3177 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003178
3179 return false;
3180}
3181
Steve Naroff08d92e42007-09-15 18:49:24 +00003182/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00003183/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00003184Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00003185 SourceLocation DeclStart,
3186 Declarator &D, ExprTy *BitfieldWidth) {
3187 IdentifierInfo *II = D.getIdentifier();
3188 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00003189 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00003190 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003191 if (II) Loc = D.getIdentifierLoc();
3192
3193 // FIXME: Unnamed fields can be handled in various different ways, for
3194 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00003195
Reid Spencer5f016e22007-07-11 17:01:13 +00003196 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00003197 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3198 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00003199
Reid Spencer5f016e22007-07-11 17:01:13 +00003200 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3201 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00003202 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00003203 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003204 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003205 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003206 T = FixedTy;
3207 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003208 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00003209 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00003210 InvalidDecl = true;
3211 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003212 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003213
3214 if (BitWidth) {
3215 if (VerifyBitField(Loc, II, T, BitWidth))
3216 InvalidDecl = true;
3217 } else {
3218 // Not a bitfield.
3219
3220 // validate II.
3221
3222 }
3223
Reid Spencer5f016e22007-07-11 17:01:13 +00003224 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003225 FieldDecl *NewFD;
3226
Douglas Gregor44b43212008-12-11 16:49:14 +00003227 NewFD = FieldDecl::Create(Context, Record,
3228 Loc, II, T, BitWidth,
3229 D.getDeclSpec().getStorageClassSpec() ==
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003230 DeclSpec::SCS_mutable);
Douglas Gregor44b43212008-12-11 16:49:14 +00003231
Douglas Gregor72de6672009-01-08 20:45:30 +00003232 if (II) {
3233 Decl *PrevDecl
Steve Naroff133147d2009-01-28 16:09:22 +00003234 = LookupDecl(II, Decl::IDNS_Member, S, 0, false);
Douglas Gregor72de6672009-01-08 20:45:30 +00003235 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3236 && !isa<TagDecl>(PrevDecl)) {
3237 Diag(Loc, diag::err_duplicate_member) << II;
3238 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3239 NewFD->setInvalidDecl();
3240 Record->setInvalidDecl();
3241 }
3242 }
3243
Sebastian Redl64b45f72009-01-05 20:52:13 +00003244 if (getLangOptions().CPlusPlus) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003245 CheckExtraCXXDefaultArguments(D);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003246 if (!T->isPODType())
3247 cast<CXXRecordDecl>(Record)->setPOD(false);
3248 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003249
Chris Lattner3ff30c82008-06-29 00:02:00 +00003250 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00003251
Steve Naroff5912a352007-08-28 20:14:24 +00003252 if (D.getInvalidType() || InvalidDecl)
3253 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003254
Douglas Gregor72de6672009-01-08 20:45:30 +00003255 if (II) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003256 PushOnScopeChains(NewFD, S);
Douglas Gregor72de6672009-01-08 20:45:30 +00003257 } else
Douglas Gregor482b77d2009-01-12 23:27:07 +00003258 Record->addDecl(NewFD);
Douglas Gregor44b43212008-12-11 16:49:14 +00003259
Steve Naroff5912a352007-08-28 20:14:24 +00003260 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003261}
3262
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003263/// TranslateIvarVisibility - Translate visibility from a token ID to an
3264/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003265static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003266TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00003267 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00003268 default: assert(0 && "Unknown visitibility kind");
3269 case tok::objc_private: return ObjCIvarDecl::Private;
3270 case tok::objc_public: return ObjCIvarDecl::Public;
3271 case tok::objc_protected: return ObjCIvarDecl::Protected;
3272 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00003273 }
3274}
3275
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003276/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3277/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003278Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003279 SourceLocation DeclStart,
3280 Declarator &D, ExprTy *BitfieldWidth,
3281 tok::ObjCKeywordKind Visibility) {
Douglas Gregor72de6672009-01-08 20:45:30 +00003282
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003283 IdentifierInfo *II = D.getIdentifier();
3284 Expr *BitWidth = (Expr*)BitfieldWidth;
3285 SourceLocation Loc = DeclStart;
3286 if (II) Loc = D.getIdentifierLoc();
3287
3288 // FIXME: Unnamed fields can be handled in various different ways, for
3289 // example, unnamed unions inject all members into the struct namespace!
3290
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003291 QualType T = GetTypeForDeclarator(D, S);
3292 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3293 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003294
3295 if (BitWidth) {
3296 // TODO: Validate.
3297 //printf("WARNING: BITFIELDS IGNORED!\n");
3298
3299 // 6.7.2.1p3
3300 // 6.7.2.1p4
3301
3302 } else {
3303 // Not a bitfield.
3304
3305 // validate II.
3306
3307 }
3308
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003309 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3310 // than a variably modified type.
3311 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00003312 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003313 InvalidDecl = true;
3314 }
3315
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003316 // Get the visibility (access control) for this ivar.
3317 ObjCIvarDecl::AccessControl ac =
3318 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3319 : ObjCIvarDecl::None;
3320
3321 // Construct the decl.
3322 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00003323 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003324
Douglas Gregor72de6672009-01-08 20:45:30 +00003325 if (II) {
3326 Decl *PrevDecl
Steve Naroff133147d2009-01-28 16:09:22 +00003327 = LookupDecl(II, Decl::IDNS_Member, S, 0, false);
Douglas Gregor72de6672009-01-08 20:45:30 +00003328 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3329 && !isa<TagDecl>(PrevDecl)) {
3330 Diag(Loc, diag::err_duplicate_member) << II;
3331 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3332 NewID->setInvalidDecl();
3333 }
3334 }
3335
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003336 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00003337 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003338
3339 if (D.getInvalidType() || InvalidDecl)
3340 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003341
Douglas Gregor72de6672009-01-08 20:45:30 +00003342 if (II) {
3343 // FIXME: When interfaces are DeclContexts, we'll need to add
3344 // these to the interface.
3345 S->AddDecl(NewID);
3346 IdResolver.AddDecl(NewID);
3347 }
3348
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003349 return NewID;
3350}
3351
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00003352void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003353 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00003354 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00003355 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00003356 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00003357 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3358 assert(EnclosingDecl && "missing record or interface decl");
3359 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3360
Reid Spencer5f016e22007-07-11 17:01:13 +00003361 // Verify that all the fields are okay.
3362 unsigned NumNamedMembers = 0;
3363 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003364
Reid Spencer5f016e22007-07-11 17:01:13 +00003365 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff74216642007-09-14 22:20:54 +00003366 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3367 assert(FD && "missing field decl");
3368
Reid Spencer5f016e22007-07-11 17:01:13 +00003369 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003370 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003371
Douglas Gregor72de6672009-01-08 20:45:30 +00003372 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003373 // Remember all fields written by the user.
3374 RecFields.push_back(FD);
3375 }
Steve Narofff13271f2007-09-14 23:09:53 +00003376
Reid Spencer5f016e22007-07-11 17:01:13 +00003377 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003378 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003379 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003380 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003381 FD->setInvalidDecl();
3382 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003383 continue;
3384 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003385 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3386 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003387 if (!Record) { // Incomplete ivar type is always an error.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003388 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3389 diag::err_field_incomplete);
Steve Naroff74216642007-09-14 22:20:54 +00003390 FD->setInvalidDecl();
3391 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003392 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003393 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003394 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003395 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003396 !FDTy->isArrayType()) { //... may have incomplete array type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003397 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3398 diag::err_field_incomplete);
Steve Naroff74216642007-09-14 22:20:54 +00003399 FD->setInvalidDecl();
3400 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003401 continue;
3402 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003403 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003404 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003405 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003406 FD->setInvalidDecl();
3407 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003408 continue;
3409 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003410 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003411 if (Record)
3412 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003413 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003414 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3415 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003416 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003417 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3418 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003419 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003420 Record->setHasFlexibleArrayMember(true);
3421 } else {
3422 // If this is a struct/class and this is not the last element, reject
3423 // it. Note that GCC supports variable sized arrays in the middle of
3424 // structures.
3425 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003426 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003427 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003428 FD->setInvalidDecl();
3429 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003430 continue;
3431 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003432 // We support flexible arrays at the end of structs in other structs
3433 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003434 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003435 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003436 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003437 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003438 }
3439 }
3440 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003441 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003442 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003443 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003444 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003445 FD->setInvalidDecl();
3446 EnclosingDecl->setInvalidDecl();
3447 continue;
3448 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003449 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00003450 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00003451 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003452 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003453
Reid Spencer5f016e22007-07-11 17:01:13 +00003454 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003455 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003456 Record->completeDefinition(Context);
Chris Lattnere1e79852008-02-06 00:51:33 +00003457 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003458 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003459 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003460 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003461 // Must enforce the rule that ivars in the base classes may not be
3462 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003463 if (ID->getSuperClass()) {
3464 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3465 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3466 ObjCIvarDecl* Ivar = (*IVI);
3467 IdentifierInfo *II = Ivar->getIdentifier();
3468 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3469 if (prevIvar) {
3470 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregor72de6672009-01-08 20:45:30 +00003471 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003472 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003473 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003474 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003475 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003476 else if (ObjCImplementationDecl *IMPDecl =
3477 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003478 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3479 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003480 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003481 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003482 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003483
3484 if (Attr)
3485 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003486}
3487
Steve Naroff08d92e42007-09-15 18:49:24 +00003488Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003489 DeclTy *lastEnumConst,
3490 SourceLocation IdLoc, IdentifierInfo *Id,
3491 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003492 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003493 EnumConstantDecl *LastEnumConst =
3494 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3495 Expr *Val = static_cast<Expr*>(val);
3496
Chris Lattner31e05722007-08-26 06:24:45 +00003497 // The scope passed in may not be a decl scope. Zip up the scope tree until
3498 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003499 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003500
Reid Spencer5f016e22007-07-11 17:01:13 +00003501 // Verify that there isn't already something declared with this name in this
3502 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003503 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003504 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003505 // Maybe we will complain about the shadowed template parameter.
3506 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3507 // Just pretend that we didn't see the previous declaration.
3508 PrevDecl = 0;
3509 }
3510
3511 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003512 // When in C++, we may get a TagDecl with the same name; in this case the
3513 // enum constant will 'hide' the tag.
3514 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3515 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003516 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003517 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003518 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003519 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003520 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003521 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003522 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003523 return 0;
3524 }
3525 }
3526
3527 llvm::APSInt EnumVal(32);
3528 QualType EltTy;
3529 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003530 // Make sure to promote the operand type to int.
3531 UsualUnaryConversions(Val);
3532
Reid Spencer5f016e22007-07-11 17:01:13 +00003533 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3534 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003535 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003536 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003537 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003538 } else {
3539 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003540 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003541 }
3542
3543 if (!Val) {
3544 if (LastEnumConst) {
3545 // Assign the last value + 1.
3546 EnumVal = LastEnumConst->getInitVal();
3547 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003548
3549 // Check for overflow on increment.
3550 if (EnumVal < LastEnumConst->getInitVal())
3551 Diag(IdLoc, diag::warn_enum_value_overflow);
3552
Chris Lattnerb7416f92007-08-27 17:37:24 +00003553 EltTy = LastEnumConst->getType();
3554 } else {
3555 // First value, set to zero.
3556 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003557 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003558 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003559 }
3560
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003561 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003562 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003563 Val, EnumVal);
Reid Spencer5f016e22007-07-11 17:01:13 +00003564
3565 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003566 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003567
Reid Spencer5f016e22007-07-11 17:01:13 +00003568 return New;
3569}
3570
Steve Naroff02408c62008-08-07 14:08:16 +00003571// FIXME: For consistency with ActOnFields(), we should have the parser
3572// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003573void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003574 DeclTy **Elements, unsigned NumElements) {
3575 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00003576 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003577
Chris Lattnere37f0be2007-08-28 05:10:31 +00003578 // TODO: If the result value doesn't fit in an int, it must be a long or long
3579 // long value. ISO C does not support this, but GCC does as an extension,
3580 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003581 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003582
Chris Lattnerac609682007-08-28 06:15:15 +00003583 // Verify that all the values are okay, compute the size of the values, and
3584 // reverse the list.
3585 unsigned NumNegativeBits = 0;
3586 unsigned NumPositiveBits = 0;
3587
3588 // Keep track of whether all elements have type int.
3589 bool AllElementsInt = true;
3590
Reid Spencer5f016e22007-07-11 17:01:13 +00003591 for (unsigned i = 0; i != NumElements; ++i) {
3592 EnumConstantDecl *ECD =
3593 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3594 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003595
3596 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003597 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003598 assert(InitVal.getBitWidth() >= IntWidth &&
3599 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003600 if (InitVal.getBitWidth() > IntWidth) {
3601 llvm::APSInt V(InitVal);
3602 V.trunc(IntWidth);
3603 V.extend(InitVal.getBitWidth());
3604 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003605 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3606 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003607 }
Chris Lattnerac609682007-08-28 06:15:15 +00003608
3609 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003610 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003611 NumPositiveBits = std::max(NumPositiveBits,
3612 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003613 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003614 NumNegativeBits = std::max(NumNegativeBits,
3615 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003616
Chris Lattnerac609682007-08-28 06:15:15 +00003617 // Keep track of whether every enum element has type int (very commmon).
3618 if (AllElementsInt)
3619 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003620 }
3621
Chris Lattnerac609682007-08-28 06:15:15 +00003622 // Figure out the type that should be used for this enum.
3623 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3624 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003625 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003626
3627 if (NumNegativeBits) {
3628 // If there is a negative value, figure out the smallest integer type (of
3629 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003630 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003631 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003632 BestWidth = IntWidth;
3633 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003634 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003635
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003636 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003637 BestType = Context.LongTy;
3638 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003639 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003640
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003641 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003642 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3643 BestType = Context.LongLongTy;
3644 }
3645 }
3646 } else {
3647 // If there is no negative value, figure out which of uint, ulong, ulonglong
3648 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003649 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003650 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003651 BestWidth = IntWidth;
3652 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003653 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003654 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003655 } else {
3656 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003657 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003658 "How could an initializer get larger than ULL?");
3659 BestType = Context.UnsignedLongLongTy;
3660 }
3661 }
3662
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003663 // Loop over all of the enumerator constants, changing their types to match
3664 // the type of the enum if needed.
3665 for (unsigned i = 0; i != NumElements; ++i) {
3666 EnumConstantDecl *ECD =
3667 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3668 if (!ECD) continue; // Already issued a diagnostic.
3669
3670 // Standard C says the enumerators have int type, but we allow, as an
3671 // extension, the enumerators to be larger than int size. If each
3672 // enumerator value fits in an int, type it as an int, otherwise type it the
3673 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3674 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003675 if (ECD->getType() == Context.IntTy) {
3676 // Make sure the init value is signed.
3677 llvm::APSInt IV = ECD->getInitVal();
3678 IV.setIsSigned(true);
3679 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003680
3681 if (getLangOptions().CPlusPlus)
3682 // C++ [dcl.enum]p4: Following the closing brace of an
3683 // enum-specifier, each enumerator has the type of its
3684 // enumeration.
3685 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003686 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003687 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003688
3689 // Determine whether the value fits into an int.
3690 llvm::APSInt InitVal = ECD->getInitVal();
3691 bool FitsInInt;
3692 if (InitVal.isUnsigned() || !InitVal.isNegative())
3693 FitsInInt = InitVal.getActiveBits() < IntWidth;
3694 else
3695 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3696
3697 // If it fits into an integer type, force it. Otherwise force it to match
3698 // the enum decl type.
3699 QualType NewTy;
3700 unsigned NewWidth;
3701 bool NewSign;
3702 if (FitsInInt) {
3703 NewTy = Context.IntTy;
3704 NewWidth = IntWidth;
3705 NewSign = true;
3706 } else if (ECD->getType() == BestType) {
3707 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003708 if (getLangOptions().CPlusPlus)
3709 // C++ [dcl.enum]p4: Following the closing brace of an
3710 // enum-specifier, each enumerator has the type of its
3711 // enumeration.
3712 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003713 continue;
3714 } else {
3715 NewTy = BestType;
3716 NewWidth = BestWidth;
3717 NewSign = BestType->isSignedIntegerType();
3718 }
3719
3720 // Adjust the APSInt value.
3721 InitVal.extOrTrunc(NewWidth);
3722 InitVal.setIsSigned(NewSign);
3723 ECD->setInitVal(InitVal);
3724
3725 // Adjust the Expr initializer and type.
Chris Lattner13fd4162009-01-15 19:19:42 +00003726 if (ECD->getInitExpr())
3727 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3728 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003729 if (getLangOptions().CPlusPlus)
3730 // C++ [dcl.enum]p4: Following the closing brace of an
3731 // enum-specifier, each enumerator has the type of its
3732 // enumeration.
3733 ECD->setType(EnumType);
3734 else
3735 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003736 }
Chris Lattnerac609682007-08-28 06:15:15 +00003737
Douglas Gregor44b43212008-12-11 16:49:14 +00003738 Enum->completeDefinition(Context, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00003739}
3740
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003741Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003742 ExprArg expr) {
3743 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3744
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003745 return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003746}
3747
Douglas Gregorf44515a2008-12-16 22:23:02 +00003748
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003749void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3750 ExprTy *alignment, SourceLocation PragmaLoc,
3751 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3752 Expr *Alignment = static_cast<Expr *>(alignment);
3753
3754 // If specified then alignment must be a "small" power of two.
3755 unsigned AlignmentVal = 0;
3756 if (Alignment) {
3757 llvm::APSInt Val;
3758 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3759 !Val.isPowerOf2() ||
3760 Val.getZExtValue() > 16) {
3761 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3762 delete Alignment;
3763 return; // Ignore
3764 }
3765
3766 AlignmentVal = (unsigned) Val.getZExtValue();
3767 }
3768
3769 switch (Kind) {
3770 case Action::PPK_Default: // pack([n])
3771 PackContext.setAlignment(AlignmentVal);
3772 break;
3773
3774 case Action::PPK_Show: // pack(show)
3775 // Show the current alignment, making sure to show the right value
3776 // for the default.
3777 AlignmentVal = PackContext.getAlignment();
3778 // FIXME: This should come from the target.
3779 if (AlignmentVal == 0)
3780 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003781 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003782 break;
3783
3784 case Action::PPK_Push: // pack(push [, id] [, [n])
3785 PackContext.push(Name);
3786 // Set the new alignment if specified.
3787 if (Alignment)
3788 PackContext.setAlignment(AlignmentVal);
3789 break;
3790
3791 case Action::PPK_Pop: // pack(pop [, id] [, n])
3792 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3793 // "#pragma pack(pop, identifier, n) is undefined"
3794 if (Alignment && Name)
3795 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3796
3797 // Do the pop.
3798 if (!PackContext.pop(Name)) {
3799 // If a name was specified then failure indicates the name
3800 // wasn't found. Otherwise failure indicates the stack was
3801 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003802 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3803 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003804
3805 // FIXME: Warn about popping named records as MSVC does.
3806 } else {
3807 // Pop succeeded, set the new alignment if specified.
3808 if (Alignment)
3809 PackContext.setAlignment(AlignmentVal);
3810 }
3811 break;
3812
3813 default:
3814 assert(0 && "Invalid #pragma pack kind.");
3815 }
3816}
3817
3818bool PragmaPackStack::pop(IdentifierInfo *Name) {
3819 if (Stack.empty())
3820 return false;
3821
3822 // If name is empty just pop top.
3823 if (!Name) {
3824 Alignment = Stack.back().first;
3825 Stack.pop_back();
3826 return true;
3827 }
3828
3829 // Otherwise, find the named record.
3830 for (unsigned i = Stack.size(); i != 0; ) {
3831 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003832 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003833 // Found it, pop up to and including this record.
3834 Alignment = Stack[i].first;
3835 Stack.erase(Stack.begin() + i, Stack.end());
3836 return true;
3837 }
3838 }
3839
3840 return false;
3841}