blob: 0927576b5166d5f8b880548556fc030649bc060b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregore267ff32008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Douglas Gregore267ff32008-12-11 20:41:00 +000031
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
Douglas Gregor2def4832008-11-17 20:34:05 +000034Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000035 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000036 DeclContext *DC = 0;
37 if (SS) {
38 if (SS->isInvalid())
39 return 0;
40 DC = static_cast<DeclContext*>(SS->getScopeRep());
41 }
Douglas Gregor7176fff2009-01-15 00:26:24 +000042 LookupResult Result = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
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
91 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
92 return SD->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.
124 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
Douglas Gregor482b77d2009-01-12 23:27:07 +0000125 CurContext->addDecl(SD);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000126
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000127 // C++ [basic.scope]p4:
128 // -- exactly one declaration shall declare a class name or
129 // enumeration name that is not a typedef name and the other
130 // declarations shall all refer to the same object or
131 // enumerator, or all refer to functions and function templates;
132 // in this case the class name or enumeration name is hidden.
133 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
134 // We are pushing the name of a tag (enum or class).
Douglas Gregore21b9942009-01-07 16:34:42 +0000135 if (CurContext->getLookupContext()
136 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000137 // We're pushing the tag into the current context, which might
138 // require some reshuffling in the identifier resolver.
139 IdentifierResolver::iterator
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000140 I = IdResolver.begin(TD->getDeclName(), CurContext,
141 false/*LookInParentCtx*/),
142 IEnd = IdResolver.end();
143 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
144 NamedDecl *PrevDecl = *I;
145 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
146 PrevDecl = *I, ++I) {
147 if (TD->declarationReplaces(*I)) {
148 // This is a redeclaration. Remove it from the chain and
149 // break out, so that we'll add in the shadowed
150 // declaration.
151 S->RemoveDecl(*I);
152 if (PrevDecl == *I) {
153 IdResolver.RemoveDecl(*I);
154 IdResolver.AddDecl(TD);
155 return;
156 } else {
157 IdResolver.RemoveDecl(*I);
158 break;
159 }
160 }
161 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000162
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000163 // There is already a declaration with the same name in the same
164 // scope, which is not a tag declaration. It must be found
165 // before we find the new declaration, so insert the new
166 // declaration at the end of the chain.
167 IdResolver.AddShadowedDecl(TD, PrevDecl);
168
169 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000170 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000171 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000172 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000173 // We are pushing the name of a function, which might be an
174 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000175 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregorce356072009-01-06 23:51:29 +0000176 DeclContext *DC = FD->getDeclContext()->getLookupContext();
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000177 IdentifierResolver::iterator Redecl
Douglas Gregor074149e2009-01-05 19:45:36 +0000178 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000179 false/*LookInParentCtx*/),
180 IdResolver.end(),
181 std::bind1st(std::mem_fun(&ScopedDecl::declarationReplaces),
182 FD));
183 if (Redecl != IdResolver.end()) {
184 // There is already a declaration of a function on our
185 // IdResolver chain. Replace it with this declaration.
186 S->RemoveDecl(*Redecl);
187 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000188 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000189 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000190
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000191 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000192}
193
Steve Naroffb216c882007-10-09 22:01:59 +0000194void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000195 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000196 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
197 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000198
Reid Spencer5f016e22007-07-11 17:01:13 +0000199 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
200 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000201 Decl *TmpD = static_cast<Decl*>(*I);
202 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000203
Douglas Gregor44b43212008-12-11 16:49:14 +0000204 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
205 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000206
Douglas Gregor44b43212008-12-11 16:49:14 +0000207 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000208
Douglas Gregor44b43212008-12-11 16:49:14 +0000209 // Remove this name from our lexical scope.
210 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000211 }
212}
213
Steve Naroffe8043c32008-04-01 23:04:06 +0000214/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
215/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000216ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000217 // The third "scope" argument is 0 since we aren't enabling lazy built-in
218 // creation from this context.
219 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000220
Steve Naroffb327ce02008-04-02 14:35:35 +0000221 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000222}
223
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000224/// getNonFieldDeclScope - Retrieves the innermost scope, starting
225/// from S, where a non-field would be declared. This routine copes
226/// with the difference between C and C++ scoping rules in structs and
227/// unions. For example, the following code is well-formed in C but
228/// ill-formed in C++:
229/// @code
230/// struct S6 {
231/// enum { BAR } e;
232/// };
233///
234/// void test_S6() {
235/// struct S6 a;
236/// a.e = BAR;
237/// }
238/// @endcode
239/// For the declaration of BAR, this routine will return a different
240/// scope. The scope S will be the scope of the unnamed enumeration
241/// within S6. In C++, this routine will return the scope associated
242/// with S6, because the enumeration's scope is a transparent
243/// context but structures can contain non-field names. In C, this
244/// routine will return the translation unit scope, since the
245/// enumeration's scope is a transparent context and structures cannot
246/// contain non-field names.
247Scope *Sema::getNonFieldDeclScope(Scope *S) {
248 while (((S->getFlags() & Scope::DeclScope) == 0) ||
249 (S->getEntity() &&
250 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
251 (S->isClassScope() && !getLangOptions().CPlusPlus))
252 S = S->getParent();
253 return S;
254}
255
Steve Naroffe8043c32008-04-01 23:04:06 +0000256/// LookupDecl - Look up the inner-most declaration in the specified
Douglas Gregorf780abc2008-12-30 03:27:21 +0000257/// namespace. NamespaceNameOnly - during lookup only namespace names
258/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
259/// 'When looking up a namespace-name in a using-directive or
260/// namespace-alias-definition, only namespace names are considered.'
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000261///
262/// Note: The use of this routine is deprecated. Please use
263/// LookupName, LookupQualifiedName, or LookupParsedName instead.
264Sema::LookupResult
265Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
266 const DeclContext *LookupCtx,
267 bool enableLazyBuiltinCreation,
268 bool LookInParent,
269 bool NamespaceNameOnly) {
270 LookupCriteria::NameKind Kind;
271 if (NSI == Decl::IDNS_Ordinary) {
272 if (NamespaceNameOnly)
273 Kind = LookupCriteria::Namespace;
274 else
275 Kind = LookupCriteria::Ordinary;
276 } else if (NSI == Decl::IDNS_Tag)
277 Kind = LookupCriteria::Tag;
278 else if (NSI == Decl::IDNS_Member)
279 Kind = LookupCriteria::Member;
280 else
281 assert(false && "Unable to grok LookupDecl NSI argument");
Chris Lattner7f925cc2008-04-11 07:00:53 +0000282
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000283 if (LookupCtx)
284 return LookupQualifiedName(const_cast<DeclContext *>(LookupCtx), Name,
285 LookupCriteria(Kind, !LookInParent,
286 getLangOptions().CPlusPlus));
Douglas Gregor72de6672009-01-08 20:45:30 +0000287
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000288 // Unqualified lookup
289 return LookupName(S, Name,
290 LookupCriteria(Kind, !LookInParent,
291 getLangOptions().CPlusPlus));
Reid Spencer5f016e22007-07-11 17:01:13 +0000292}
293
Chris Lattner95e2c712008-05-05 22:18:14 +0000294void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000295 if (!Context.getBuiltinVaListType().isNull())
296 return;
297
298 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000299 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000300 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000301 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
302}
303
Reid Spencer5f016e22007-07-11 17:01:13 +0000304/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
305/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000306ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
307 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 Builtin::ID BID = (Builtin::ID)bid;
309
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000310 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000311 InitBuiltinVaListType();
312
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000313 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000314 FunctionDecl *New = FunctionDecl::Create(Context,
315 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000316 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000317 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000318
Chris Lattner95e2c712008-05-05 22:18:14 +0000319 // Create Decl objects for each parameter, adding them to the
320 // FunctionDecl.
321 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
322 llvm::SmallVector<ParmVarDecl*, 16> Params;
323 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
324 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
325 FT->getArgType(i), VarDecl::None, 0,
326 0));
Ted Kremenekfc767612009-01-14 00:42:25 +0000327 New->setParams(Context, &Params[0], Params.size());
Chris Lattner95e2c712008-05-05 22:18:14 +0000328 }
329
330
331
Chris Lattner7f925cc2008-04-11 07:00:53 +0000332 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000333 // FIXME: This is hideous. We need to teach PushOnScopeChains to
334 // relate Scopes to DeclContexts, and probably eliminate CurContext
335 // entirely, but we're not there yet.
336 DeclContext *SavedContext = CurContext;
337 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000338 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000339 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 return New;
341}
342
Sebastian Redlc42e1182008-11-11 11:37:55 +0000343/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
344/// everything from the standard library is defined.
345NamespaceDecl *Sema::GetStdNamespace() {
346 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000347 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000348 DeclContext *Global = Context.getTranslationUnitDecl();
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000349 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000350 0, Global, /*enableLazyBuiltinCreation=*/false);
351 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
352 }
353 return StdNamespace;
354}
355
Reid Spencer5f016e22007-07-11 17:01:13 +0000356/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
357/// and scope as a previous declaration 'Old'. Figure out how to resolve this
358/// situation, merging decls or emitting diagnostics as appropriate.
359///
Steve Naroffe8043c32008-04-01 23:04:06 +0000360TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000361 // Allow multiple definitions for ObjC built-in typedefs.
362 // FIXME: Verify the underlying types are equivalent!
363 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000364 const IdentifierInfo *TypeID = New->getIdentifier();
365 switch (TypeID->getLength()) {
366 default: break;
367 case 2:
368 if (!TypeID->isStr("id"))
369 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000370 Context.setObjCIdType(New);
371 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000372 case 5:
373 if (!TypeID->isStr("Class"))
374 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000375 Context.setObjCClassType(New);
376 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000377 case 3:
378 if (!TypeID->isStr("SEL"))
379 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000380 Context.setObjCSelType(New);
381 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000382 case 8:
383 if (!TypeID->isStr("Protocol"))
384 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000385 Context.setObjCProtoType(New->getUnderlyingType());
386 return New;
387 }
388 // Fall through - the typedef name was not a builtin type.
389 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000390 // Verify the old decl was also a typedef.
391 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
392 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000393 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000394 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000395 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 return New;
397 }
398
Chris Lattner99cb9972008-07-25 18:44:27 +0000399 // If the typedef types are not identical, reject them in all languages and
400 // with any extensions enabled.
401 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
402 Context.getCanonicalType(Old->getUnderlyingType()) !=
403 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000404 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000405 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000406 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000407 return New;
Chris Lattner99cb9972008-07-25 18:44:27 +0000408 }
409
Eli Friedman54ecfce2008-06-11 06:20:39 +0000410 if (getLangOptions().Microsoft) return New;
411
Douglas Gregorbbe27432008-11-21 16:29:06 +0000412 // C++ [dcl.typedef]p2:
413 // In a given non-class scope, a typedef specifier can be used to
414 // redefine the name of any type declared in that scope to refer
415 // to the type to which it already refers.
416 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
417 return New;
418
419 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000420 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
421 // *either* declaration is in a system header. The code below implements
422 // this adhoc compatibility rule. FIXME: The following code will not
423 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000424 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
425 SourceManager &SrcMgr = Context.getSourceManager();
426 if (SrcMgr.isInSystemHeader(Old->getLocation()))
427 return New;
428 if (SrcMgr.isInSystemHeader(New->getLocation()))
429 return New;
430 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000431
Chris Lattner08631c52008-11-23 21:45:46 +0000432 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000433 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000434 return New;
435}
436
Chris Lattner6b6b5372008-06-26 18:38:35 +0000437/// DeclhasAttr - returns true if decl Declaration already has the target
438/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000439static bool DeclHasAttr(const Decl *decl, const Attr *target) {
440 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
441 if (attr->getKind() == target->getKind())
442 return true;
443
444 return false;
445}
446
447/// MergeAttributes - append attributes from the Old decl to the New one.
448static void MergeAttributes(Decl *New, Decl *Old) {
449 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
450
Chris Lattnerddee4232008-03-03 03:28:21 +0000451 while (attr) {
452 tmp = attr;
453 attr = attr->getNext();
454
455 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000456 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000457 New->addAttr(tmp);
458 } else {
459 tmp->setNext(0);
460 delete(tmp);
461 }
462 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000463
464 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000465}
466
Chris Lattner04421082008-04-08 04:40:51 +0000467/// MergeFunctionDecl - We just parsed a function 'New' from
468/// declarator D which has the same name and scope as a previous
469/// declaration 'Old'. Figure out how to resolve this situation,
470/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000471/// Redeclaration will be set true if this New is a redeclaration OldD.
472///
473/// In C++, New and Old must be declarations that are not
474/// overloaded. Use IsOverload to determine whether New and Old are
475/// overloaded, and to select the Old declaration that New should be
476/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000477FunctionDecl *
478Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000479 assert(!isa<OverloadedFunctionDecl>(OldD) &&
480 "Cannot merge with an overloaded function declaration");
481
Douglas Gregorf0097952008-04-21 02:02:58 +0000482 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000483 // Verify the old decl was also a function.
484 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
485 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000486 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000487 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000488 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000489 return New;
490 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491
492 // Determine whether the previous declaration was a definition,
493 // implicit declaration, or a declaration.
494 diag::kind PrevDiag;
495 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000496 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000497 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000498 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000499 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000500 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000501
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000502 QualType OldQType = Context.getCanonicalType(Old->getType());
503 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000504
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000505 if (getLangOptions().CPlusPlus) {
506 // (C++98 13.1p2):
507 // Certain function declarations cannot be overloaded:
508 // -- Function declarations that differ only in the return type
509 // cannot be overloaded.
510 QualType OldReturnType
511 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
512 QualType NewReturnType
513 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
514 if (OldReturnType != NewReturnType) {
515 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
516 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000517 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000518 return New;
519 }
520
521 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
522 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
523 if (OldMethod && NewMethod) {
524 // -- Member function declarations with the same name and the
525 // same parameter types cannot be overloaded if any of them
526 // is a static member function declaration.
527 if (OldMethod->isStatic() || NewMethod->isStatic()) {
528 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
529 Diag(Old->getLocation(), PrevDiag);
530 return New;
531 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000532
533 // C++ [class.mem]p1:
534 // [...] A member shall not be declared twice in the
535 // member-specification, except that a nested class or member
536 // class template can be declared and then later defined.
537 if (OldMethod->getLexicalDeclContext() ==
538 NewMethod->getLexicalDeclContext()) {
539 unsigned NewDiag;
540 if (isa<CXXConstructorDecl>(OldMethod))
541 NewDiag = diag::err_constructor_redeclared;
542 else if (isa<CXXDestructorDecl>(NewMethod))
543 NewDiag = diag::err_destructor_redeclared;
544 else if (isa<CXXConversionDecl>(NewMethod))
545 NewDiag = diag::err_conv_function_redeclared;
546 else
547 NewDiag = diag::err_member_redeclared;
548
549 Diag(New->getLocation(), NewDiag);
550 Diag(Old->getLocation(), PrevDiag);
551 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000552 }
553
554 // (C++98 8.3.5p3):
555 // All declarations for a function shall agree exactly in both the
556 // return type and the parameter-type-list.
557 if (OldQType == NewQType) {
558 // We have a redeclaration.
559 MergeAttributes(New, Old);
560 Redeclaration = true;
561 return MergeCXXFunctionDecl(New, Old);
562 }
563
564 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000565 }
Chris Lattner04421082008-04-08 04:40:51 +0000566
567 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000568 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000569 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000570 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000571 MergeAttributes(New, Old);
572 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000573 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000574 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000575
Steve Naroff837618c2008-01-16 15:01:34 +0000576 // A function that has already been declared has been redeclared or defined
577 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000578
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
580 // TODO: This is totally simplistic. It should handle merging functions
581 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000582 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000583 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000584 return New;
585}
586
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000587/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000588static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000589 if (VD->isFileVarDecl())
590 return (!VD->getInit() &&
591 (VD->getStorageClass() == VarDecl::None ||
592 VD->getStorageClass() == VarDecl::Static));
593 return false;
594}
595
596/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
597/// when dealing with C "tentative" external object definitions (C99 6.9.2).
598void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
599 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000600 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000601
Douglas Gregore21b9942009-01-07 16:34:42 +0000602 // FIXME: I don't think this will actually see all of the
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000603 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000604 for (IdentifierResolver::iterator
605 I = IdResolver.begin(VD->getIdentifier(),
606 VD->getDeclContext(), false/*LookInParentCtx*/),
607 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000608 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000609 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
610
Steve Narofff855e6f2008-08-10 15:20:13 +0000611 // Handle the following case:
612 // int a[10];
613 // int a[]; - the code below makes sure we set the correct type.
614 // int a[11]; - this is an error, size isn't 10.
615 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
616 OldDecl->getType()->isConstantArrayType())
617 VD->setType(OldDecl->getType());
618
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000619 // Check for "tentative" definitions. We can't accomplish this in
620 // MergeVarDecl since the initializer hasn't been attached.
621 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
622 continue;
623
624 // Handle __private_extern__ just like extern.
625 if (OldDecl->getStorageClass() != VarDecl::Extern &&
626 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
627 VD->getStorageClass() != VarDecl::Extern &&
628 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000629 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000630 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000631 }
632 }
633 }
634}
635
Reid Spencer5f016e22007-07-11 17:01:13 +0000636/// MergeVarDecl - We just parsed a variable 'New' which has the same name
637/// and scope as a previous declaration 'Old'. Figure out how to resolve this
638/// situation, merging decls or emitting diagnostics as appropriate.
639///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000640/// Tentative definition rules (C99 6.9.2p2) are checked by
641/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
642/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000643///
Steve Naroffe8043c32008-04-01 23:04:06 +0000644VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 // Verify the old decl was also a variable.
646 VarDecl *Old = dyn_cast<VarDecl>(OldD);
647 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000648 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000649 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000650 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000651 return New;
652 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000653
654 MergeAttributes(New, Old);
655
Reid Spencer5f016e22007-07-11 17:01:13 +0000656 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000657 QualType OldCType = Context.getCanonicalType(Old->getType());
658 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000659 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000660 Diag(New->getLocation(), diag::err_redefinition_different_type)
661 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000662 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000663 return New;
664 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000665 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
666 if (New->getStorageClass() == VarDecl::Static &&
667 (Old->getStorageClass() == VarDecl::None ||
668 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000669 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000670 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000671 return New;
672 }
673 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
674 if (New->getStorageClass() != VarDecl::Static &&
675 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000676 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000677 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000678 return New;
679 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000680 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
681 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000682 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000683 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000684 }
685 return New;
686}
687
Chris Lattner04421082008-04-08 04:40:51 +0000688/// CheckParmsForFunctionDef - Check that the parameters of the given
689/// function are appropriate for the definition of a function. This
690/// takes care of any checks that cannot be performed on the
691/// declaration itself, e.g., that the types of each of the function
692/// parameters are complete.
693bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
694 bool HasInvalidParm = false;
695 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
696 ParmVarDecl *Param = FD->getParamDecl(p);
697
698 // C99 6.7.5.3p4: the parameters in a parameter type list in a
699 // function declarator that is part of a function definition of
700 // that function shall not have incomplete type.
701 if (Param->getType()->isIncompleteType() &&
702 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000703 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000704 << Param->getType();
Chris Lattner04421082008-04-08 04:40:51 +0000705 Param->setInvalidDecl();
706 HasInvalidParm = true;
707 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000708
709 // C99 6.9.1p5: If the declarator includes a parameter type list, the
710 // declaration of each parameter shall include an identifier.
711 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
712 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000713 }
714
715 return HasInvalidParm;
716}
717
Reid Spencer5f016e22007-07-11 17:01:13 +0000718/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
719/// no declarator (e.g. "struct foo;") is parsed.
720Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000721 TagDecl *Tag
722 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
723 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
724 if (!Record->getDeclName() && Record->isDefinition() &&
725 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
726 return BuildAnonymousStructOrUnion(S, DS, Record);
727
728 // Microsoft allows unnamed struct/union fields. Don't complain
729 // about them.
730 // FIXME: Should we support Microsoft's extensions in this area?
731 if (Record->getDeclName() && getLangOptions().Microsoft)
732 return Tag;
733 }
734
Douglas Gregoree159c12009-01-13 23:10:51 +0000735 // Permit typedefs without declarators as a Microsoft extension.
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000736 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregoree159c12009-01-13 23:10:51 +0000737 if (getLangOptions().Microsoft &&
738 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
739 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
740 << DS.getSourceRange();
741 return Tag;
742 }
743
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000744 // FIXME: This diagnostic is emitted even when various previous
745 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
746 // DeclSpec has no means of communicating this information, and the
747 // responsible parser functions are quite far apart.
748 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
749 << DS.getSourceRange();
750 return 0;
751 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000752
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000753 return Tag;
754}
755
756/// InjectAnonymousStructOrUnionMembers - Inject the members of the
757/// anonymous struct or union AnonRecord into the owning context Owner
758/// and scope S. This routine will be invoked just after we realize
759/// that an unnamed union or struct is actually an anonymous union or
760/// struct, e.g.,
761///
762/// @code
763/// union {
764/// int i;
765/// float f;
766/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
767/// // f into the surrounding scope.x
768/// @endcode
769///
770/// This routine is recursive, injecting the names of nested anonymous
771/// structs/unions into the owning context and scope as well.
772bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
773 RecordDecl *AnonRecord) {
774 bool Invalid = false;
775 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
776 FEnd = AnonRecord->field_end();
777 F != FEnd; ++F) {
778 if ((*F)->getDeclName()) {
779 Decl *PrevDecl = LookupDecl((*F)->getDeclName(), Decl::IDNS_Ordinary,
780 S, Owner, false, false, false);
781 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
782 // C++ [class.union]p2:
783 // The names of the members of an anonymous union shall be
784 // distinct from the names of any other entity in the
785 // scope in which the anonymous union is declared.
786 unsigned diagKind
787 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
788 : diag::err_anonymous_struct_member_redecl;
789 Diag((*F)->getLocation(), diagKind)
790 << (*F)->getDeclName();
791 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
792 Invalid = true;
793 } else {
794 // C++ [class.union]p2:
795 // For the purpose of name lookup, after the anonymous union
796 // definition, the members of the anonymous union are
797 // considered to have been defined in the scope in which the
798 // anonymous union is declared.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000799 Owner->insert(*F);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000800 S->AddDecl(*F);
801 IdResolver.AddDecl(*F);
802 }
803 } else if (const RecordType *InnerRecordType
804 = (*F)->getType()->getAsRecordType()) {
805 RecordDecl *InnerRecord = InnerRecordType->getDecl();
806 if (InnerRecord->isAnonymousStructOrUnion())
807 Invalid = Invalid ||
808 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
809 }
810 }
811
812 return Invalid;
813}
814
815/// ActOnAnonymousStructOrUnion - Handle the declaration of an
816/// anonymous structure or union. Anonymous unions are a C++ feature
817/// (C++ [class.union]) and a GNU C extension; anonymous structures
818/// are a GNU C and GNU C++ extension.
819Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
820 RecordDecl *Record) {
821 DeclContext *Owner = Record->getDeclContext();
822
823 // Diagnose whether this anonymous struct/union is an extension.
824 if (Record->isUnion() && !getLangOptions().CPlusPlus)
825 Diag(Record->getLocation(), diag::ext_anonymous_union);
826 else if (!Record->isUnion())
827 Diag(Record->getLocation(), diag::ext_anonymous_struct);
828
829 // C and C++ require different kinds of checks for anonymous
830 // structs/unions.
831 bool Invalid = false;
832 if (getLangOptions().CPlusPlus) {
833 const char* PrevSpec = 0;
834 // C++ [class.union]p3:
835 // Anonymous unions declared in a named namespace or in the
836 // global namespace shall be declared static.
837 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
838 (isa<TranslationUnitDecl>(Owner) ||
839 (isa<NamespaceDecl>(Owner) &&
840 cast<NamespaceDecl>(Owner)->getDeclName()))) {
841 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
842 Invalid = true;
843
844 // Recover by adding 'static'.
845 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
846 }
847 // C++ [class.union]p3:
848 // A storage class is not allowed in a declaration of an
849 // anonymous union in a class scope.
850 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
851 isa<RecordDecl>(Owner)) {
852 Diag(DS.getStorageClassSpecLoc(),
853 diag::err_anonymous_union_with_storage_spec);
854 Invalid = true;
855
856 // Recover by removing the storage specifier.
857 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
858 PrevSpec);
859 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000860
861 // C++ [class.union]p2:
862 // The member-specification of an anonymous union shall only
863 // define non-static data members. [Note: nested types and
864 // functions cannot be declared within an anonymous union. ]
865 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
866 MemEnd = Record->decls_end();
867 Mem != MemEnd; ++Mem) {
868 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
869 // C++ [class.union]p3:
870 // An anonymous union shall not have private or protected
871 // members (clause 11).
872 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
873 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
874 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
875 Invalid = true;
876 }
877 } else if ((*Mem)->isImplicit()) {
878 // Any implicit members are fine.
879 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
880 if (!MemRecord->isAnonymousStructOrUnion() &&
881 MemRecord->getDeclName()) {
882 // This is a nested type declaration.
883 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
884 << (int)Record->isUnion();
885 Invalid = true;
886 }
887 } else {
888 // We have something that isn't a non-static data
889 // member. Complain about it.
890 unsigned DK = diag::err_anonymous_record_bad_member;
891 if (isa<TypeDecl>(*Mem))
892 DK = diag::err_anonymous_record_with_type;
893 else if (isa<FunctionDecl>(*Mem))
894 DK = diag::err_anonymous_record_with_function;
895 else if (isa<VarDecl>(*Mem))
896 DK = diag::err_anonymous_record_with_static;
897 Diag((*Mem)->getLocation(), DK)
898 << (int)Record->isUnion();
899 Invalid = true;
900 }
901 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000902 } else {
903 // FIXME: Check GNU C semantics
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000904 if (Record->isUnion() && !Owner->isRecord()) {
905 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
906 << (int)getLangOptions().CPlusPlus;
907 Invalid = true;
908 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000909 }
910
911 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000912 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
913 << (int)getLangOptions().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000914 Invalid = true;
915 }
916
917 // Create a declaration for this anonymous struct/union.
918 ScopedDecl *Anon = 0;
919 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
920 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
921 /*IdentifierInfo=*/0,
922 Context.getTypeDeclType(Record),
923 /*BitWidth=*/0, /*Mutable=*/false,
924 /*PrevDecl=*/0);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000925 Anon->setAccess(AS_public);
926 if (getLangOptions().CPlusPlus)
927 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000928 } else {
929 VarDecl::StorageClass SC;
930 switch (DS.getStorageClassSpec()) {
931 default: assert(0 && "Unknown storage class!");
932 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
933 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
934 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
935 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
936 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
937 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
938 case DeclSpec::SCS_mutable:
939 // mutable can only appear on non-static class members, so it's always
940 // an error here
941 Diag(Record->getLocation(), diag::err_mutable_nonmember);
942 Invalid = true;
943 SC = VarDecl::None;
944 break;
945 }
946
947 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
948 /*IdentifierInfo=*/0,
949 Context.getTypeDeclType(Record),
950 SC, /*FIXME:LastDeclarator=*/0,
951 DS.getSourceRange().getBegin());
952 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000953 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000954
955 // Add the anonymous struct/union object to the current
956 // context. We'll be referencing this object when we refer to one of
957 // its members.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000958 Owner->addDecl(Anon);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000959
960 // Inject the members of the anonymous struct/union into the owning
961 // context and into the identifier resolver chain for name lookup
962 // purposes.
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000963 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
964 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000965
966 // Mark this as an anonymous struct/union type. Note that we do not
967 // do this until after we have already checked and injected the
968 // members of this anonymous struct/union type, because otherwise
969 // the members could be injected twice: once by DeclContext when it
970 // builds its lookup table, and once by
971 // InjectAnonymousStructOrUnionMembers.
972 Record->setAnonymousStructOrUnion(true);
973
974 if (Invalid)
975 Anon->setInvalidDecl();
976
977 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +0000978}
979
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000980bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
981 bool DirectInit) {
Steve Narofff0090632007-09-02 02:04:30 +0000982 // Get the type before calling CheckSingleAssignmentConstraints(), since
983 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000984 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +0000985
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000986 if (getLangOptions().CPlusPlus) {
987 // FIXME: I dislike this error message. A lot.
988 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
989 return Diag(Init->getSourceRange().getBegin(),
990 diag::err_typecheck_convert_incompatible)
991 << DeclType << Init->getType() << "initializing"
992 << Init->getSourceRange();
993
994 return false;
995 }
Douglas Gregor45920e82008-12-19 17:40:08 +0000996
Chris Lattner5cf216b2008-01-04 18:04:52 +0000997 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
998 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
999 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +00001000}
1001
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001002bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001003 const ArrayType *AT = Context.getAsArrayType(DeclT);
1004
1005 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001006 // C99 6.7.8p14. We have an array of character type with unknown size
1007 // being initialized to a string literal.
1008 llvm::APSInt ConstVal(32);
1009 ConstVal = strLiteral->getByteLength() + 1;
1010 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +00001011 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001012 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001013 } else {
1014 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001015 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001016 // FIXME: Avoid truncation for 64-bit length strings.
1017 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001018 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001019 diag::warn_initializer_string_for_char_array_too_long)
1020 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001021 }
1022 // Set type from "char *" to "constant array of char".
1023 strLiteral->setType(DeclT);
1024 // For now, we always return false (meaning success).
1025 return false;
1026}
1027
1028StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001029 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +00001030 if (AT && AT->getElementType()->isCharType()) {
1031 return dyn_cast<StringLiteral>(Init);
1032 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001033 return 0;
1034}
1035
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001036bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1037 SourceLocation InitLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001038 DeclarationName InitEntity,
1039 bool DirectInit) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +00001040 if (DeclType->isDependentType() || Init->isTypeDependent())
1041 return false;
1042
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001043 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +00001044 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001045 // (8.3.2), shall be initialized by an object, or function, of
1046 // type T or by an object that can be converted into a T.
1047 if (DeclType->isReferenceType())
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001048 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001049
Steve Naroffca107302008-01-21 23:53:58 +00001050 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1051 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001052 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001053 return Diag(InitLoc, diag::err_variable_object_no_init)
1054 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +00001055
Steve Naroff2fdc3742007-12-10 22:44:33 +00001056 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1057 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001058 // FIXME: Handle wide strings
1059 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1060 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +00001061
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001062 // C++ [dcl.init]p14:
1063 // -- If the destination type is a (possibly cv-qualified) class
1064 // type:
1065 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1066 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1067 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1068
1069 // -- If the initialization is direct-initialization, or if it is
1070 // copy-initialization where the cv-unqualified version of the
1071 // source type is the same class as, or a derived class of, the
1072 // class of the destination, constructors are considered.
1073 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1074 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1075 CXXConstructorDecl *Constructor
1076 = PerformInitializationByConstructor(DeclType, &Init, 1,
1077 InitLoc, Init->getSourceRange(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001078 InitEntity,
1079 DirectInit? IK_Direct : IK_Copy);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001080 return Constructor == 0;
1081 }
1082
1083 // -- Otherwise (i.e., for the remaining copy-initialization
1084 // cases), user-defined conversion sequences that can
1085 // convert from the source type to the destination type or
1086 // (when a conversion function is used) to a derived class
1087 // thereof are enumerated as described in 13.3.1.4, and the
1088 // best one is chosen through overload resolution
1089 // (13.3). If the conversion cannot be done or is
1090 // ambiguous, the initialization is ill-formed. The
1091 // function selected is called with the initializer
1092 // expression as its argument; if the function is a
1093 // constructor, the call initializes a temporary of the
1094 // destination type.
1095 // FIXME: We're pretending to do copy elision here; return to
1096 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +00001097 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001098 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001099
Douglas Gregor61366e92008-12-24 00:01:03 +00001100 if (InitEntity)
1101 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1102 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1103 << Init->getType() << Init->getSourceRange();
1104 else
1105 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1106 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1107 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001108 }
1109
Steve Naroff1ac6fdd2008-09-29 20:07:05 +00001110 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +00001111 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001112 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1113 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +00001114
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001115 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregor64bffa92008-11-05 16:20:31 +00001116 } else if (getLangOptions().CPlusPlus) {
1117 // C++ [dcl.init]p14:
1118 // [...] If the class is an aggregate (8.5.1), and the initializer
1119 // is a brace-enclosed list, see 8.5.1.
1120 //
1121 // Note: 8.5.1 is handled below; here, we diagnose the case where
1122 // we have an initializer list and a destination type that is not
1123 // an aggregate.
1124 // FIXME: In C++0x, this is yet another form of initialization.
1125 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1126 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1127 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001128 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00001129 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +00001130 }
Steve Naroff2fdc3742007-12-10 22:44:33 +00001131 }
Eli Friedmane6f058f2008-06-06 19:40:52 +00001132
Steve Naroff0cca7492008-05-01 22:18:59 +00001133 InitListChecker CheckInitList(this, InitList, DeclType);
1134 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +00001135}
1136
Douglas Gregor10bd3682008-11-17 22:58:34 +00001137/// GetNameForDeclarator - Determine the full declaration name for the
1138/// given Declarator.
1139DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1140 switch (D.getKind()) {
1141 case Declarator::DK_Abstract:
1142 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1143 return DeclarationName();
1144
1145 case Declarator::DK_Normal:
1146 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1147 return DeclarationName(D.getIdentifier());
1148
1149 case Declarator::DK_Constructor: {
1150 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1151 Ty = Context.getCanonicalType(Ty);
1152 return Context.DeclarationNames.getCXXConstructorName(Ty);
1153 }
1154
1155 case Declarator::DK_Destructor: {
1156 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1157 Ty = Context.getCanonicalType(Ty);
1158 return Context.DeclarationNames.getCXXDestructorName(Ty);
1159 }
1160
1161 case Declarator::DK_Conversion: {
1162 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1163 Ty = Context.getCanonicalType(Ty);
1164 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1165 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001166
1167 case Declarator::DK_Operator:
1168 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1169 return Context.DeclarationNames.getCXXOperatorName(
1170 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001171 }
1172
1173 assert(false && "Unknown name kind");
1174 return DeclarationName();
1175}
1176
Douglas Gregor584049d2008-12-15 23:53:10 +00001177/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1178/// functions Declaration and Definition are "nearly" matching. This
1179/// heuristic is used to improve diagnostics in the case where an
1180/// out-of-line member function definition doesn't match any
1181/// declaration within the class.
1182static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1183 FunctionDecl *Declaration,
1184 FunctionDecl *Definition) {
1185 if (Declaration->param_size() != Definition->param_size())
1186 return false;
1187 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1188 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1189 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1190
1191 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1192 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1193 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1194 return false;
1195 }
1196
1197 return true;
1198}
1199
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001200Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001201Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1202 bool IsFunctionDefinition) {
Steve Naroff94745042007-09-13 23:52:58 +00001203 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001204 DeclarationName Name = GetNameForDeclarator(D);
1205
Chris Lattnere80a59c2007-07-25 00:24:17 +00001206 // All of these full declarators require an identifier. If it doesn't have
1207 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001208 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001209 if (!D.getInvalidType()) // Reject this if we think it is valid.
1210 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001211 diag::err_declarator_need_ident)
1212 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001213 return 0;
1214 }
1215
Chris Lattner31e05722007-08-26 06:24:45 +00001216 // The scope passed in may not be a decl scope. Zip up the scope tree until
1217 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001218 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1219 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001220 S = S->getParent();
1221
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001222 DeclContext *DC;
1223 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +00001224 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001225 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001226
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001227 // See if this is a redefinition of a variable in the same scope.
1228 if (!D.getCXXScopeSpec().isSet()) {
1229 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +00001230 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001231 } else { // Something like "int foo::x;"
1232 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001233 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001234
1235 // C++ 7.3.1.2p2:
1236 // Members (including explicit specializations of templates) of a named
1237 // namespace can also be defined outside that namespace by explicit
1238 // qualification of the name being defined, provided that the entity being
1239 // defined was already declared in the namespace and the definition appears
1240 // after the point of declaration in a namespace that encloses the
1241 // declarations namespace.
1242 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001243 // Note that we only check the context at this point. We don't yet
1244 // have enough information to make sure that PrevDecl is actually
1245 // the declaration we want to match. For example, given:
1246 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001247 // class X {
1248 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001249 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001250 // };
1251 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001252 // void X::f(int) { } // ill-formed
1253 //
1254 // In this case, PrevDecl will point to the overload set
1255 // containing the two f's declared in X, but neither of them
1256 // matches.
1257 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001258 // The qualifying scope doesn't enclose the original declaration.
1259 // Emit diagnostic based on current scope.
1260 SourceLocation L = D.getIdentifierLoc();
1261 SourceRange R = D.getCXXScopeSpec().getRange();
1262 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001263 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001264 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001265 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001266 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001267 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001268 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001269 }
1270 }
1271
Douglas Gregorf57172b2008-12-08 18:40:42 +00001272 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001273 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001274 InvalidDecl = InvalidDecl
1275 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001276 // Just pretend that we didn't see the previous declaration.
1277 PrevDecl = 0;
1278 }
1279
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001280 // In C++, the previous declaration we find might be a tag type
1281 // (class or enum). In this case, the new declaration will hide the
1282 // tag type.
1283 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1284 PrevDecl = 0;
1285
Chris Lattner41af0932007-11-14 06:34:38 +00001286 QualType R = GetTypeForDeclarator(D, S);
1287 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1288
Reid Spencer5f016e22007-07-11 17:01:13 +00001289 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001290 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1291 InvalidDecl);
Chris Lattner41af0932007-11-14 06:34:38 +00001292 } else if (R.getTypePtr()->isFunctionType()) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001293 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1294 IsFunctionDefinition, InvalidDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 } else {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001296 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1297 InvalidDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001299
1300 if (New == 0)
1301 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001302
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001303 // Set the lexical context. If the declarator has a C++ scope specifier, the
1304 // lexical context will be different from the semantic context.
1305 New->setLexicalDeclContext(CurContext);
1306
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001308 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001309 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001310 // If any semantic error occurred, mark the decl as invalid.
1311 if (D.getInvalidType() || InvalidDecl)
1312 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001313
1314 return New;
1315}
1316
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001317ScopedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001318Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1319 QualType R, ScopedDecl* LastDeclarator,
1320 Decl* PrevDecl, bool& InvalidDecl) {
1321 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1322 if (D.getCXXScopeSpec().isSet()) {
1323 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1324 << D.getCXXScopeSpec().getRange();
1325 InvalidDecl = true;
1326 // Pretend we didn't see the scope specifier.
1327 DC = 0;
1328 }
1329
1330 // Check that there are no default arguments (C++ only).
1331 if (getLangOptions().CPlusPlus)
1332 CheckExtraCXXDefaultArguments(D);
1333
1334 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1335 if (!NewTD) return 0;
1336
1337 // Handle attributes prior to checking for duplicates in MergeVarDecl
1338 ProcessDeclAttributes(NewTD, D);
1339 // Merge the decl with the existing one if appropriate. If the decl is
1340 // in an outer scope, it isn't the same thing.
1341 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1342 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1343 if (NewTD == 0) return 0;
1344 }
1345
1346 if (S->getFnParent() == 0) {
1347 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1348 // then it shall have block scope.
1349 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1350 if (NewTD->getUnderlyingType()->isVariableArrayType())
1351 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1352 else
1353 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1354
1355 InvalidDecl = true;
1356 }
1357 }
1358 return NewTD;
1359}
1360
1361ScopedDecl*
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001362Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1363 QualType R, ScopedDecl* LastDeclarator,
1364 Decl* PrevDecl, bool& InvalidDecl) {
1365 DeclarationName Name = GetNameForDeclarator(D);
1366
1367 // Check that there are no default arguments (C++ only).
1368 if (getLangOptions().CPlusPlus)
1369 CheckExtraCXXDefaultArguments(D);
1370
1371 if (R.getTypePtr()->isObjCInterfaceType()) {
1372 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1373 << D.getIdentifier();
1374 InvalidDecl = true;
1375 }
1376
1377 VarDecl *NewVD;
1378 VarDecl::StorageClass SC;
1379 switch (D.getDeclSpec().getStorageClassSpec()) {
1380 default: assert(0 && "Unknown storage class!");
1381 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1382 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1383 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1384 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1385 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1386 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1387 case DeclSpec::SCS_mutable:
1388 // mutable can only appear on non-static class members, so it's always
1389 // an error here
1390 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1391 InvalidDecl = true;
1392 SC = VarDecl::None;
1393 break;
1394 }
1395
1396 IdentifierInfo *II = Name.getAsIdentifierInfo();
1397 if (!II) {
1398 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1399 << Name.getAsString();
1400 return 0;
1401 }
1402
1403 if (DC->isRecord()) {
1404 // This is a static data member for a C++ class.
1405 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1406 D.getIdentifierLoc(), II,
1407 R, LastDeclarator);
1408 } else {
1409 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1410 if (S->getFnParent() == 0) {
1411 // C99 6.9p2: The storage-class specifiers auto and register shall not
1412 // appear in the declaration specifiers in an external declaration.
1413 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1414 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1415 InvalidDecl = true;
1416 }
1417 }
1418 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1419 II, R, SC, LastDeclarator,
1420 // FIXME: Move to DeclGroup...
1421 D.getDeclSpec().getSourceRange().getBegin());
1422 NewVD->setThreadSpecified(ThreadSpecified);
1423 }
1424 // Handle attributes prior to checking for duplicates in MergeVarDecl
1425 ProcessDeclAttributes(NewVD, D);
1426
1427 // Handle GNU asm-label extension (encoded as an attribute).
1428 if (Expr *E = (Expr*) D.getAsmLabel()) {
1429 // The parser guarantees this is a string.
1430 StringLiteral *SE = cast<StringLiteral>(E);
1431 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1432 SE->getByteLength())));
1433 }
1434
1435 // Emit an error if an address space was applied to decl with local storage.
1436 // This includes arrays of objects with address space qualifiers, but not
1437 // automatic variables that point to other address spaces.
1438 // ISO/IEC TR 18037 S5.1.2
1439 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1440 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1441 InvalidDecl = true;
1442 }
1443 // Merge the decl with the existing one if appropriate. If the decl is
1444 // in an outer scope, it isn't the same thing.
1445 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1446 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1447 // The user tried to define a non-static data member
1448 // out-of-line (C++ [dcl.meaning]p1).
1449 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1450 << D.getCXXScopeSpec().getRange();
1451 NewVD->Destroy(Context);
1452 return 0;
1453 }
1454
1455 NewVD = MergeVarDecl(NewVD, PrevDecl);
1456 if (NewVD == 0) return 0;
1457
1458 if (D.getCXXScopeSpec().isSet()) {
1459 // No previous declaration in the qualifying scope.
1460 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1461 << Name << D.getCXXScopeSpec().getRange();
1462 InvalidDecl = true;
1463 }
1464 }
1465 return NewVD;
1466}
1467
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001468ScopedDecl*
1469Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1470 QualType R, ScopedDecl *LastDeclarator,
1471 Decl* PrevDecl, bool IsFunctionDefinition,
1472 bool& InvalidDecl) {
1473 assert(R.getTypePtr()->isFunctionType());
1474
1475 DeclarationName Name = GetNameForDeclarator(D);
1476 FunctionDecl::StorageClass SC = FunctionDecl::None;
1477 switch (D.getDeclSpec().getStorageClassSpec()) {
1478 default: assert(0 && "Unknown storage class!");
1479 case DeclSpec::SCS_auto:
1480 case DeclSpec::SCS_register:
1481 case DeclSpec::SCS_mutable:
1482 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1483 InvalidDecl = true;
1484 break;
1485 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1486 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1487 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
1488 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1489 }
1490
1491 bool isInline = D.getDeclSpec().isInlineSpecified();
1492 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1493 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1494
1495 FunctionDecl *NewFD;
1496 if (D.getKind() == Declarator::DK_Constructor) {
1497 // This is a C++ constructor declaration.
1498 assert(DC->isRecord() &&
1499 "Constructors can only be declared in a member context");
1500
1501 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1502
1503 // Create the new declaration
1504 NewFD = CXXConstructorDecl::Create(Context,
1505 cast<CXXRecordDecl>(DC),
1506 D.getIdentifierLoc(), Name, R,
1507 isExplicit, isInline,
1508 /*isImplicitlyDeclared=*/false);
1509
1510 if (InvalidDecl)
1511 NewFD->setInvalidDecl();
1512 } else if (D.getKind() == Declarator::DK_Destructor) {
1513 // This is a C++ destructor declaration.
1514 if (DC->isRecord()) {
1515 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1516
1517 NewFD = CXXDestructorDecl::Create(Context,
1518 cast<CXXRecordDecl>(DC),
1519 D.getIdentifierLoc(), Name, R,
1520 isInline,
1521 /*isImplicitlyDeclared=*/false);
1522
1523 if (InvalidDecl)
1524 NewFD->setInvalidDecl();
1525 } else {
1526 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1527
1528 // Create a FunctionDecl to satisfy the function definition parsing
1529 // code path.
1530 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
1531 Name, R, SC, isInline, LastDeclarator,
1532 // FIXME: Move to DeclGroup...
1533 D.getDeclSpec().getSourceRange().getBegin());
1534 InvalidDecl = true;
1535 NewFD->setInvalidDecl();
1536 }
1537 } else if (D.getKind() == Declarator::DK_Conversion) {
1538 if (!DC->isRecord()) {
1539 Diag(D.getIdentifierLoc(),
1540 diag::err_conv_function_not_member);
1541 return 0;
1542 } else {
1543 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1544
1545 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1546 D.getIdentifierLoc(), Name, R,
1547 isInline, isExplicit);
1548
1549 if (InvalidDecl)
1550 NewFD->setInvalidDecl();
1551 }
1552 } else if (DC->isRecord()) {
1553 // This is a C++ method declaration.
1554 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1555 D.getIdentifierLoc(), Name, R,
1556 (SC == FunctionDecl::Static), isInline,
1557 LastDeclarator);
1558 } else {
1559 NewFD = FunctionDecl::Create(Context, DC,
1560 D.getIdentifierLoc(),
1561 Name, R, SC, isInline, LastDeclarator,
1562 // FIXME: Move to DeclGroup...
1563 D.getDeclSpec().getSourceRange().getBegin());
1564 }
1565
1566 // Set the lexical context. If the declarator has a C++
1567 // scope specifier, the lexical context will be different
1568 // from the semantic context.
1569 NewFD->setLexicalDeclContext(CurContext);
1570
1571 // Handle GNU asm-label extension (encoded as an attribute).
1572 if (Expr *E = (Expr*) D.getAsmLabel()) {
1573 // The parser guarantees this is a string.
1574 StringLiteral *SE = cast<StringLiteral>(E);
1575 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1576 SE->getByteLength())));
1577 }
1578
1579 // Copy the parameter declarations from the declarator D to
1580 // the function declaration NewFD, if they are available.
1581 if (D.getNumTypeObjects() > 0) {
1582 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1583
1584 // Create Decl objects for each parameter, adding them to the
1585 // FunctionDecl.
1586 llvm::SmallVector<ParmVarDecl*, 16> Params;
1587
1588 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1589 // function that takes no arguments, not a function that takes a
1590 // single void argument.
1591 // We let through "const void" here because Sema::GetTypeForDeclarator
1592 // already checks for that case.
1593 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1594 FTI.ArgInfo[0].Param &&
1595 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1596 // empty arg list, don't push any params.
1597 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1598
1599 // In C++, the empty parameter-type-list must be spelled "void"; a
1600 // typedef of void is not permitted.
1601 if (getLangOptions().CPlusPlus &&
1602 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1603 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1604 }
1605 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1606 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1607 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1608 }
1609
1610 NewFD->setParams(Context, &Params[0], Params.size());
1611 } else if (R->getAsTypedefType()) {
1612 // When we're declaring a function with a typedef, as in the
1613 // following example, we'll need to synthesize (unnamed)
1614 // parameters for use in the declaration.
1615 //
1616 // @code
1617 // typedef void fn(int);
1618 // fn f;
1619 // @endcode
1620 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1621 if (!FT) {
1622 // This is a typedef of a function with no prototype, so we
1623 // don't need to do anything.
1624 } else if ((FT->getNumArgs() == 0) ||
1625 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1626 FT->getArgType(0)->isVoidType())) {
1627 // This is a zero-argument function. We don't need to do anything.
1628 } else {
1629 // Synthesize a parameter for each argument type.
1630 llvm::SmallVector<ParmVarDecl*, 16> Params;
1631 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1632 ArgType != FT->arg_type_end(); ++ArgType) {
1633 Params.push_back(ParmVarDecl::Create(Context, DC,
1634 SourceLocation(), 0,
1635 *ArgType, VarDecl::None,
1636 0, 0));
1637 }
1638
1639 NewFD->setParams(Context, &Params[0], Params.size());
1640 }
1641 }
1642
1643 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1644 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1645 else if (isa<CXXDestructorDecl>(NewFD)) {
1646 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1647 Record->setUserDeclaredDestructor(true);
1648 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1649 // user-defined destructor.
1650 Record->setPOD(false);
1651 } else if (CXXConversionDecl *Conversion =
1652 dyn_cast<CXXConversionDecl>(NewFD))
1653 ActOnConversionDeclarator(Conversion);
1654
1655 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1656 if (NewFD->isOverloadedOperator() &&
1657 CheckOverloadedOperatorDeclaration(NewFD))
1658 NewFD->setInvalidDecl();
1659
1660 // Merge the decl with the existing one if appropriate. Since C functions
1661 // are in a flat namespace, make sure we consider decls in outer scopes.
1662 if (PrevDecl &&
1663 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1664 bool Redeclaration = false;
1665
1666 // If C++, determine whether NewFD is an overload of PrevDecl or
1667 // a declaration that requires merging. If it's an overload,
1668 // there's no more work to do here; we'll just add the new
1669 // function to the scope.
1670 OverloadedFunctionDecl::function_iterator MatchedDecl;
1671 if (!getLangOptions().CPlusPlus ||
1672 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1673 Decl *OldDecl = PrevDecl;
1674
1675 // If PrevDecl was an overloaded function, extract the
1676 // FunctionDecl that matched.
1677 if (isa<OverloadedFunctionDecl>(PrevDecl))
1678 OldDecl = *MatchedDecl;
1679
1680 // NewFD and PrevDecl represent declarations that need to be
1681 // merged.
1682 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1683
1684 if (NewFD == 0) return 0;
1685 if (Redeclaration) {
1686 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1687
1688 // An out-of-line member function declaration must also be a
1689 // definition (C++ [dcl.meaning]p1).
1690 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1691 !InvalidDecl) {
1692 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1693 << D.getCXXScopeSpec().getRange();
1694 NewFD->setInvalidDecl();
1695 }
1696 }
1697 }
1698
1699 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1700 // The user tried to provide an out-of-line definition for a
1701 // member function, but there was no such member function
1702 // declared (C++ [class.mfct]p2). For example:
1703 //
1704 // class X {
1705 // void f() const;
1706 // };
1707 //
1708 // void X::f() { } // ill-formed
1709 //
1710 // Complain about this problem, and attempt to suggest close
1711 // matches (e.g., those that differ only in cv-qualifiers and
1712 // whether the parameter types are references).
1713 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1714 << cast<CXXRecordDecl>(DC)->getDeclName()
1715 << D.getCXXScopeSpec().getRange();
1716 InvalidDecl = true;
1717
1718 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1719 if (!PrevDecl) {
1720 // Nothing to suggest.
1721 } else if (OverloadedFunctionDecl *Ovl
1722 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1723 for (OverloadedFunctionDecl::function_iterator
1724 Func = Ovl->function_begin(),
1725 FuncEnd = Ovl->function_end();
1726 Func != FuncEnd; ++Func) {
1727 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1728 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1729
1730 }
1731 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1732 // Suggest this no matter how mismatched it is; it's the only
1733 // thing we have.
1734 unsigned diag;
1735 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1736 diag = diag::note_member_def_close_match;
1737 else if (Method->getBody())
1738 diag = diag::note_previous_definition;
1739 else
1740 diag = diag::note_previous_declaration;
1741 Diag(Method->getLocation(), diag);
1742 }
1743
1744 PrevDecl = 0;
1745 }
1746 }
1747 // Handle attributes. We need to have merged decls when handling attributes
1748 // (for example to check for conflicts, etc).
1749 ProcessDeclAttributes(NewFD, D);
1750
1751 if (getLangOptions().CPlusPlus) {
1752 // In C++, check default arguments now that we have merged decls.
1753 CheckCXXDefaultArguments(NewFD);
1754
1755 // An out-of-line member function declaration must also be a
1756 // definition (C++ [dcl.meaning]p1).
1757 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1758 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1759 << D.getCXXScopeSpec().getRange();
1760 InvalidDecl = true;
1761 }
1762 }
1763 return NewFD;
1764}
1765
Steve Naroff6594a702008-10-27 11:34:16 +00001766void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001767 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1768 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001769}
1770
Eli Friedmanc594b322008-05-20 13:48:25 +00001771bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1772 switch (Init->getStmtClass()) {
1773 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001774 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001775 return true;
1776 case Expr::ParenExprClass: {
1777 const ParenExpr* PE = cast<ParenExpr>(Init);
1778 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1779 }
1780 case Expr::CompoundLiteralExprClass:
1781 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor1a49af92009-01-06 05:10:23 +00001782 case Expr::DeclRefExprClass:
1783 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001784 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001785 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1786 if (VD->hasGlobalStorage())
1787 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001788 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001789 return true;
1790 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001791 if (isa<FunctionDecl>(D))
1792 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001793 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001794 return true;
1795 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001796 case Expr::MemberExprClass: {
1797 const MemberExpr *M = cast<MemberExpr>(Init);
1798 if (M->isArrow())
1799 return CheckAddressConstantExpression(M->getBase());
1800 return CheckAddressConstantExpressionLValue(M->getBase());
1801 }
1802 case Expr::ArraySubscriptExprClass: {
1803 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1804 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1805 return CheckAddressConstantExpression(ASE->getBase()) ||
1806 CheckArithmeticConstantExpression(ASE->getIdx());
1807 }
1808 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001809 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001810 return false;
1811 case Expr::UnaryOperatorClass: {
1812 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1813
1814 // C99 6.6p9
1815 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001816 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001817
Steve Naroff6594a702008-10-27 11:34:16 +00001818 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001819 return true;
1820 }
1821 }
1822}
1823
1824bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1825 switch (Init->getStmtClass()) {
1826 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001827 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001828 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001829 case Expr::ParenExprClass:
1830 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001831 case Expr::StringLiteralClass:
1832 case Expr::ObjCStringLiteralClass:
1833 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001834 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001835 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001836 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1837 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1838 Builtin::BI__builtin___CFStringMakeConstantString)
1839 return false;
1840
Steve Naroff6594a702008-10-27 11:34:16 +00001841 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001842 return true;
1843
Eli Friedmanc594b322008-05-20 13:48:25 +00001844 case Expr::UnaryOperatorClass: {
1845 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1846
1847 // C99 6.6p9
1848 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1849 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1850
1851 if (Exp->getOpcode() == UnaryOperator::Extension)
1852 return CheckAddressConstantExpression(Exp->getSubExpr());
1853
Steve Naroff6594a702008-10-27 11:34:16 +00001854 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001855 return true;
1856 }
1857 case Expr::BinaryOperatorClass: {
1858 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1859 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1860
1861 Expr *PExp = Exp->getLHS();
1862 Expr *IExp = Exp->getRHS();
1863 if (IExp->getType()->isPointerType())
1864 std::swap(PExp, IExp);
1865
1866 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1867 return CheckAddressConstantExpression(PExp) ||
1868 CheckArithmeticConstantExpression(IExp);
1869 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001870 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001871 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001872 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001873 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1874 // Check for implicit promotion
1875 if (SubExpr->getType()->isFunctionType() ||
1876 SubExpr->getType()->isArrayType())
1877 return CheckAddressConstantExpressionLValue(SubExpr);
1878 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001879
1880 // Check for pointer->pointer cast
1881 if (SubExpr->getType()->isPointerType())
1882 return CheckAddressConstantExpression(SubExpr);
1883
Eli Friedmanc3f07642008-08-25 20:46:57 +00001884 if (SubExpr->getType()->isIntegralType()) {
1885 // Check for the special-case of a pointer->int->pointer cast;
1886 // this isn't standard, but some code requires it. See
1887 // PR2720 for an example.
1888 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1889 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1890 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1891 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1892 if (IntWidth >= PointerWidth) {
1893 return CheckAddressConstantExpression(SubCast->getSubExpr());
1894 }
1895 }
1896 }
1897 }
1898 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001899 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001900 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001901
Steve Naroff6594a702008-10-27 11:34:16 +00001902 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001903 return true;
1904 }
1905 case Expr::ConditionalOperatorClass: {
1906 // FIXME: Should we pedwarn here?
1907 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1908 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001909 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001910 return true;
1911 }
1912 if (CheckArithmeticConstantExpression(Exp->getCond()))
1913 return true;
1914 if (Exp->getLHS() &&
1915 CheckAddressConstantExpression(Exp->getLHS()))
1916 return true;
1917 return CheckAddressConstantExpression(Exp->getRHS());
1918 }
1919 case Expr::AddrLabelExprClass:
1920 return false;
1921 }
1922}
1923
Eli Friedman4caf0552008-06-09 05:05:07 +00001924static const Expr* FindExpressionBaseAddress(const Expr* E);
1925
1926static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1927 switch (E->getStmtClass()) {
1928 default:
1929 return E;
1930 case Expr::ParenExprClass: {
1931 const ParenExpr* PE = cast<ParenExpr>(E);
1932 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1933 }
1934 case Expr::MemberExprClass: {
1935 const MemberExpr *M = cast<MemberExpr>(E);
1936 if (M->isArrow())
1937 return FindExpressionBaseAddress(M->getBase());
1938 return FindExpressionBaseAddressLValue(M->getBase());
1939 }
1940 case Expr::ArraySubscriptExprClass: {
1941 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1942 return FindExpressionBaseAddress(ASE->getBase());
1943 }
1944 case Expr::UnaryOperatorClass: {
1945 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1946
1947 if (Exp->getOpcode() == UnaryOperator::Deref)
1948 return FindExpressionBaseAddress(Exp->getSubExpr());
1949
1950 return E;
1951 }
1952 }
1953}
1954
1955static const Expr* FindExpressionBaseAddress(const Expr* E) {
1956 switch (E->getStmtClass()) {
1957 default:
1958 return E;
1959 case Expr::ParenExprClass: {
1960 const ParenExpr* PE = cast<ParenExpr>(E);
1961 return FindExpressionBaseAddress(PE->getSubExpr());
1962 }
1963 case Expr::UnaryOperatorClass: {
1964 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1965
1966 // C99 6.6p9
1967 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1968 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1969
1970 if (Exp->getOpcode() == UnaryOperator::Extension)
1971 return FindExpressionBaseAddress(Exp->getSubExpr());
1972
1973 return E;
1974 }
1975 case Expr::BinaryOperatorClass: {
1976 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1977
1978 Expr *PExp = Exp->getLHS();
1979 Expr *IExp = Exp->getRHS();
1980 if (IExp->getType()->isPointerType())
1981 std::swap(PExp, IExp);
1982
1983 return FindExpressionBaseAddress(PExp);
1984 }
1985 case Expr::ImplicitCastExprClass: {
1986 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1987
1988 // Check for implicit promotion
1989 if (SubExpr->getType()->isFunctionType() ||
1990 SubExpr->getType()->isArrayType())
1991 return FindExpressionBaseAddressLValue(SubExpr);
1992
1993 // Check for pointer->pointer cast
1994 if (SubExpr->getType()->isPointerType())
1995 return FindExpressionBaseAddress(SubExpr);
1996
1997 // We assume that we have an arithmetic expression here;
1998 // if we don't, we'll figure it out later
1999 return 0;
2000 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002001 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00002002 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2003
2004 // Check for pointer->pointer cast
2005 if (SubExpr->getType()->isPointerType())
2006 return FindExpressionBaseAddress(SubExpr);
2007
2008 // We assume that we have an arithmetic expression here;
2009 // if we don't, we'll figure it out later
2010 return 0;
2011 }
2012 }
2013}
2014
Anders Carlsson51fe9962008-11-22 21:04:56 +00002015bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00002016 switch (Init->getStmtClass()) {
2017 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002018 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002019 return true;
2020 case Expr::ParenExprClass: {
2021 const ParenExpr* PE = cast<ParenExpr>(Init);
2022 return CheckArithmeticConstantExpression(PE->getSubExpr());
2023 }
2024 case Expr::FloatingLiteralClass:
2025 case Expr::IntegerLiteralClass:
2026 case Expr::CharacterLiteralClass:
2027 case Expr::ImaginaryLiteralClass:
2028 case Expr::TypesCompatibleExprClass:
2029 case Expr::CXXBoolLiteralExprClass:
2030 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00002031 case Expr::CallExprClass:
2032 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002033 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002034
2035 // Allow any constant foldable calls to builtins.
2036 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00002037 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002038
Steve Naroff6594a702008-10-27 11:34:16 +00002039 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002040 return true;
2041 }
Douglas Gregor1a49af92009-01-06 05:10:23 +00002042 case Expr::DeclRefExprClass:
2043 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002044 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2045 if (isa<EnumConstantDecl>(D))
2046 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002047 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002048 return true;
2049 }
2050 case Expr::CompoundLiteralExprClass:
2051 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2052 // but vectors are allowed to be magic.
2053 if (Init->getType()->isVectorType())
2054 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002055 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002056 return true;
2057 case Expr::UnaryOperatorClass: {
2058 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2059
2060 switch (Exp->getOpcode()) {
2061 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2062 // See C99 6.6p3.
2063 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002064 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002065 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002066 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00002067 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2068 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002069 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002070 return true;
2071 case UnaryOperator::Extension:
2072 case UnaryOperator::LNot:
2073 case UnaryOperator::Plus:
2074 case UnaryOperator::Minus:
2075 case UnaryOperator::Not:
2076 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2077 }
2078 }
Sebastian Redl05189992008-11-11 17:56:53 +00002079 case Expr::SizeOfAlignOfExprClass: {
2080 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002081 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00002082 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00002083 return false;
2084 // alignof always evaluates to a constant.
2085 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00002086 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00002087 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002088 return true;
2089 }
2090 return false;
2091 }
2092 case Expr::BinaryOperatorClass: {
2093 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2094
2095 if (Exp->getLHS()->getType()->isArithmeticType() &&
2096 Exp->getRHS()->getType()->isArithmeticType()) {
2097 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2098 CheckArithmeticConstantExpression(Exp->getRHS());
2099 }
2100
Eli Friedman4caf0552008-06-09 05:05:07 +00002101 if (Exp->getLHS()->getType()->isPointerType() &&
2102 Exp->getRHS()->getType()->isPointerType()) {
2103 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2104 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2105
2106 // Only allow a null (constant integer) base; we could
2107 // allow some additional cases if necessary, but this
2108 // is sufficient to cover offsetof-like constructs.
2109 if (!LHSBase && !RHSBase) {
2110 return CheckAddressConstantExpression(Exp->getLHS()) ||
2111 CheckAddressConstantExpression(Exp->getRHS());
2112 }
2113 }
2114
Steve Naroff6594a702008-10-27 11:34:16 +00002115 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002116 return true;
2117 }
2118 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002119 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002120 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00002121 if (SubExpr->getType()->isArithmeticType())
2122 return CheckArithmeticConstantExpression(SubExpr);
2123
Eli Friedmanb529d832008-09-02 09:37:00 +00002124 if (SubExpr->getType()->isPointerType()) {
2125 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2126 // If the pointer has a null base, this is an offsetof-like construct
2127 if (!Base)
2128 return CheckAddressConstantExpression(SubExpr);
2129 }
2130
Steve Naroff6594a702008-10-27 11:34:16 +00002131 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00002132 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002133 }
2134 case Expr::ConditionalOperatorClass: {
2135 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00002136
2137 // If GNU extensions are disabled, we require all operands to be arithmetic
2138 // constant expressions.
2139 if (getLangOptions().NoExtensions) {
2140 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2141 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2142 CheckArithmeticConstantExpression(Exp->getRHS());
2143 }
2144
2145 // Otherwise, we have to emulate some of the behavior of fold here.
2146 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2147 // because it can constant fold things away. To retain compatibility with
2148 // GCC code, we see if we can fold the condition to a constant (which we
2149 // should always be able to do in theory). If so, we only require the
2150 // specified arm of the conditional to be a constant. This is a horrible
2151 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002152 Expr::EvalResult EvalResult;
2153 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2154 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002155 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00002156 // won't be able to either. Use it to emit the diagnostic though.
2157 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002158 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00002159 return Res;
2160 }
2161
2162 // Verify that the side following the condition is also a constant.
2163 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002164 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00002165 std::swap(TrueSide, FalseSide);
2166
2167 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00002168 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00002169
2170 // Okay, the evaluated side evaluates to a constant, so we accept this.
2171 // Check to see if the other side is obviously not a constant. If so,
2172 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002173 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00002174 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002175 diag::ext_typecheck_expression_not_constant_but_accepted)
2176 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00002177 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00002178 }
2179 }
2180}
2181
2182bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002183 Expr::EvalResult Result;
2184
Nuno Lopes9a979c32008-07-07 16:46:50 +00002185 Init = Init->IgnoreParens();
2186
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002187 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
2188 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) {
Steve Naroff8e74c932007-09-13 21:41:19 +00002298 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2299 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002300 RealDecl->setInvalidDecl();
2301 return;
2302 }
Steve Naroffbb204692007-09-12 14:07:44 +00002303 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002304 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002305 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002306 if (VDecl->isBlockVarDecl()) {
2307 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002308 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002309 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002310 VDecl->setInvalidDecl();
2311 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002312 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002313 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002314 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002315
2316 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2317 if (!getLangOptions().CPlusPlus) {
2318 if (SC == VarDecl::Static) // C99 6.7.8p4.
2319 CheckForConstantInitializer(Init, DclT);
2320 }
Steve Naroffbb204692007-09-12 14:07:44 +00002321 }
Steve Naroff248a7532008-04-15 22:42:06 +00002322 } else if (VDecl->isFileVarDecl()) {
2323 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002324 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002325 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002326 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002327 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002328 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002329
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002330 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2331 if (!getLangOptions().CPlusPlus) {
2332 // C99 6.7.8p4. All file scoped initializers need to be constant.
2333 CheckForConstantInitializer(Init, DclT);
2334 }
Steve Naroffbb204692007-09-12 14:07:44 +00002335 }
2336 // If the type changed, it means we had an incomplete type that was
2337 // completed by the initializer. For example:
2338 // int ary[] = { 1, 3, 5 };
2339 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002340 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002341 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002342 Init->setType(DclT);
2343 }
Steve Naroffbb204692007-09-12 14:07:44 +00002344
2345 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002346 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002347 return;
2348}
2349
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002350void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2351 Decl *RealDecl = static_cast<Decl *>(dcl);
2352
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002353 // If there is no declaration, there was an error parsing it. Just ignore it.
2354 if (RealDecl == 0)
2355 return;
2356
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002357 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2358 QualType Type = Var->getType();
2359 // C++ [dcl.init.ref]p3:
2360 // The initializer can be omitted for a reference only in a
2361 // parameter declaration (8.3.5), in the declaration of a
2362 // function return type, in the declaration of a class member
2363 // within its class declaration (9.2), and where the extern
2364 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002365 if (Type->isReferenceType() &&
2366 Var->getStorageClass() != VarDecl::Extern &&
2367 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002368 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002369 << Var->getDeclName()
2370 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002371 Var->setInvalidDecl();
2372 return;
2373 }
2374
2375 // C++ [dcl.init]p9:
2376 //
2377 // If no initializer is specified for an object, and the object
2378 // is of (possibly cv-qualified) non-POD class type (or array
2379 // thereof), the object shall be default-initialized; if the
2380 // object is of const-qualified type, the underlying class type
2381 // shall have a user-declared default constructor.
2382 if (getLangOptions().CPlusPlus) {
2383 QualType InitType = Type;
2384 if (const ArrayType *Array = Context.getAsArrayType(Type))
2385 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002386 if (Var->getStorageClass() != VarDecl::Extern &&
2387 Var->getStorageClass() != VarDecl::PrivateExtern &&
2388 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002389 const CXXConstructorDecl *Constructor
2390 = PerformInitializationByConstructor(InitType, 0, 0,
2391 Var->getLocation(),
2392 SourceRange(Var->getLocation(),
2393 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002394 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002395 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002396 if (!Constructor)
2397 Var->setInvalidDecl();
2398 }
2399 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002400
Douglas Gregor818ce482008-10-29 13:50:18 +00002401#if 0
2402 // FIXME: Temporarily disabled because we are not properly parsing
2403 // linkage specifications on declarations, e.g.,
2404 //
2405 // extern "C" const CGPoint CGPointerZero;
2406 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002407 // C++ [dcl.init]p9:
2408 //
2409 // If no initializer is specified for an object, and the
2410 // object is of (possibly cv-qualified) non-POD class type (or
2411 // array thereof), the object shall be default-initialized; if
2412 // the object is of const-qualified type, the underlying class
2413 // type shall have a user-declared default
2414 // constructor. Otherwise, if no initializer is specified for
2415 // an object, the object and its subobjects, if any, have an
2416 // indeterminate initial value; if the object or any of its
2417 // subobjects are of const-qualified type, the program is
2418 // ill-formed.
2419 //
2420 // This isn't technically an error in C, so we don't diagnose it.
2421 //
2422 // FIXME: Actually perform the POD/user-defined default
2423 // constructor check.
2424 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002425 Context.getCanonicalType(Type).isConstQualified() &&
2426 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002427 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2428 << Var->getName()
2429 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002430#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002431 }
2432}
2433
Reid Spencer5f016e22007-07-11 17:01:13 +00002434/// The declarators are chained together backwards, reverse the list.
2435Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2436 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002437 Decl *GroupDecl = static_cast<Decl*>(group);
2438 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002439 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002440
2441 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2442 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002443 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002444 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002445 else { // reverse the list.
2446 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00002447 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002448 Group->setNextDeclarator(NewGroup);
2449 NewGroup = Group;
2450 Group = Next;
2451 }
2452 }
2453 // Perform semantic analysis that depends on having fully processed both
2454 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00002455 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002456 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2457 if (!IDecl)
2458 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002459 QualType T = IDecl->getType();
2460
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002461 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002462 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002463
2464 // FIXME: This won't give the correct result for
2465 // int a[10][n];
2466 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002467 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002468 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2469 SizeRange;
2470
Eli Friedmanc5773c42008-02-15 18:16:39 +00002471 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002472 } else {
2473 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2474 // static storage duration, it shall not have a variable length array.
2475 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002476 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2477 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002478 IDecl->setInvalidDecl();
2479 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002480 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2481 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002482 IDecl->setInvalidDecl();
2483 }
2484 }
2485 } else if (T->isVariablyModifiedType()) {
2486 if (IDecl->isFileVarDecl()) {
2487 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2488 IDecl->setInvalidDecl();
2489 } else {
2490 if (IDecl->getStorageClass() == VarDecl::Extern) {
2491 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2492 IDecl->setInvalidDecl();
2493 }
Steve Naroffbb204692007-09-12 14:07:44 +00002494 }
2495 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002496
Steve Naroffbb204692007-09-12 14:07:44 +00002497 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2498 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002499 if (IDecl->isBlockVarDecl() &&
2500 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002501 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002502 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002503 IDecl->setInvalidDecl();
2504 }
2505 }
2506 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2507 // object that has file scope without an initializer, and without a
2508 // storage-class specifier or with the storage-class specifier "static",
2509 // constitutes a tentative definition. Note: A tentative definition with
2510 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002511 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002512 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002513 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2514 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002515 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002516 // C99 6.9.2p3: If the declaration of an identifier for an object is
2517 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2518 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002519 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002520 IDecl->setInvalidDecl();
2521 }
2522 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002523 if (IDecl->isFileVarDecl())
2524 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002525 }
2526 return NewGroup;
2527}
Steve Naroffe1223f72007-08-28 03:03:08 +00002528
Chris Lattner04421082008-04-08 04:40:51 +00002529/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2530/// to introduce parameters into function prototype scope.
2531Sema::DeclTy *
2532Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002533 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002534
Chris Lattner04421082008-04-08 04:40:51 +00002535 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002536 VarDecl::StorageClass StorageClass = VarDecl::None;
2537 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2538 StorageClass = VarDecl::Register;
2539 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002540 Diag(DS.getStorageClassSpecLoc(),
2541 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002542 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002543 }
2544 if (DS.isThreadSpecified()) {
2545 Diag(DS.getThreadSpecLoc(),
2546 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002547 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002548 }
2549
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002550 // Check that there are no default arguments inside the type of this
2551 // parameter (C++ only).
2552 if (getLangOptions().CPlusPlus)
2553 CheckExtraCXXDefaultArguments(D);
2554
Chris Lattner04421082008-04-08 04:40:51 +00002555 // In this context, we *do not* check D.getInvalidType(). If the declarator
2556 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2557 // though it will not reflect the user specified type.
2558 QualType parmDeclType = GetTypeForDeclarator(D, S);
2559
2560 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2561
Reid Spencer5f016e22007-07-11 17:01:13 +00002562 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2563 // Can this happen for params? We already checked that they don't conflict
2564 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002565 IdentifierInfo *II = D.getIdentifier();
2566 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregorf57172b2008-12-08 18:40:42 +00002567 if (PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002568 // 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)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002573 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002574
2575 // Recover by removing the name
2576 II = 0;
2577 D.SetIdentifier(0, D.getIdentifierLoc());
2578 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002579 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002580
2581 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2582 // Doing the promotion here has a win and a loss. The win is the type for
2583 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2584 // code generator). The loss is the orginal type isn't preserved. For example:
2585 //
2586 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2587 // int blockvardecl[5];
2588 // sizeof(parmvardecl); // size == 4
2589 // sizeof(blockvardecl); // size == 20
2590 // }
2591 //
2592 // For expressions, all implicit conversions are captured using the
2593 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2594 //
2595 // FIXME: If a source translation tool needs to see the original type, then
2596 // we need to consider storing both types (in ParmVarDecl)...
2597 //
Chris Lattnere6327742008-04-02 05:18:44 +00002598 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002599 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002600 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002601 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002602 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002603
Chris Lattner04421082008-04-08 04:40:51 +00002604 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2605 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002606 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002607 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002608
Chris Lattner04421082008-04-08 04:40:51 +00002609 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002610 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002611
Douglas Gregor584049d2008-12-15 23:53:10 +00002612 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2613 if (D.getCXXScopeSpec().isSet()) {
2614 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2615 << D.getCXXScopeSpec().getRange();
2616 New->setInvalidDecl();
2617 }
2618
Douglas Gregor44b43212008-12-11 16:49:14 +00002619 // Add the parameter declaration into this scope.
2620 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002621 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002622 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002623
Chris Lattner3ff30c82008-06-29 00:02:00 +00002624 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002625 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002626
Reid Spencer5f016e22007-07-11 17:01:13 +00002627}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002628
Chris Lattnerb652cea2007-10-09 17:14:05 +00002629Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002630 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
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);
2650 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002651 }
2652 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002653 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002654 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002655 }
2656
Douglas Gregor584049d2008-12-15 23:53:10 +00002657 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002658
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002659 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002660 ActOnDeclarator(ParentScope, D, 0,
2661 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002662}
2663
2664Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2665 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002666 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002667
2668 // See if this is a redefinition.
2669 const FunctionDecl *Definition;
2670 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002671 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002672 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002673 }
2674
Douglas Gregor44b43212008-12-11 16:49:14 +00002675 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002676
Chris Lattner04421082008-04-08 04:40:51 +00002677 // Check the validity of our function parameters
2678 CheckParmsForFunctionDef(FD);
2679
2680 // Introduce our parameters into the function scope
2681 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2682 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00002683 Param->setOwningFunction(FD);
2684
Chris Lattner04421082008-04-08 04:40:51 +00002685 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002686 if (Param->getIdentifier())
2687 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002688 }
Chris Lattner04421082008-04-08 04:40:51 +00002689
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002690 // Checking attributes of current function definition
2691 // dllimport attribute.
2692 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2693 // dllimport attribute cannot be applied to definition.
2694 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2695 Diag(FD->getLocation(),
2696 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2697 << "dllimport";
2698 FD->setInvalidDecl();
2699 return FD;
2700 } else {
2701 // If a symbol previously declared dllimport is later defined, the
2702 // attribute is ignored in subsequent references, and a warning is
2703 // emitted.
2704 Diag(FD->getLocation(),
2705 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2706 << FD->getNameAsCString() << "dllimport";
2707 }
2708 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002709 return FD;
2710}
2711
Sebastian Redl798d1192008-12-13 16:23:55 +00002712Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002713 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002714 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002715 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002716 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002717 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002718 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002719 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002720 } else
2721 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002722 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002723 // Verify and clean out per-function state.
2724
2725 // Check goto/label use.
2726 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2727 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2728 // Verify that we have no forward references left. If so, there was a goto
2729 // or address of a label taken, but no definition of it. Label fwd
2730 // definitions are indicated with a null substmt.
2731 if (I->second->getSubStmt() == 0) {
2732 LabelStmt *L = I->second;
2733 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002734 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002735
2736 // At this point, we have gotos that use the bogus label. Stitch it into
2737 // the function body so that they aren't leaked and that the AST is well
2738 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002739 if (Body) {
2740 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002741 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002742 } else {
2743 // The whole function wasn't parsed correctly, just delete this.
2744 delete L;
2745 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002746 }
2747 }
2748 LabelMap.clear();
2749
Steve Naroffd6d054d2007-11-11 23:20:51 +00002750 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002751}
2752
Reid Spencer5f016e22007-07-11 17:01:13 +00002753/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2754/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002755ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2756 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002757 // Extension in C99. Legal in C90, but warn about it.
2758 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002759 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002760 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002761 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002762
2763 // FIXME: handle stuff like:
2764 // void foo() { extern float X(); }
2765 // void bar() { X(); } <-- implicit decl for X in another scope.
2766
2767 // Set a Declarator for the implicit definition: int foo();
2768 const char *Dummy;
2769 DeclSpec DS;
2770 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2771 Error = Error; // Silence warning.
2772 assert(!Error && "Error setting up implicit decl!");
2773 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002774 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002775 D.SetIdentifier(&II, Loc);
2776
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002777 // Insert this function into translation-unit scope.
2778
2779 DeclContext *PrevDC = CurContext;
2780 CurContext = Context.getTranslationUnitDecl();
2781
Steve Naroffe2ef8152008-04-04 14:32:09 +00002782 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002783 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002784 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002785
2786 CurContext = PrevDC;
2787
Steve Naroffe2ef8152008-04-04 14:32:09 +00002788 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002789}
2790
2791
Chris Lattner41af0932007-11-14 06:34:38 +00002792TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002793 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002794 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002795 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002796
2797 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002798 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2799 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002800 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002801 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002802 if (D.getInvalidType())
2803 NewTD->setInvalidDecl();
2804 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002805}
2806
Steve Naroff08d92e42007-09-15 18:49:24 +00002807/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002808/// former case, Name will be non-null. In the later case, Name will be null.
2809/// TagType indicates what kind of tag this is. TK indicates whether this is a
2810/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002811Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002812 SourceLocation KWLoc, const CXXScopeSpec &SS,
2813 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +00002814 AttributeList *Attr,
2815 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002816 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002817 assert((Name != 0 || TK == TK_Definition) &&
2818 "Nameless record must be a definition!");
2819
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002820 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002821 switch (TagType) {
2822 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002823 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2824 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2825 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2826 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002827 }
2828
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002829 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002830 DeclContext *DC = CurContext;
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002831 DeclContext *LexicalContext = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002832 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002833
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002834 if (Name && SS.isNotEmpty()) {
2835 // We have a nested-name tag ('struct foo::bar').
2836
2837 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002838 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002839 Name = 0;
2840 goto CreateNewDecl;
2841 }
2842
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002843 DC = static_cast<DeclContext*>(SS.getScopeRep());
2844 // Look-up name inside 'foo::'.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002845 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC)
2846 .getAsDecl());
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002847
2848 // A tag 'foo::bar' must already exist.
2849 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002850 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002851 Name = 0;
2852 goto CreateNewDecl;
2853 }
2854 } else {
2855 // If this is a named struct, check to see if there was a previous forward
2856 // declaration or definition.
2857 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002858 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S)
2859 .getAsDecl());
Douglas Gregor72de6672009-01-08 20:45:30 +00002860
2861 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2862 // FIXME: This makes sure that we ignore the contexts associated
2863 // with C structs, unions, and enums when looking for a matching
2864 // tag declaration or definition. See the similar lookup tweak
2865 // in Sema::LookupDecl; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002866 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2867 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +00002868 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002869 }
2870
Douglas Gregorf57172b2008-12-08 18:40:42 +00002871 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002872 // Maybe we will complain about the shadowed template parameter.
2873 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2874 // Just pretend that we didn't see the previous declaration.
2875 PrevDecl = 0;
2876 }
2877
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002878 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002879 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2880 "unexpected Decl type");
2881 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002882 // If this is a use of a previous tag, or if the tag is already declared
2883 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002884 // rementions the tag), reuse the decl.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002885 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002886 // Make sure that this wasn't declared as an enum and now used as a
2887 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002888 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002889 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002890 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002891 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002892 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002893 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002894 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002895 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002896
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002897 // FIXME: In the future, return a variant or some other clue
2898 // for the consumer of this Decl to know it doesn't own it.
2899 // For our current ASTs this shouldn't be a problem, but will
2900 // need to be changed with DeclGroups.
2901 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002902 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002903
2904 // Diagnose attempts to redefine a tag.
2905 if (TK == TK_Definition) {
2906 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2907 Diag(NameLoc, diag::err_redefinition) << Name;
2908 Diag(Def->getLocation(), diag::note_previous_definition);
2909 // If this is a redefinition, recover by making this struct be
2910 // anonymous, which will make any later references get the previous
2911 // definition.
2912 Name = 0;
2913 PrevDecl = 0;
2914 }
2915 // Okay, this is definition of a previously declared or referenced
2916 // tag PrevDecl. We're going to create a new Decl for it.
2917 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002918 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002919 // If we get here we have (another) forward declaration or we
2920 // have a definition. Just create a new decl.
2921 } else {
2922 // If we get here, this is a definition of a new tag type in a nested
2923 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2924 // new decl/type. We set PrevDecl to NULL so that the entities
2925 // have distinct types.
2926 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002927 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002928 // If we get here, we're going to create a new Decl. If PrevDecl
2929 // is non-NULL, it's a definition of the tag declared by
2930 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002931 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002932 // PrevDecl is a namespace.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002933 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002934 // The tag name clashes with a namespace name, issue an error and
2935 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002936 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002937 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002938 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002939 PrevDecl = 0;
2940 } else {
2941 // The existing declaration isn't relevant to us; we're in a
2942 // new scope, so clear out the previous declaration.
2943 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002944 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002945 }
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002946 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
2947 (Kind != TagDecl::TK_enum)) {
2948 // C++ [basic.scope.pdecl]p5:
2949 // -- for an elaborated-type-specifier of the form
2950 //
2951 // class-key identifier
2952 //
2953 // if the elaborated-type-specifier is used in the
2954 // decl-specifier-seq or parameter-declaration-clause of a
2955 // function defined in namespace scope, the identifier is
2956 // declared as a class-name in the namespace that contains
2957 // the declaration; otherwise, except as a friend
2958 // declaration, the identifier is declared in the smallest
2959 // non-class, non-function-prototype scope that contains the
2960 // declaration.
2961 //
2962 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
2963 // C structs and unions.
2964
2965 // Find the context where we'll be declaring the tag.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002966 // FIXME: We would like to maintain the current DeclContext as the
2967 // lexical context,
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002968 while (DC->isRecord())
2969 DC = DC->getParent();
2970 LexicalContext = DC;
2971
2972 // Find the scope where we'll be declaring the tag.
2973 while (S->isClassScope() ||
2974 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00002975 ((S->getFlags() & Scope::DeclScope) == 0) ||
2976 (S->getEntity() &&
2977 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002978 S = S->getParent();
Reid Spencer5f016e22007-07-11 17:01:13 +00002979 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002980
Chris Lattnercc98eac2008-12-17 07:13:27 +00002981CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002982
2983 // If there is an identifier, use the location of the identifier as the
2984 // location of the decl, otherwise use the location of the struct/union
2985 // keyword.
2986 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2987
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002988 // Otherwise, create a new declaration. If there is a previous
2989 // declaration of the same entity, the two will be linked via
2990 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00002991 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002992
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002993 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002994 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2995 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002996 New = EnumDecl::Create(Context, DC, Loc, Name,
2997 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002998 // If this is an undefined enum, warn.
2999 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003000 } else {
3001 // struct/union/class
3002
Reid Spencer5f016e22007-07-11 17:01:13 +00003003 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3004 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003005 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00003006 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003007 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
3008 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003009 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003010 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
3011 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003012 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003013
3014 if (Kind != TagDecl::TK_enum) {
3015 // Handle #pragma pack: if the #pragma pack stack has non-default
3016 // alignment, make up a packed attribute for this decl. These
3017 // attributes are checked when the ASTContext lays out the
3018 // structure.
3019 //
3020 // It is important for implementing the correct semantics that this
3021 // happen here (in act on tag decl). The #pragma pack stack is
3022 // maintained as a result of parser callbacks which can occur at
3023 // many points during the parsing of a struct declaration (because
3024 // the #pragma tokens are effectively skipped over during the
3025 // parsing of the struct).
3026 if (unsigned Alignment = PackContext.getAlignment())
3027 New->addAttr(new PackedAttr(Alignment * 8));
3028 }
3029
3030 if (Attr)
3031 ProcessDeclAttributeList(New, Attr);
3032
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003033 // If we're declaring or defining
3034 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3035 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3036
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003037 // Set the lexical context. If the tag has a C++ scope specifier, the
3038 // lexical context will be different from the semantic context.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003039 New->setLexicalDeclContext(LexicalContext);
Reid Spencer5f016e22007-07-11 17:01:13 +00003040
3041 // If this has an identifier, add it to the scope stack.
3042 if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003043 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003044
3045 // Add it to the decl chain.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003046 if (LexicalContext != CurContext) {
3047 // FIXME: PushOnScopeChains should not rely on CurContext!
3048 DeclContext *OldContext = CurContext;
3049 CurContext = LexicalContext;
3050 PushOnScopeChains(New, S);
3051 CurContext = OldContext;
3052 } else
3053 PushOnScopeChains(New, S);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003054 } else {
Douglas Gregor482b77d2009-01-12 23:27:07 +00003055 LexicalContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00003056 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00003057
Reid Spencer5f016e22007-07-11 17:01:13 +00003058 return New;
3059}
3060
Douglas Gregor72de6672009-01-08 20:45:30 +00003061void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3062 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3063
3064 // Enter the tag context.
3065 PushDeclContext(S, Tag);
3066
3067 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3068 FieldCollector->StartClass();
3069
3070 if (Record->getIdentifier()) {
3071 // C++ [class]p2:
3072 // [...] The class-name is also inserted into the scope of the
3073 // class itself; this is known as the injected-class-name. For
3074 // purposes of access checking, the injected-class-name is treated
3075 // as if it were a public member name.
3076 RecordDecl *InjectedClassName
3077 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3078 CurContext, Record->getLocation(),
3079 Record->getIdentifier(), Record);
3080 InjectedClassName->setImplicit();
3081 PushOnScopeChains(InjectedClassName, S);
3082 }
3083 }
3084}
3085
3086void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3087 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3088
3089 if (isa<CXXRecordDecl>(Tag))
3090 FieldCollector->FinishClass();
3091
3092 // Exit this scope of this tag's definition.
3093 PopDeclContext();
3094
3095 // Notify the consumer that we've defined a tag.
3096 Consumer.HandleTagDeclDefinition(Tag);
3097}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00003098
Chris Lattner1d353ba2008-11-12 21:17:48 +00003099/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3100/// types into constant array types in certain situations which would otherwise
3101/// be errors (for GCC compatibility).
3102static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3103 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00003104 // This method tries to turn a variable array into a constant
3105 // array even when the size isn't an ICE. This is necessary
3106 // for compatibility with code that depends on gcc's buggy
3107 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00003108 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3109 if (!VLATy) return QualType();
3110
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003111 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00003112 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003113 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00003114 return QualType();
3115
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003116 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3117 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00003118 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3119 return Context.getConstantArrayType(VLATy->getElementType(),
3120 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003121 return QualType();
3122}
3123
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003124bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00003125 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003126 // FIXME: 6.7.2.1p4 - verify the field type.
3127
3128 llvm::APSInt Value;
3129 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3130 return true;
3131
Chris Lattnercd087072008-12-12 04:56:04 +00003132 // Zero-width bitfield is ok for anonymous field.
3133 if (Value == 0 && FieldName)
3134 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3135
3136 if (Value.isNegative())
3137 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003138
3139 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3140 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00003141 if (TypeSize && Value.getZExtValue() > TypeSize)
3142 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3143 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003144
3145 return false;
3146}
3147
Steve Naroff08d92e42007-09-15 18:49:24 +00003148/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00003149/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00003150Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00003151 SourceLocation DeclStart,
3152 Declarator &D, ExprTy *BitfieldWidth) {
3153 IdentifierInfo *II = D.getIdentifier();
3154 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00003155 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00003156 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003157 if (II) Loc = D.getIdentifierLoc();
3158
3159 // FIXME: Unnamed fields can be handled in various different ways, for
3160 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00003161
Reid Spencer5f016e22007-07-11 17:01:13 +00003162 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00003163 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3164 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00003165
Reid Spencer5f016e22007-07-11 17:01:13 +00003166 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3167 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00003168 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00003169 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003170 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003171 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003172 T = FixedTy;
3173 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003174 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00003175 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00003176 InvalidDecl = true;
3177 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003178 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003179
3180 if (BitWidth) {
3181 if (VerifyBitField(Loc, II, T, BitWidth))
3182 InvalidDecl = true;
3183 } else {
3184 // Not a bitfield.
3185
3186 // validate II.
3187
3188 }
3189
Reid Spencer5f016e22007-07-11 17:01:13 +00003190 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003191 FieldDecl *NewFD;
3192
Douglas Gregor44b43212008-12-11 16:49:14 +00003193 NewFD = FieldDecl::Create(Context, Record,
3194 Loc, II, T, BitWidth,
3195 D.getDeclSpec().getStorageClassSpec() ==
3196 DeclSpec::SCS_mutable,
3197 /*PrevDecl=*/0);
3198
Douglas Gregor72de6672009-01-08 20:45:30 +00003199 if (II) {
3200 Decl *PrevDecl
3201 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3202 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3203 && !isa<TagDecl>(PrevDecl)) {
3204 Diag(Loc, diag::err_duplicate_member) << II;
3205 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3206 NewFD->setInvalidDecl();
3207 Record->setInvalidDecl();
3208 }
3209 }
3210
Sebastian Redl64b45f72009-01-05 20:52:13 +00003211 if (getLangOptions().CPlusPlus) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003212 CheckExtraCXXDefaultArguments(D);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003213 if (!T->isPODType())
3214 cast<CXXRecordDecl>(Record)->setPOD(false);
3215 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003216
Chris Lattner3ff30c82008-06-29 00:02:00 +00003217 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00003218
Steve Naroff5912a352007-08-28 20:14:24 +00003219 if (D.getInvalidType() || InvalidDecl)
3220 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003221
Douglas Gregor72de6672009-01-08 20:45:30 +00003222 if (II) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003223 PushOnScopeChains(NewFD, S);
Douglas Gregor72de6672009-01-08 20:45:30 +00003224 } else
Douglas Gregor482b77d2009-01-12 23:27:07 +00003225 Record->addDecl(NewFD);
Douglas Gregor44b43212008-12-11 16:49:14 +00003226
Steve Naroff5912a352007-08-28 20:14:24 +00003227 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003228}
3229
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003230/// TranslateIvarVisibility - Translate visibility from a token ID to an
3231/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003232static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003233TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00003234 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00003235 default: assert(0 && "Unknown visitibility kind");
3236 case tok::objc_private: return ObjCIvarDecl::Private;
3237 case tok::objc_public: return ObjCIvarDecl::Public;
3238 case tok::objc_protected: return ObjCIvarDecl::Protected;
3239 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00003240 }
3241}
3242
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003243/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3244/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003245Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003246 SourceLocation DeclStart,
3247 Declarator &D, ExprTy *BitfieldWidth,
3248 tok::ObjCKeywordKind Visibility) {
Douglas Gregor72de6672009-01-08 20:45:30 +00003249
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003250 IdentifierInfo *II = D.getIdentifier();
3251 Expr *BitWidth = (Expr*)BitfieldWidth;
3252 SourceLocation Loc = DeclStart;
3253 if (II) Loc = D.getIdentifierLoc();
3254
3255 // FIXME: Unnamed fields can be handled in various different ways, for
3256 // example, unnamed unions inject all members into the struct namespace!
3257
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003258 QualType T = GetTypeForDeclarator(D, S);
3259 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3260 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003261
3262 if (BitWidth) {
3263 // TODO: Validate.
3264 //printf("WARNING: BITFIELDS IGNORED!\n");
3265
3266 // 6.7.2.1p3
3267 // 6.7.2.1p4
3268
3269 } else {
3270 // Not a bitfield.
3271
3272 // validate II.
3273
3274 }
3275
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003276 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3277 // than a variably modified type.
3278 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00003279 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003280 InvalidDecl = true;
3281 }
3282
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003283 // Get the visibility (access control) for this ivar.
3284 ObjCIvarDecl::AccessControl ac =
3285 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3286 : ObjCIvarDecl::None;
3287
3288 // Construct the decl.
3289 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00003290 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003291
Douglas Gregor72de6672009-01-08 20:45:30 +00003292 if (II) {
3293 Decl *PrevDecl
3294 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3295 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3296 && !isa<TagDecl>(PrevDecl)) {
3297 Diag(Loc, diag::err_duplicate_member) << II;
3298 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3299 NewID->setInvalidDecl();
3300 }
3301 }
3302
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003303 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00003304 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003305
3306 if (D.getInvalidType() || InvalidDecl)
3307 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003308
Douglas Gregor72de6672009-01-08 20:45:30 +00003309 if (II) {
3310 // FIXME: When interfaces are DeclContexts, we'll need to add
3311 // these to the interface.
3312 S->AddDecl(NewID);
3313 IdResolver.AddDecl(NewID);
3314 }
3315
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003316 return NewID;
3317}
3318
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00003319void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003320 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00003321 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00003322 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00003323 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00003324 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3325 assert(EnclosingDecl && "missing record or interface decl");
3326 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3327
Douglas Gregor72de6672009-01-08 20:45:30 +00003328 if (Record) {
3329 QualType RecordType = Context.getTypeDeclType(Record);
3330 if (RecordType->getAsRecordType()->getDecl()->isDefinition()) {
3331 RecordDecl *Def = RecordType->getAsRecordType()->getDecl();
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003332 // Diagnose code like:
3333 // struct S { struct S {} X; };
3334 // We discover this when we complete the outer S. Reject and ignore the
3335 // outer S.
Douglas Gregor72de6672009-01-08 20:45:30 +00003336 Diag(Def->getLocation(), diag::err_nested_redefinition)
3337 << Def->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003338 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003339 Record->setInvalidDecl();
3340 return;
3341 }
Douglas Gregor72de6672009-01-08 20:45:30 +00003342 }
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003343
Reid Spencer5f016e22007-07-11 17:01:13 +00003344 // Verify that all the fields are okay.
3345 unsigned NumNamedMembers = 0;
3346 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003347
Reid Spencer5f016e22007-07-11 17:01:13 +00003348 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff74216642007-09-14 22:20:54 +00003349 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3350 assert(FD && "missing field decl");
3351
Reid Spencer5f016e22007-07-11 17:01:13 +00003352 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003353 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003354
Douglas Gregor72de6672009-01-08 20:45:30 +00003355 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003356 // Remember all fields written by the user.
3357 RecFields.push_back(FD);
3358 }
Steve Narofff13271f2007-09-14 23:09:53 +00003359
Reid Spencer5f016e22007-07-11 17:01:13 +00003360 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003361 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003362 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003363 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003364 FD->setInvalidDecl();
3365 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003366 continue;
3367 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003368 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3369 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003370 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003371 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003372 FD->setInvalidDecl();
3373 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003374 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003375 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003376 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003377 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003378 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003379 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003380 FD->setInvalidDecl();
3381 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003382 continue;
3383 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003384 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003385 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003386 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003387 FD->setInvalidDecl();
3388 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003389 continue;
3390 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003391 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003392 if (Record)
3393 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003394 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003395 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3396 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003397 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003398 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3399 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003400 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003401 Record->setHasFlexibleArrayMember(true);
3402 } else {
3403 // If this is a struct/class and this is not the last element, reject
3404 // it. Note that GCC supports variable sized arrays in the middle of
3405 // structures.
3406 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003407 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003408 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003409 FD->setInvalidDecl();
3410 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003411 continue;
3412 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003413 // We support flexible arrays at the end of structs in other structs
3414 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003415 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003416 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003417 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003418 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003419 }
3420 }
3421 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003422 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003423 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003424 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003425 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003426 FD->setInvalidDecl();
3427 EnclosingDecl->setInvalidDecl();
3428 continue;
3429 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003430 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00003431 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00003432 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003433 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003434
Reid Spencer5f016e22007-07-11 17:01:13 +00003435 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003436 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003437 Record->completeDefinition(Context);
Chris Lattnere1e79852008-02-06 00:51:33 +00003438 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003439 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003440 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003441 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003442 // Must enforce the rule that ivars in the base classes may not be
3443 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003444 if (ID->getSuperClass()) {
3445 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3446 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3447 ObjCIvarDecl* Ivar = (*IVI);
3448 IdentifierInfo *II = Ivar->getIdentifier();
3449 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3450 if (prevIvar) {
3451 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregor72de6672009-01-08 20:45:30 +00003452 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003453 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003454 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003455 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003456 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003457 else if (ObjCImplementationDecl *IMPDecl =
3458 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003459 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3460 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003461 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003462 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003463 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003464
3465 if (Attr)
3466 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003467}
3468
Steve Naroff08d92e42007-09-15 18:49:24 +00003469Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003470 DeclTy *lastEnumConst,
3471 SourceLocation IdLoc, IdentifierInfo *Id,
3472 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003473 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003474 EnumConstantDecl *LastEnumConst =
3475 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3476 Expr *Val = static_cast<Expr*>(val);
3477
Chris Lattner31e05722007-08-26 06:24:45 +00003478 // The scope passed in may not be a decl scope. Zip up the scope tree until
3479 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003480 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003481
Reid Spencer5f016e22007-07-11 17:01:13 +00003482 // Verify that there isn't already something declared with this name in this
3483 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003484 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003485 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003486 // Maybe we will complain about the shadowed template parameter.
3487 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3488 // Just pretend that we didn't see the previous declaration.
3489 PrevDecl = 0;
3490 }
3491
3492 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003493 // When in C++, we may get a TagDecl with the same name; in this case the
3494 // enum constant will 'hide' the tag.
3495 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3496 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003497 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003498 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003499 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003500 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003501 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003502 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003503 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003504 return 0;
3505 }
3506 }
3507
3508 llvm::APSInt EnumVal(32);
3509 QualType EltTy;
3510 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003511 // Make sure to promote the operand type to int.
3512 UsualUnaryConversions(Val);
3513
Reid Spencer5f016e22007-07-11 17:01:13 +00003514 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3515 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003516 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003517 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003518 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003519 } else {
3520 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003521 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003522 }
3523
3524 if (!Val) {
3525 if (LastEnumConst) {
3526 // Assign the last value + 1.
3527 EnumVal = LastEnumConst->getInitVal();
3528 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003529
3530 // Check for overflow on increment.
3531 if (EnumVal < LastEnumConst->getInitVal())
3532 Diag(IdLoc, diag::warn_enum_value_overflow);
3533
Chris Lattnerb7416f92007-08-27 17:37:24 +00003534 EltTy = LastEnumConst->getType();
3535 } else {
3536 // First value, set to zero.
3537 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003538 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003539 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003540 }
3541
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003542 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003543 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3544 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003545 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003546
3547 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003548 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003549
Reid Spencer5f016e22007-07-11 17:01:13 +00003550 return New;
3551}
3552
Steve Naroff02408c62008-08-07 14:08:16 +00003553// FIXME: For consistency with ActOnFields(), we should have the parser
3554// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003555void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003556 DeclTy **Elements, unsigned NumElements) {
3557 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00003558 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003559
Douglas Gregor074149e2009-01-05 19:45:36 +00003560 if (EnumType->getAsEnumType()->getDecl()->isDefinition()) {
3561 EnumDecl *Def = EnumType->getAsEnumType()->getDecl();
3562 // Diagnose code like:
3563 // enum e0 {
3564 // E0 = sizeof(enum e0 { E1 })
3565 // };
3566 Diag(Def->getLocation(), diag::err_nested_redefinition)
3567 << Enum->getDeclName();
3568 Diag(Enum->getLocation(), diag::note_previous_definition);
3569 Enum->setInvalidDecl();
Douglas Gregor074149e2009-01-05 19:45:36 +00003570 return;
Steve Naroff02408c62008-08-07 14:08:16 +00003571 }
Douglas Gregor074149e2009-01-05 19:45:36 +00003572
Chris Lattnere37f0be2007-08-28 05:10:31 +00003573 // TODO: If the result value doesn't fit in an int, it must be a long or long
3574 // long value. ISO C does not support this, but GCC does as an extension,
3575 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003576 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003577
Chris Lattnerac609682007-08-28 06:15:15 +00003578 // Verify that all the values are okay, compute the size of the values, and
3579 // reverse the list.
3580 unsigned NumNegativeBits = 0;
3581 unsigned NumPositiveBits = 0;
3582
3583 // Keep track of whether all elements have type int.
3584 bool AllElementsInt = true;
3585
Reid Spencer5f016e22007-07-11 17:01:13 +00003586 for (unsigned i = 0; i != NumElements; ++i) {
3587 EnumConstantDecl *ECD =
3588 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3589 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003590
3591 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003592 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003593 assert(InitVal.getBitWidth() >= IntWidth &&
3594 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003595 if (InitVal.getBitWidth() > IntWidth) {
3596 llvm::APSInt V(InitVal);
3597 V.trunc(IntWidth);
3598 V.extend(InitVal.getBitWidth());
3599 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003600 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3601 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003602 }
Chris Lattnerac609682007-08-28 06:15:15 +00003603
3604 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003605 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003606 NumPositiveBits = std::max(NumPositiveBits,
3607 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003608 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003609 NumNegativeBits = std::max(NumNegativeBits,
3610 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003611
Chris Lattnerac609682007-08-28 06:15:15 +00003612 // Keep track of whether every enum element has type int (very commmon).
3613 if (AllElementsInt)
3614 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003615 }
3616
Chris Lattnerac609682007-08-28 06:15:15 +00003617 // Figure out the type that should be used for this enum.
3618 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3619 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003620 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003621
3622 if (NumNegativeBits) {
3623 // If there is a negative value, figure out the smallest integer type (of
3624 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003625 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003626 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003627 BestWidth = IntWidth;
3628 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003629 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003630
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003631 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003632 BestType = Context.LongTy;
3633 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003634 BestWidth = Context.Target.getLongLongWidth();
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 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3638 BestType = Context.LongLongTy;
3639 }
3640 }
3641 } else {
3642 // If there is no negative value, figure out which of uint, ulong, ulonglong
3643 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003644 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003645 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003646 BestWidth = IntWidth;
3647 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003648 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003649 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003650 } else {
3651 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003652 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003653 "How could an initializer get larger than ULL?");
3654 BestType = Context.UnsignedLongLongTy;
3655 }
3656 }
3657
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003658 // Loop over all of the enumerator constants, changing their types to match
3659 // the type of the enum if needed.
3660 for (unsigned i = 0; i != NumElements; ++i) {
3661 EnumConstantDecl *ECD =
3662 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3663 if (!ECD) continue; // Already issued a diagnostic.
3664
3665 // Standard C says the enumerators have int type, but we allow, as an
3666 // extension, the enumerators to be larger than int size. If each
3667 // enumerator value fits in an int, type it as an int, otherwise type it the
3668 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3669 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003670 if (ECD->getType() == Context.IntTy) {
3671 // Make sure the init value is signed.
3672 llvm::APSInt IV = ECD->getInitVal();
3673 IV.setIsSigned(true);
3674 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003675
3676 if (getLangOptions().CPlusPlus)
3677 // C++ [dcl.enum]p4: Following the closing brace of an
3678 // enum-specifier, each enumerator has the type of its
3679 // enumeration.
3680 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003681 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003682 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003683
3684 // Determine whether the value fits into an int.
3685 llvm::APSInt InitVal = ECD->getInitVal();
3686 bool FitsInInt;
3687 if (InitVal.isUnsigned() || !InitVal.isNegative())
3688 FitsInInt = InitVal.getActiveBits() < IntWidth;
3689 else
3690 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3691
3692 // If it fits into an integer type, force it. Otherwise force it to match
3693 // the enum decl type.
3694 QualType NewTy;
3695 unsigned NewWidth;
3696 bool NewSign;
3697 if (FitsInInt) {
3698 NewTy = Context.IntTy;
3699 NewWidth = IntWidth;
3700 NewSign = true;
3701 } else if (ECD->getType() == BestType) {
3702 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003703 if (getLangOptions().CPlusPlus)
3704 // C++ [dcl.enum]p4: Following the closing brace of an
3705 // enum-specifier, each enumerator has the type of its
3706 // enumeration.
3707 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003708 continue;
3709 } else {
3710 NewTy = BestType;
3711 NewWidth = BestWidth;
3712 NewSign = BestType->isSignedIntegerType();
3713 }
3714
3715 // Adjust the APSInt value.
3716 InitVal.extOrTrunc(NewWidth);
3717 InitVal.setIsSigned(NewSign);
3718 ECD->setInitVal(InitVal);
3719
3720 // Adjust the Expr initializer and type.
Chris Lattner13fd4162009-01-15 19:19:42 +00003721 if (ECD->getInitExpr())
3722 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3723 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003724 if (getLangOptions().CPlusPlus)
3725 // C++ [dcl.enum]p4: Following the closing brace of an
3726 // enum-specifier, each enumerator has the type of its
3727 // enumeration.
3728 ECD->setType(EnumType);
3729 else
3730 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003731 }
Chris Lattnerac609682007-08-28 06:15:15 +00003732
Douglas Gregor44b43212008-12-11 16:49:14 +00003733 Enum->completeDefinition(Context, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00003734}
3735
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003736Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003737 ExprArg expr) {
3738 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3739
Chris Lattner8e25d862008-03-16 00:16:02 +00003740 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003741}
3742
Douglas Gregorf44515a2008-12-16 22:23:02 +00003743
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003744void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3745 ExprTy *alignment, SourceLocation PragmaLoc,
3746 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3747 Expr *Alignment = static_cast<Expr *>(alignment);
3748
3749 // If specified then alignment must be a "small" power of two.
3750 unsigned AlignmentVal = 0;
3751 if (Alignment) {
3752 llvm::APSInt Val;
3753 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3754 !Val.isPowerOf2() ||
3755 Val.getZExtValue() > 16) {
3756 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3757 delete Alignment;
3758 return; // Ignore
3759 }
3760
3761 AlignmentVal = (unsigned) Val.getZExtValue();
3762 }
3763
3764 switch (Kind) {
3765 case Action::PPK_Default: // pack([n])
3766 PackContext.setAlignment(AlignmentVal);
3767 break;
3768
3769 case Action::PPK_Show: // pack(show)
3770 // Show the current alignment, making sure to show the right value
3771 // for the default.
3772 AlignmentVal = PackContext.getAlignment();
3773 // FIXME: This should come from the target.
3774 if (AlignmentVal == 0)
3775 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003776 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003777 break;
3778
3779 case Action::PPK_Push: // pack(push [, id] [, [n])
3780 PackContext.push(Name);
3781 // Set the new alignment if specified.
3782 if (Alignment)
3783 PackContext.setAlignment(AlignmentVal);
3784 break;
3785
3786 case Action::PPK_Pop: // pack(pop [, id] [, n])
3787 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3788 // "#pragma pack(pop, identifier, n) is undefined"
3789 if (Alignment && Name)
3790 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3791
3792 // Do the pop.
3793 if (!PackContext.pop(Name)) {
3794 // If a name was specified then failure indicates the name
3795 // wasn't found. Otherwise failure indicates the stack was
3796 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003797 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3798 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003799
3800 // FIXME: Warn about popping named records as MSVC does.
3801 } else {
3802 // Pop succeeded, set the new alignment if specified.
3803 if (Alignment)
3804 PackContext.setAlignment(AlignmentVal);
3805 }
3806 break;
3807
3808 default:
3809 assert(0 && "Invalid #pragma pack kind.");
3810 }
3811}
3812
3813bool PragmaPackStack::pop(IdentifierInfo *Name) {
3814 if (Stack.empty())
3815 return false;
3816
3817 // If name is empty just pop top.
3818 if (!Name) {
3819 Alignment = Stack.back().first;
3820 Stack.pop_back();
3821 return true;
3822 }
3823
3824 // Otherwise, find the named record.
3825 for (unsigned i = Stack.size(); i != 0; ) {
3826 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003827 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003828 // Found it, pop up to and including this record.
3829 Alignment = Stack[i].first;
3830 Stack.erase(Stack.begin() + i, Stack.end());
3831 return true;
3832 }
3833 }
3834
3835 return false;
3836}