blob: cff01c6530129ee1b002d900a40431e456094b6c [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6953a072008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-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 Lattner33aad6e2008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregor39677622008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor6e71edc2008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Douglas Gregor39677622008-12-11 20:41:00 +000031
Chris Lattner4b009652007-07-25 00:24:17 +000032using namespace clang;
33
Douglas Gregorb0212bd2008-11-17 20:34:05 +000034Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000035 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-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 Gregor29dfa2f2009-01-15 00:26:24 +000042 LookupResult Result = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroff6384a012008-04-02 14:35:35 +000043
Douglas Gregor29dfa2f2009-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 Jahanian23f968b2007-10-12 16:34:10 +000064 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000065 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000066}
67
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000068DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000069 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000070 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000071 if (MD->isOutOfLineDefinition())
72 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-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
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000077 // the topmost (non-nested) class it is lexically declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000078 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
79 DC = MD->getParent();
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000080 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argiris Kirtzidis38f16712008-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
Argiris Kirtzidis881964b2008-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();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000093
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000094 return DC->getLexicalParent();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000095}
96
Douglas Gregor8acb7272008-12-11 16:49:14 +000097void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000098 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu2c9b8102008-12-08 07:14:51 +000099 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +0000100 CurContext = DC;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000101 S->setEntity(DC);
Chris Lattnereee57c02008-04-04 06:12:32 +0000102}
103
Chris Lattnerf3874bc2008-04-06 04:47:34 +0000104void Sema::PopDeclContext() {
105 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor8acb7272008-12-11 16:49:14 +0000106
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000107 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +0000108}
109
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000110/// Add this decl to the scope shadowed decl chains.
111void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregord8028382009-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
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000119 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000120
Douglas Gregor6e71edc2008-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 Gregor03b2ad22009-01-12 23:27:07 +0000125 CurContext->addDecl(SD);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000126
Argiris Kirtzidis59a9afb2008-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 Gregor3a423132009-01-07 16:34:42 +0000135 if (CurContext->getLookupContext()
136 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor8acb7272008-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 Gregor6e71edc2008-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 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000162
Douglas Gregor6e71edc2008-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 Gregor8acb7272008-12-11 16:49:14 +0000170 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000171 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000172 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000173 // We are pushing the name of a function, which might be an
174 // overloaded name.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000175 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor69e781f2009-01-06 23:51:29 +0000176 DeclContext *DC = FD->getDeclContext()->getLookupContext();
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000177 IdentifierResolver::iterator Redecl
Douglas Gregord8028382009-01-05 19:45:36 +0000178 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6e71edc2008-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 Gregord2baafd2008-10-21 16:13:35 +0000188 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000189 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000190
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000191 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000192}
193
Steve Naroff9637a9b2007-10-09 22:01:59 +0000194void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000195 if (S->decl_empty()) return;
Douglas Gregordd861062008-12-05 18:15:24 +0000196 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
197 "Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000198
Chris Lattner4b009652007-07-25 00:24:17 +0000199 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
200 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000201 Decl *TmpD = static_cast<Decl*>(*I);
202 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000203
Douglas Gregor8acb7272008-12-11 16:49:14 +0000204 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
205 NamedDecl *D = cast<NamedDecl>(TmpD);
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000206
Douglas Gregor8acb7272008-12-11 16:49:14 +0000207 if (!D->getDeclName()) continue;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000208
Douglas Gregor8acb7272008-12-11 16:49:14 +0000209 // Remove this name from our lexical scope.
210 IdResolver.RemoveDecl(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000211 }
212}
213
Steve Naroffe57c21a2008-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 Naroffe57c21a2008-04-01 23:04:06 +0000216ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-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 Jahaniandc36dc12007-10-12 19:38:20 +0000220
Steve Naroff6384a012008-04-02 14:35:35 +0000221 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000222}
223
Douglas Gregor5eca99e2009-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 Naroffe57c21a2008-04-01 23:04:06 +0000256/// LookupDecl - Look up the inner-most declaration in the specified
Douglas Gregor5ff0ee52008-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 Gregor78d70132009-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;
Chris Lattner50500f62009-01-16 19:44:00 +0000278 else {
279 assert(NSI == Decl::IDNS_Member &&"Unable to grok LookupDecl NSI argument");
Douglas Gregor78d70132009-01-14 22:20:51 +0000280 Kind = LookupCriteria::Member;
Chris Lattner50500f62009-01-16 19:44:00 +0000281 }
282
Douglas Gregor78d70132009-01-14 22:20:51 +0000283 if (LookupCtx)
284 return LookupQualifiedName(const_cast<DeclContext *>(LookupCtx), Name,
285 LookupCriteria(Kind, !LookInParent,
286 getLangOptions().CPlusPlus));
Douglas Gregordb568cf2009-01-08 20:45:30 +0000287
Douglas Gregor78d70132009-01-14 22:20:51 +0000288 // Unqualified lookup
289 return LookupName(S, Name,
290 LookupCriteria(Kind, !LookInParent,
291 getLangOptions().CPlusPlus));
Chris Lattner4b009652007-07-25 00:24:17 +0000292}
293
Chris Lattnera9c87f22008-05-05 22:18:14 +0000294void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000295 if (!Context.getBuiltinVaListType().isNull())
296 return;
297
298 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000299 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000300 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000301 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
302}
303
Chris Lattner4b009652007-07-25 00:24:17 +0000304/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
305/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000306ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
307 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000308 Builtin::ID BID = (Builtin::ID)bid;
309
Chris Lattnerb23469f2008-09-28 05:54:29 +0000310 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000311 InitBuiltinVaListType();
312
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000313 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000314 FunctionDecl *New = FunctionDecl::Create(Context,
315 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000316 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000317 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000318
Chris Lattnera9c87f22008-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 Kremenek8494c962009-01-14 00:42:25 +0000327 New->setParams(Context, &Params[0], Params.size());
Chris Lattnera9c87f22008-05-05 22:18:14 +0000328 }
329
330
331
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000332 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregord394a272009-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();
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000338 PushOnScopeChains(New, TUScope);
Douglas Gregord394a272009-01-09 18:51:29 +0000339 CurContext = SavedContext;
Chris Lattner4b009652007-07-25 00:24:17 +0000340 return New;
341}
342
Sebastian Redlb93b49c2008-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 Lattnerf0939602008-11-20 05:45:14 +0000347 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000348 DeclContext *Global = Context.getTranslationUnitDecl();
Douglas Gregor78d70132009-01-14 22:20:51 +0000349 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Ordinary,
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000350 0, Global, /*enableLazyBuiltinCreation=*/false);
351 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
352 }
353 return StdNamespace;
354}
355
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffe57c21a2008-04-01 23:04:06 +0000360TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahaniande939672009-01-16 19:58:32 +0000361 bool objc_types = false;
Steve Naroff453a8782008-09-09 14:32:20 +0000362 // Allow multiple definitions for ObjC built-in typedefs.
363 // FIXME: Verify the underlying types are equivalent!
364 if (getLangOptions().ObjC1) {
Chris Lattner6d16b052008-11-20 05:41:43 +0000365 const IdentifierInfo *TypeID = New->getIdentifier();
366 switch (TypeID->getLength()) {
367 default: break;
368 case 2:
369 if (!TypeID->isStr("id"))
370 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000371 Context.setObjCIdType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000372 objc_types = true;
373 break;
Chris Lattner6d16b052008-11-20 05:41:43 +0000374 case 5:
375 if (!TypeID->isStr("Class"))
376 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000377 Context.setObjCClassType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000378 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000379 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000380 case 3:
381 if (!TypeID->isStr("SEL"))
382 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000383 Context.setObjCSelType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000384 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000385 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000386 case 8:
387 if (!TypeID->isStr("Protocol"))
388 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000389 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahaniande939672009-01-16 19:58:32 +0000390 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000391 return New;
392 }
393 // Fall through - the typedef name was not a builtin type.
394 }
Chris Lattner4b009652007-07-25 00:24:17 +0000395 // Verify the old decl was also a typedef.
396 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
397 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000398 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000399 << New->getDeclName();
Fariborz Jahaniande939672009-01-16 19:58:32 +0000400 if (!objc_types)
401 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000402 return New;
403 }
404
Chris Lattnerbef8d622008-07-25 18:44:27 +0000405 // If the typedef types are not identical, reject them in all languages and
406 // with any extensions enabled.
407 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
408 Context.getCanonicalType(Old->getUnderlyingType()) !=
409 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner8d756812008-11-20 06:13:02 +0000410 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000411 << New->getUnderlyingType() << Old->getUnderlyingType();
Fariborz Jahaniande939672009-01-16 19:58:32 +0000412 if (!objc_types)
413 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregord1675382009-01-09 19:42:16 +0000414 return New;
Chris Lattnerbef8d622008-07-25 18:44:27 +0000415 }
Fariborz Jahaniande939672009-01-16 19:58:32 +0000416 if (objc_types) return New;
Eli Friedman324d5032008-06-11 06:20:39 +0000417 if (getLangOptions().Microsoft) return New;
418
Douglas Gregor49ba1b72008-11-21 16:29:06 +0000419 // C++ [dcl.typedef]p2:
420 // In a given non-class scope, a typedef specifier can be used to
421 // redefine the name of any type declared in that scope to refer
422 // to the type to which it already refers.
423 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
424 return New;
425
426 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroffa9eae582008-01-30 23:46:05 +0000427 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
428 // *either* declaration is in a system header. The code below implements
429 // this adhoc compatibility rule. FIXME: The following code will not
430 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000431 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
432 SourceManager &SrcMgr = Context.getSourceManager();
433 if (SrcMgr.isInSystemHeader(Old->getLocation()))
434 return New;
435 if (SrcMgr.isInSystemHeader(New->getLocation()))
436 return New;
437 }
Eli Friedman324d5032008-06-11 06:20:39 +0000438
Chris Lattnerb1753422008-11-23 21:45:46 +0000439 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000440 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000441 return New;
442}
443
Chris Lattner6953a072008-06-26 18:38:35 +0000444/// DeclhasAttr - returns true if decl Declaration already has the target
445/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000446static bool DeclHasAttr(const Decl *decl, const Attr *target) {
447 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
448 if (attr->getKind() == target->getKind())
449 return true;
450
451 return false;
452}
453
454/// MergeAttributes - append attributes from the Old decl to the New one.
455static void MergeAttributes(Decl *New, Decl *Old) {
456 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
457
Chris Lattner402b3372008-03-03 03:28:21 +0000458 while (attr) {
459 tmp = attr;
460 attr = attr->getNext();
461
462 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000463 tmp->setInherited(true);
Chris Lattner402b3372008-03-03 03:28:21 +0000464 New->addAttr(tmp);
465 } else {
466 tmp->setNext(0);
467 delete(tmp);
468 }
469 }
Nuno Lopes77654342008-06-01 22:53:53 +0000470
471 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000472}
473
Chris Lattner3e254fb2008-04-08 04:40:51 +0000474/// MergeFunctionDecl - We just parsed a function 'New' from
475/// declarator D which has the same name and scope as a previous
476/// declaration 'Old'. Figure out how to resolve this situation,
477/// merging decls or emitting diagnostics as appropriate.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000478/// Redeclaration will be set true if this New is a redeclaration OldD.
479///
480/// In C++, New and Old must be declarations that are not
481/// overloaded. Use IsOverload to determine whether New and Old are
482/// overloaded, and to select the Old declaration that New should be
483/// merged with.
Douglas Gregor42214c52008-04-21 02:02:58 +0000484FunctionDecl *
485Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000486 assert(!isa<OverloadedFunctionDecl>(OldD) &&
487 "Cannot merge with an overloaded function declaration");
488
Douglas Gregor42214c52008-04-21 02:02:58 +0000489 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000490 // Verify the old decl was also a function.
491 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
492 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000493 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000494 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000495 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000496 return New;
497 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000498
499 // Determine whether the previous declaration was a definition,
500 // implicit declaration, or a declaration.
501 diag::kind PrevDiag;
502 if (Old->isThisDeclarationADefinition())
Chris Lattner1336cab2008-11-23 23:12:31 +0000503 PrevDiag = diag::note_previous_definition;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000504 else if (Old->isImplicit())
Chris Lattner1336cab2008-11-23 23:12:31 +0000505 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000506 else
Chris Lattner1336cab2008-11-23 23:12:31 +0000507 PrevDiag = diag::note_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000508
Chris Lattner42a21742008-04-06 23:10:54 +0000509 QualType OldQType = Context.getCanonicalType(Old->getType());
510 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000511
Douglas Gregord2baafd2008-10-21 16:13:35 +0000512 if (getLangOptions().CPlusPlus) {
513 // (C++98 13.1p2):
514 // Certain function declarations cannot be overloaded:
515 // -- Function declarations that differ only in the return type
516 // cannot be overloaded.
517 QualType OldReturnType
518 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
519 QualType NewReturnType
520 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
521 if (OldReturnType != NewReturnType) {
522 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
523 Diag(Old->getLocation(), PrevDiag);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000524 Redeclaration = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000525 return New;
526 }
527
528 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
529 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
530 if (OldMethod && NewMethod) {
531 // -- Member function declarations with the same name and the
532 // same parameter types cannot be overloaded if any of them
533 // is a static member function declaration.
534 if (OldMethod->isStatic() || NewMethod->isStatic()) {
535 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
536 Diag(Old->getLocation(), PrevDiag);
537 return New;
538 }
Douglas Gregorb9213832008-12-15 21:24:18 +0000539
540 // C++ [class.mem]p1:
541 // [...] A member shall not be declared twice in the
542 // member-specification, except that a nested class or member
543 // class template can be declared and then later defined.
544 if (OldMethod->getLexicalDeclContext() ==
545 NewMethod->getLexicalDeclContext()) {
546 unsigned NewDiag;
547 if (isa<CXXConstructorDecl>(OldMethod))
548 NewDiag = diag::err_constructor_redeclared;
549 else if (isa<CXXDestructorDecl>(NewMethod))
550 NewDiag = diag::err_destructor_redeclared;
551 else if (isa<CXXConversionDecl>(NewMethod))
552 NewDiag = diag::err_conv_function_redeclared;
553 else
554 NewDiag = diag::err_member_redeclared;
555
556 Diag(New->getLocation(), NewDiag);
557 Diag(Old->getLocation(), PrevDiag);
558 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000559 }
560
561 // (C++98 8.3.5p3):
562 // All declarations for a function shall agree exactly in both the
563 // return type and the parameter-type-list.
564 if (OldQType == NewQType) {
565 // We have a redeclaration.
566 MergeAttributes(New, Old);
567 Redeclaration = true;
568 return MergeCXXFunctionDecl(New, Old);
569 }
570
571 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000572 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000573
574 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000575 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000576 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000577 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000578 MergeAttributes(New, Old);
579 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000580 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000581 }
Chris Lattner1470b072007-11-06 06:07:26 +0000582
Steve Naroff6c9e7922008-01-16 15:01:34 +0000583 // A function that has already been declared has been redeclared or defined
584 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000585
Chris Lattner4b009652007-07-25 00:24:17 +0000586 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
587 // TODO: This is totally simplistic. It should handle merging functions
588 // together etc, merging extern int X; int X; ...
Chris Lattner271d4c22008-11-24 05:29:24 +0000589 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff6c9e7922008-01-16 15:01:34 +0000590 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000591 return New;
592}
593
Steve Naroffb5e78152008-08-08 17:50:35 +0000594/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000595static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000596 if (VD->isFileVarDecl())
597 return (!VD->getInit() &&
598 (VD->getStorageClass() == VarDecl::None ||
599 VD->getStorageClass() == VarDecl::Static));
600 return false;
601}
602
603/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
604/// when dealing with C "tentative" external object definitions (C99 6.9.2).
605void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
606 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000607 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000608
Douglas Gregor3a423132009-01-07 16:34:42 +0000609 // FIXME: I don't think this will actually see all of the
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000610 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffb5e78152008-08-08 17:50:35 +0000611 for (IdentifierResolver::iterator
612 I = IdResolver.begin(VD->getIdentifier(),
613 VD->getDeclContext(), false/*LookInParentCtx*/),
614 E = IdResolver.end(); I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000615 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000616 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
617
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000618 // Handle the following case:
619 // int a[10];
620 // int a[]; - the code below makes sure we set the correct type.
621 // int a[11]; - this is an error, size isn't 10.
622 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
623 OldDecl->getType()->isConstantArrayType())
624 VD->setType(OldDecl->getType());
625
Steve Naroffb5e78152008-08-08 17:50:35 +0000626 // Check for "tentative" definitions. We can't accomplish this in
627 // MergeVarDecl since the initializer hasn't been attached.
628 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
629 continue;
630
631 // Handle __private_extern__ just like extern.
632 if (OldDecl->getStorageClass() != VarDecl::Extern &&
633 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
634 VD->getStorageClass() != VarDecl::Extern &&
635 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000636 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000637 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffb5e78152008-08-08 17:50:35 +0000638 }
639 }
640 }
641}
642
Chris Lattner4b009652007-07-25 00:24:17 +0000643/// MergeVarDecl - We just parsed a variable 'New' which has the same name
644/// and scope as a previous declaration 'Old'. Figure out how to resolve this
645/// situation, merging decls or emitting diagnostics as appropriate.
646///
Steve Naroffb5e78152008-08-08 17:50:35 +0000647/// Tentative definition rules (C99 6.9.2p2) are checked by
648/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
649/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000650///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000651VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000652 // Verify the old decl was also a variable.
653 VarDecl *Old = dyn_cast<VarDecl>(OldD);
654 if (!Old) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000655 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000656 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000657 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000658 return New;
659 }
Chris Lattner402b3372008-03-03 03:28:21 +0000660
661 MergeAttributes(New, Old);
662
Chris Lattner4b009652007-07-25 00:24:17 +0000663 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000664 QualType OldCType = Context.getCanonicalType(Old->getType());
665 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000666 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Douglas Gregord1675382009-01-09 19:42:16 +0000667 Diag(New->getLocation(), diag::err_redefinition_different_type)
668 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000669 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000670 return New;
671 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000672 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
673 if (New->getStorageClass() == VarDecl::Static &&
674 (Old->getStorageClass() == VarDecl::None ||
675 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000676 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000677 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000678 return New;
679 }
680 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
681 if (New->getStorageClass() != VarDecl::Static &&
682 Old->getStorageClass() == VarDecl::Static) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000683 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000684 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000685 return New;
686 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000687 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
688 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000689 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000690 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000691 }
692 return New;
693}
694
Chris Lattner3e254fb2008-04-08 04:40:51 +0000695/// CheckParmsForFunctionDef - Check that the parameters of the given
696/// function are appropriate for the definition of a function. This
697/// takes care of any checks that cannot be performed on the
698/// declaration itself, e.g., that the types of each of the function
699/// parameters are complete.
700bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
701 bool HasInvalidParm = false;
702 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
703 ParmVarDecl *Param = FD->getParamDecl(p);
704
705 // C99 6.7.5.3p4: the parameters in a parameter type list in a
706 // function declarator that is part of a function definition of
707 // that function shall not have incomplete type.
708 if (Param->getType()->isIncompleteType() &&
709 !Param->isInvalidDecl()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000710 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +0000711 << Param->getType();
Chris Lattner3e254fb2008-04-08 04:40:51 +0000712 Param->setInvalidDecl();
713 HasInvalidParm = true;
714 }
Chris Lattnerb0b42f62008-12-17 07:32:46 +0000715
716 // C99 6.9.1p5: If the declarator includes a parameter type list, the
717 // declaration of each parameter shall include an identifier.
718 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
719 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000720 }
721
722 return HasInvalidParm;
723}
724
Chris Lattner4b009652007-07-25 00:24:17 +0000725/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
726/// no declarator (e.g. "struct foo;") is parsed.
727Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregorb748fc52009-01-12 22:49:06 +0000728 TagDecl *Tag
729 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
730 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
731 if (!Record->getDeclName() && Record->isDefinition() &&
732 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
733 return BuildAnonymousStructOrUnion(S, DS, Record);
734
735 // Microsoft allows unnamed struct/union fields. Don't complain
736 // about them.
737 // FIXME: Should we support Microsoft's extensions in this area?
738 if (Record->getDeclName() && getLangOptions().Microsoft)
739 return Tag;
740 }
741
Douglas Gregor80c720e2009-01-13 23:10:51 +0000742 // Permit typedefs without declarators as a Microsoft extension.
Sebastian Redlb7605e82008-12-28 15:28:59 +0000743 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregor72de8492009-01-17 02:55:50 +0000744 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
745 Tag && isa<EnumDecl>(Tag)) {
746 Diag(DS.getSourceRange().getBegin(), diag::warn_no_declarators)
Douglas Gregor80c720e2009-01-13 23:10:51 +0000747 << DS.getSourceRange();
748 return Tag;
749 }
750
Sebastian Redlb7605e82008-12-28 15:28:59 +0000751 // FIXME: This diagnostic is emitted even when various previous
752 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
753 // DeclSpec has no means of communicating this information, and the
754 // responsible parser functions are quite far apart.
755 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
756 << DS.getSourceRange();
757 return 0;
758 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000759
Douglas Gregor723d3332009-01-07 00:43:41 +0000760 return Tag;
761}
762
763/// InjectAnonymousStructOrUnionMembers - Inject the members of the
764/// anonymous struct or union AnonRecord into the owning context Owner
765/// and scope S. This routine will be invoked just after we realize
766/// that an unnamed union or struct is actually an anonymous union or
767/// struct, e.g.,
768///
769/// @code
770/// union {
771/// int i;
772/// float f;
773/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
774/// // f into the surrounding scope.x
775/// @endcode
776///
777/// This routine is recursive, injecting the names of nested anonymous
778/// structs/unions into the owning context and scope as well.
779bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
780 RecordDecl *AnonRecord) {
781 bool Invalid = false;
782 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
783 FEnd = AnonRecord->field_end();
784 F != FEnd; ++F) {
785 if ((*F)->getDeclName()) {
786 Decl *PrevDecl = LookupDecl((*F)->getDeclName(), Decl::IDNS_Ordinary,
787 S, Owner, false, false, false);
788 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
789 // C++ [class.union]p2:
790 // The names of the members of an anonymous union shall be
791 // distinct from the names of any other entity in the
792 // scope in which the anonymous union is declared.
793 unsigned diagKind
794 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
795 : diag::err_anonymous_struct_member_redecl;
796 Diag((*F)->getLocation(), diagKind)
797 << (*F)->getDeclName();
798 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
799 Invalid = true;
800 } else {
801 // C++ [class.union]p2:
802 // For the purpose of name lookup, after the anonymous union
803 // definition, the members of the anonymous union are
804 // considered to have been defined in the scope in which the
805 // anonymous union is declared.
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000806 Owner->insert(*F);
Douglas Gregor723d3332009-01-07 00:43:41 +0000807 S->AddDecl(*F);
808 IdResolver.AddDecl(*F);
809 }
810 } else if (const RecordType *InnerRecordType
811 = (*F)->getType()->getAsRecordType()) {
812 RecordDecl *InnerRecord = InnerRecordType->getDecl();
813 if (InnerRecord->isAnonymousStructOrUnion())
814 Invalid = Invalid ||
815 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
816 }
817 }
818
819 return Invalid;
820}
821
822/// ActOnAnonymousStructOrUnion - Handle the declaration of an
823/// anonymous structure or union. Anonymous unions are a C++ feature
824/// (C++ [class.union]) and a GNU C extension; anonymous structures
825/// are a GNU C and GNU C++ extension.
826Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
827 RecordDecl *Record) {
828 DeclContext *Owner = Record->getDeclContext();
829
830 // Diagnose whether this anonymous struct/union is an extension.
831 if (Record->isUnion() && !getLangOptions().CPlusPlus)
832 Diag(Record->getLocation(), diag::ext_anonymous_union);
833 else if (!Record->isUnion())
834 Diag(Record->getLocation(), diag::ext_anonymous_struct);
835
836 // C and C++ require different kinds of checks for anonymous
837 // structs/unions.
838 bool Invalid = false;
839 if (getLangOptions().CPlusPlus) {
840 const char* PrevSpec = 0;
841 // C++ [class.union]p3:
842 // Anonymous unions declared in a named namespace or in the
843 // global namespace shall be declared static.
844 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
845 (isa<TranslationUnitDecl>(Owner) ||
846 (isa<NamespaceDecl>(Owner) &&
847 cast<NamespaceDecl>(Owner)->getDeclName()))) {
848 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
849 Invalid = true;
850
851 // Recover by adding 'static'.
852 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
853 }
854 // C++ [class.union]p3:
855 // A storage class is not allowed in a declaration of an
856 // anonymous union in a class scope.
857 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
858 isa<RecordDecl>(Owner)) {
859 Diag(DS.getStorageClassSpecLoc(),
860 diag::err_anonymous_union_with_storage_spec);
861 Invalid = true;
862
863 // Recover by removing the storage specifier.
864 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
865 PrevSpec);
866 }
Douglas Gregorc7f01612009-01-07 19:46:03 +0000867
868 // C++ [class.union]p2:
869 // The member-specification of an anonymous union shall only
870 // define non-static data members. [Note: nested types and
871 // functions cannot be declared within an anonymous union. ]
872 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
873 MemEnd = Record->decls_end();
874 Mem != MemEnd; ++Mem) {
875 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
876 // C++ [class.union]p3:
877 // An anonymous union shall not have private or protected
878 // members (clause 11).
879 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
880 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
881 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
882 Invalid = true;
883 }
884 } else if ((*Mem)->isImplicit()) {
885 // Any implicit members are fine.
886 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
887 if (!MemRecord->isAnonymousStructOrUnion() &&
888 MemRecord->getDeclName()) {
889 // This is a nested type declaration.
890 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
891 << (int)Record->isUnion();
892 Invalid = true;
893 }
894 } else {
895 // We have something that isn't a non-static data
896 // member. Complain about it.
897 unsigned DK = diag::err_anonymous_record_bad_member;
898 if (isa<TypeDecl>(*Mem))
899 DK = diag::err_anonymous_record_with_type;
900 else if (isa<FunctionDecl>(*Mem))
901 DK = diag::err_anonymous_record_with_function;
902 else if (isa<VarDecl>(*Mem))
903 DK = diag::err_anonymous_record_with_static;
904 Diag((*Mem)->getLocation(), DK)
905 << (int)Record->isUnion();
906 Invalid = true;
907 }
908 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000909 } else {
910 // FIXME: Check GNU C semantics
Douglas Gregorb748fc52009-01-12 22:49:06 +0000911 if (Record->isUnion() && !Owner->isRecord()) {
912 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
913 << (int)getLangOptions().CPlusPlus;
914 Invalid = true;
915 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000916 }
917
918 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorb748fc52009-01-12 22:49:06 +0000919 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
920 << (int)getLangOptions().CPlusPlus;
Douglas Gregor723d3332009-01-07 00:43:41 +0000921 Invalid = true;
922 }
923
924 // Create a declaration for this anonymous struct/union.
925 ScopedDecl *Anon = 0;
926 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
927 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
928 /*IdentifierInfo=*/0,
929 Context.getTypeDeclType(Record),
930 /*BitWidth=*/0, /*Mutable=*/false,
931 /*PrevDecl=*/0);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000932 Anon->setAccess(AS_public);
933 if (getLangOptions().CPlusPlus)
934 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor723d3332009-01-07 00:43:41 +0000935 } else {
936 VarDecl::StorageClass SC;
937 switch (DS.getStorageClassSpec()) {
938 default: assert(0 && "Unknown storage class!");
939 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
940 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
941 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
942 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
943 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
944 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
945 case DeclSpec::SCS_mutable:
946 // mutable can only appear on non-static class members, so it's always
947 // an error here
948 Diag(Record->getLocation(), diag::err_mutable_nonmember);
949 Invalid = true;
950 SC = VarDecl::None;
951 break;
952 }
953
954 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
955 /*IdentifierInfo=*/0,
956 Context.getTypeDeclType(Record),
957 SC, /*FIXME:LastDeclarator=*/0,
958 DS.getSourceRange().getBegin());
959 }
Douglas Gregorc7f01612009-01-07 19:46:03 +0000960 Anon->setImplicit();
Douglas Gregor723d3332009-01-07 00:43:41 +0000961
962 // Add the anonymous struct/union object to the current
963 // context. We'll be referencing this object when we refer to one of
964 // its members.
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000965 Owner->addDecl(Anon);
Douglas Gregor723d3332009-01-07 00:43:41 +0000966
967 // Inject the members of the anonymous struct/union into the owning
968 // context and into the identifier resolver chain for name lookup
969 // purposes.
Douglas Gregorb748fc52009-01-12 22:49:06 +0000970 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
971 Invalid = true;
Douglas Gregor723d3332009-01-07 00:43:41 +0000972
973 // Mark this as an anonymous struct/union type. Note that we do not
974 // do this until after we have already checked and injected the
975 // members of this anonymous struct/union type, because otherwise
976 // the members could be injected twice: once by DeclContext when it
977 // builds its lookup table, and once by
978 // InjectAnonymousStructOrUnionMembers.
979 Record->setAnonymousStructOrUnion(true);
980
981 if (Invalid)
982 Anon->setInvalidDecl();
983
984 return Anon;
Chris Lattner4b009652007-07-25 00:24:17 +0000985}
986
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000987bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
988 bool DirectInit) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000989 // Get the type before calling CheckSingleAssignmentConstraints(), since
990 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000991 QualType InitType = Init->getType();
Douglas Gregor6fd35572008-12-19 17:40:08 +0000992
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000993 if (getLangOptions().CPlusPlus) {
994 // FIXME: I dislike this error message. A lot.
995 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
996 return Diag(Init->getSourceRange().getBegin(),
997 diag::err_typecheck_convert_incompatible)
998 << DeclType << Init->getType() << "initializing"
999 << Init->getSourceRange();
1000
1001 return false;
1002 }
Douglas Gregor6fd35572008-12-19 17:40:08 +00001003
Chris Lattner005ed752008-01-04 18:04:52 +00001004 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1005 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1006 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +00001007}
1008
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001009bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001010 const ArrayType *AT = Context.getAsArrayType(DeclT);
1011
1012 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001013 // C99 6.7.8p14. We have an array of character type with unknown size
1014 // being initialized to a string literal.
1015 llvm::APSInt ConstVal(32);
1016 ConstVal = strLiteral->getByteLength() + 1;
1017 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +00001018 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001019 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +00001020 } else {
1021 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001022 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +00001023 // FIXME: Avoid truncation for 64-bit length strings.
1024 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001025 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00001026 diag::warn_initializer_string_for_char_array_too_long)
1027 << strLiteral->getSourceRange();
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001028 }
1029 // Set type from "char *" to "constant array of char".
1030 strLiteral->setType(DeclT);
1031 // For now, we always return false (meaning success).
1032 return false;
1033}
1034
1035StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001036 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +00001037 if (AT && AT->getElementType()->isCharType()) {
1038 return dyn_cast<StringLiteral>(Init);
1039 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001040 return 0;
1041}
1042
Douglas Gregor6428e762008-11-05 15:29:30 +00001043bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1044 SourceLocation InitLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001045 DeclarationName InitEntity,
1046 bool DirectInit) {
Douglas Gregorf1ae3e02008-12-18 21:49:58 +00001047 if (DeclType->isDependentType() || Init->isTypeDependent())
1048 return false;
1049
Douglas Gregor81c29152008-10-29 00:13:59 +00001050 // C++ [dcl.init.ref]p1:
Sebastian Redl51504af2008-11-24 20:06:50 +00001051 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor81c29152008-10-29 00:13:59 +00001052 // (8.3.2), shall be initialized by an object, or function, of
1053 // type T or by an object that can be converted into a T.
1054 if (DeclType->isReferenceType())
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001055 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor81c29152008-10-29 00:13:59 +00001056
Steve Naroff8e9337f2008-01-21 23:53:58 +00001057 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1058 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +00001059 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattner9d2cf082008-11-19 05:27:50 +00001060 return Diag(InitLoc, diag::err_variable_object_no_init)
1061 << VAT->getSizeExpr()->getSourceRange();
Steve Naroff8e9337f2008-01-21 23:53:58 +00001062
Steve Naroffcb69fb72007-12-10 22:44:33 +00001063 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1064 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001065 // FIXME: Handle wide strings
1066 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1067 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +00001068
Douglas Gregor6428e762008-11-05 15:29:30 +00001069 // C++ [dcl.init]p14:
1070 // -- If the destination type is a (possibly cv-qualified) class
1071 // type:
1072 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1073 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1074 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1075
1076 // -- If the initialization is direct-initialization, or if it is
1077 // copy-initialization where the cv-unqualified version of the
1078 // source type is the same class as, or a derived class of, the
1079 // class of the destination, constructors are considered.
1080 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1081 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1082 CXXConstructorDecl *Constructor
1083 = PerformInitializationByConstructor(DeclType, &Init, 1,
1084 InitLoc, Init->getSourceRange(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001085 InitEntity,
1086 DirectInit? IK_Direct : IK_Copy);
Douglas Gregor6428e762008-11-05 15:29:30 +00001087 return Constructor == 0;
1088 }
1089
1090 // -- Otherwise (i.e., for the remaining copy-initialization
1091 // cases), user-defined conversion sequences that can
1092 // convert from the source type to the destination type or
1093 // (when a conversion function is used) to a derived class
1094 // thereof are enumerated as described in 13.3.1.4, and the
1095 // best one is chosen through overload resolution
1096 // (13.3). If the conversion cannot be done or is
1097 // ambiguous, the initialization is ill-formed. The
1098 // function selected is called with the initializer
1099 // expression as its argument; if the function is a
1100 // constructor, the call initializes a temporary of the
1101 // destination type.
1102 // FIXME: We're pretending to do copy elision here; return to
1103 // this when we have ASTs for such things.
Douglas Gregor6fd35572008-12-19 17:40:08 +00001104 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregor6428e762008-11-05 15:29:30 +00001105 return false;
Chris Lattner70b93d82008-11-18 22:52:51 +00001106
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001107 if (InitEntity)
1108 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1109 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1110 << Init->getType() << Init->getSourceRange();
1111 else
1112 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1113 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1114 << Init->getType() << Init->getSourceRange();
Douglas Gregor6428e762008-11-05 15:29:30 +00001115 }
1116
Steve Naroffb2f72412008-09-29 20:07:05 +00001117 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +00001118 if (DeclType->isArrayType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001119 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1120 << Init->getSourceRange();
Eli Friedman65280992008-02-08 00:48:24 +00001121
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001122 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregor15e04622008-11-05 16:20:31 +00001123 } else if (getLangOptions().CPlusPlus) {
1124 // C++ [dcl.init]p14:
1125 // [...] If the class is an aggregate (8.5.1), and the initializer
1126 // is a brace-enclosed list, see 8.5.1.
1127 //
1128 // Note: 8.5.1 is handled below; here, we diagnose the case where
1129 // we have an initializer list and a destination type that is not
1130 // an aggregate.
1131 // FIXME: In C++0x, this is yet another form of initialization.
1132 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1133 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1134 if (!ClassDecl->isAggregate())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001135 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001136 << DeclType << Init->getSourceRange();
Douglas Gregor15e04622008-11-05 16:20:31 +00001137 }
Steve Naroffcb69fb72007-12-10 22:44:33 +00001138 }
Eli Friedman38b7a912008-06-06 19:40:52 +00001139
Steve Naroffc4d4a482008-05-01 22:18:59 +00001140 InitListChecker CheckInitList(this, InitList, DeclType);
1141 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +00001142}
1143
Douglas Gregor6704b312008-11-17 22:58:34 +00001144/// GetNameForDeclarator - Determine the full declaration name for the
1145/// given Declarator.
1146DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1147 switch (D.getKind()) {
1148 case Declarator::DK_Abstract:
1149 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1150 return DeclarationName();
1151
1152 case Declarator::DK_Normal:
1153 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1154 return DeclarationName(D.getIdentifier());
1155
1156 case Declarator::DK_Constructor: {
1157 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1158 Ty = Context.getCanonicalType(Ty);
1159 return Context.DeclarationNames.getCXXConstructorName(Ty);
1160 }
1161
1162 case Declarator::DK_Destructor: {
1163 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1164 Ty = Context.getCanonicalType(Ty);
1165 return Context.DeclarationNames.getCXXDestructorName(Ty);
1166 }
1167
1168 case Declarator::DK_Conversion: {
1169 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1170 Ty = Context.getCanonicalType(Ty);
1171 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1172 }
Douglas Gregor96a32dd2008-11-18 14:39:36 +00001173
1174 case Declarator::DK_Operator:
1175 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1176 return Context.DeclarationNames.getCXXOperatorName(
1177 D.getOverloadedOperator());
Douglas Gregor6704b312008-11-17 22:58:34 +00001178 }
1179
1180 assert(false && "Unknown name kind");
1181 return DeclarationName();
1182}
1183
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001184/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1185/// functions Declaration and Definition are "nearly" matching. This
1186/// heuristic is used to improve diagnostics in the case where an
1187/// out-of-line member function definition doesn't match any
1188/// declaration within the class.
1189static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1190 FunctionDecl *Declaration,
1191 FunctionDecl *Definition) {
1192 if (Declaration->param_size() != Definition->param_size())
1193 return false;
1194 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1195 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1196 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1197
1198 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1199 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1200 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1201 return false;
1202 }
1203
1204 return true;
1205}
1206
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001207Sema::DeclTy *
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001208Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1209 bool IsFunctionDefinition) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001210 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor6704b312008-11-17 22:58:34 +00001211 DeclarationName Name = GetNameForDeclarator(D);
1212
Chris Lattner4b009652007-07-25 00:24:17 +00001213 // All of these full declarators require an identifier. If it doesn't have
1214 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor6704b312008-11-17 22:58:34 +00001215 if (!Name) {
Chris Lattnercd61d592008-11-11 06:13:16 +00001216 if (!D.getInvalidType()) // Reject this if we think it is valid.
1217 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001218 diag::err_declarator_need_ident)
1219 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001220 return 0;
1221 }
1222
Chris Lattnera7549902007-08-26 06:24:45 +00001223 // The scope passed in may not be a decl scope. Zip up the scope tree until
1224 // we find one that is.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001225 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1226 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattnera7549902007-08-26 06:24:45 +00001227 S = S->getParent();
1228
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001229 DeclContext *DC;
1230 Decl *PrevDecl;
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001231 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001232 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +00001233
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001234 // See if this is a redefinition of a variable in the same scope.
1235 if (!D.getCXXScopeSpec().isSet()) {
1236 DC = CurContext;
Douglas Gregor6704b312008-11-17 22:58:34 +00001237 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001238 } else { // Something like "int foo::x;"
1239 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor6704b312008-11-17 22:58:34 +00001240 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001241
1242 // C++ 7.3.1.2p2:
1243 // Members (including explicit specializations of templates) of a named
1244 // namespace can also be defined outside that namespace by explicit
1245 // qualification of the name being defined, provided that the entity being
1246 // defined was already declared in the namespace and the definition appears
1247 // after the point of declaration in a namespace that encloses the
1248 // declarations namespace.
1249 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001250 // Note that we only check the context at this point. We don't yet
1251 // have enough information to make sure that PrevDecl is actually
1252 // the declaration we want to match. For example, given:
1253 //
Douglas Gregor98341042008-12-12 08:25:50 +00001254 // class X {
1255 // void f();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001256 // void f(float);
Douglas Gregor98341042008-12-12 08:25:50 +00001257 // };
1258 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001259 // void X::f(int) { } // ill-formed
1260 //
1261 // In this case, PrevDecl will point to the overload set
1262 // containing the two f's declared in X, but neither of them
1263 // matches.
1264 if (!CurContext->Encloses(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001265 // The qualifying scope doesn't enclose the original declaration.
1266 // Emit diagnostic based on current scope.
1267 SourceLocation L = D.getIdentifierLoc();
1268 SourceRange R = D.getCXXScopeSpec().getRange();
1269 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner254de7d2008-11-23 20:28:15 +00001270 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001271 } else {
Chris Lattner254de7d2008-11-23 20:28:15 +00001272 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattner271d4c22008-11-24 05:29:24 +00001273 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001274 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001275 InvalidDecl = true;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001276 }
1277 }
1278
Douglas Gregor2715a1f2008-12-08 18:40:42 +00001279 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00001280 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001281 InvalidDecl = InvalidDecl
1282 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +00001283 // Just pretend that we didn't see the previous declaration.
1284 PrevDecl = 0;
1285 }
1286
Douglas Gregor1d661552008-04-13 21:07:44 +00001287 // In C++, the previous declaration we find might be a tag type
1288 // (class or enum). In this case, the new declaration will hide the
1289 // tag type.
1290 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1291 PrevDecl = 0;
1292
Chris Lattner82bb4792007-11-14 06:34:38 +00001293 QualType R = GetTypeForDeclarator(D, S);
1294 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1295
Chris Lattner4b009652007-07-25 00:24:17 +00001296 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001297 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1298 InvalidDecl);
Chris Lattner82bb4792007-11-14 06:34:38 +00001299 } else if (R.getTypePtr()->isFunctionType()) {
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001300 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1301 IsFunctionDefinition, InvalidDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001302 } else {
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001303 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1304 InvalidDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001305 }
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001306
1307 if (New == 0)
1308 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001309
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001310 // Set the lexical context. If the declarator has a C++ scope specifier, the
1311 // lexical context will be different from the semantic context.
1312 New->setLexicalDeclContext(CurContext);
1313
Chris Lattner4b009652007-07-25 00:24:17 +00001314 // If this has an identifier, add it to the scope stack.
Douglas Gregor6704b312008-11-17 22:58:34 +00001315 if (Name)
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001316 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001317 // If any semantic error occurred, mark the decl as invalid.
1318 if (D.getInvalidType() || InvalidDecl)
1319 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001320
1321 return New;
1322}
1323
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001324ScopedDecl*
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001325Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1326 QualType R, ScopedDecl* LastDeclarator,
1327 Decl* PrevDecl, bool& InvalidDecl) {
1328 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1329 if (D.getCXXScopeSpec().isSet()) {
1330 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1331 << D.getCXXScopeSpec().getRange();
1332 InvalidDecl = true;
1333 // Pretend we didn't see the scope specifier.
1334 DC = 0;
1335 }
1336
1337 // Check that there are no default arguments (C++ only).
1338 if (getLangOptions().CPlusPlus)
1339 CheckExtraCXXDefaultArguments(D);
1340
1341 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1342 if (!NewTD) return 0;
1343
1344 // Handle attributes prior to checking for duplicates in MergeVarDecl
1345 ProcessDeclAttributes(NewTD, D);
1346 // Merge the decl with the existing one if appropriate. If the decl is
1347 // in an outer scope, it isn't the same thing.
1348 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1349 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1350 if (NewTD == 0) return 0;
1351 }
1352
1353 if (S->getFnParent() == 0) {
1354 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1355 // then it shall have block scope.
1356 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1357 if (NewTD->getUnderlyingType()->isVariableArrayType())
1358 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1359 else
1360 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1361
1362 InvalidDecl = true;
1363 }
1364 }
1365 return NewTD;
1366}
1367
1368ScopedDecl*
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001369Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1370 QualType R, ScopedDecl* LastDeclarator,
1371 Decl* PrevDecl, bool& InvalidDecl) {
1372 DeclarationName Name = GetNameForDeclarator(D);
1373
1374 // Check that there are no default arguments (C++ only).
1375 if (getLangOptions().CPlusPlus)
1376 CheckExtraCXXDefaultArguments(D);
1377
1378 if (R.getTypePtr()->isObjCInterfaceType()) {
1379 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1380 << D.getIdentifier();
1381 InvalidDecl = true;
1382 }
1383
1384 VarDecl *NewVD;
1385 VarDecl::StorageClass SC;
1386 switch (D.getDeclSpec().getStorageClassSpec()) {
1387 default: assert(0 && "Unknown storage class!");
1388 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1389 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1390 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1391 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1392 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1393 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1394 case DeclSpec::SCS_mutable:
1395 // mutable can only appear on non-static class members, so it's always
1396 // an error here
1397 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1398 InvalidDecl = true;
1399 SC = VarDecl::None;
1400 break;
1401 }
1402
1403 IdentifierInfo *II = Name.getAsIdentifierInfo();
1404 if (!II) {
1405 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1406 << Name.getAsString();
1407 return 0;
1408 }
1409
1410 if (DC->isRecord()) {
1411 // This is a static data member for a C++ class.
1412 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1413 D.getIdentifierLoc(), II,
1414 R, LastDeclarator);
1415 } else {
1416 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1417 if (S->getFnParent() == 0) {
1418 // C99 6.9p2: The storage-class specifiers auto and register shall not
1419 // appear in the declaration specifiers in an external declaration.
1420 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1421 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1422 InvalidDecl = true;
1423 }
1424 }
1425 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1426 II, R, SC, LastDeclarator,
1427 // FIXME: Move to DeclGroup...
1428 D.getDeclSpec().getSourceRange().getBegin());
1429 NewVD->setThreadSpecified(ThreadSpecified);
1430 }
1431 // Handle attributes prior to checking for duplicates in MergeVarDecl
1432 ProcessDeclAttributes(NewVD, D);
1433
1434 // Handle GNU asm-label extension (encoded as an attribute).
1435 if (Expr *E = (Expr*) D.getAsmLabel()) {
1436 // The parser guarantees this is a string.
1437 StringLiteral *SE = cast<StringLiteral>(E);
1438 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1439 SE->getByteLength())));
1440 }
1441
1442 // Emit an error if an address space was applied to decl with local storage.
1443 // This includes arrays of objects with address space qualifiers, but not
1444 // automatic variables that point to other address spaces.
1445 // ISO/IEC TR 18037 S5.1.2
1446 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1447 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1448 InvalidDecl = true;
1449 }
1450 // Merge the decl with the existing one if appropriate. If the decl is
1451 // in an outer scope, it isn't the same thing.
1452 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1453 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1454 // The user tried to define a non-static data member
1455 // out-of-line (C++ [dcl.meaning]p1).
1456 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1457 << D.getCXXScopeSpec().getRange();
1458 NewVD->Destroy(Context);
1459 return 0;
1460 }
1461
1462 NewVD = MergeVarDecl(NewVD, PrevDecl);
1463 if (NewVD == 0) return 0;
1464
1465 if (D.getCXXScopeSpec().isSet()) {
1466 // No previous declaration in the qualifying scope.
1467 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1468 << Name << D.getCXXScopeSpec().getRange();
1469 InvalidDecl = true;
1470 }
1471 }
1472 return NewVD;
1473}
1474
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001475ScopedDecl*
1476Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1477 QualType R, ScopedDecl *LastDeclarator,
1478 Decl* PrevDecl, bool IsFunctionDefinition,
1479 bool& InvalidDecl) {
1480 assert(R.getTypePtr()->isFunctionType());
1481
1482 DeclarationName Name = GetNameForDeclarator(D);
1483 FunctionDecl::StorageClass SC = FunctionDecl::None;
1484 switch (D.getDeclSpec().getStorageClassSpec()) {
1485 default: assert(0 && "Unknown storage class!");
1486 case DeclSpec::SCS_auto:
1487 case DeclSpec::SCS_register:
1488 case DeclSpec::SCS_mutable:
1489 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1490 InvalidDecl = true;
1491 break;
1492 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1493 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1494 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
1495 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1496 }
1497
1498 bool isInline = D.getDeclSpec().isInlineSpecified();
1499 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1500 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1501
1502 FunctionDecl *NewFD;
1503 if (D.getKind() == Declarator::DK_Constructor) {
1504 // This is a C++ constructor declaration.
1505 assert(DC->isRecord() &&
1506 "Constructors can only be declared in a member context");
1507
1508 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1509
1510 // Create the new declaration
1511 NewFD = CXXConstructorDecl::Create(Context,
1512 cast<CXXRecordDecl>(DC),
1513 D.getIdentifierLoc(), Name, R,
1514 isExplicit, isInline,
1515 /*isImplicitlyDeclared=*/false);
1516
1517 if (InvalidDecl)
1518 NewFD->setInvalidDecl();
1519 } else if (D.getKind() == Declarator::DK_Destructor) {
1520 // This is a C++ destructor declaration.
1521 if (DC->isRecord()) {
1522 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1523
1524 NewFD = CXXDestructorDecl::Create(Context,
1525 cast<CXXRecordDecl>(DC),
1526 D.getIdentifierLoc(), Name, R,
1527 isInline,
1528 /*isImplicitlyDeclared=*/false);
1529
1530 if (InvalidDecl)
1531 NewFD->setInvalidDecl();
1532 } else {
1533 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1534
1535 // Create a FunctionDecl to satisfy the function definition parsing
1536 // code path.
1537 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
1538 Name, R, SC, isInline, LastDeclarator,
1539 // FIXME: Move to DeclGroup...
1540 D.getDeclSpec().getSourceRange().getBegin());
1541 InvalidDecl = true;
1542 NewFD->setInvalidDecl();
1543 }
1544 } else if (D.getKind() == Declarator::DK_Conversion) {
1545 if (!DC->isRecord()) {
1546 Diag(D.getIdentifierLoc(),
1547 diag::err_conv_function_not_member);
1548 return 0;
1549 } else {
1550 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1551
1552 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1553 D.getIdentifierLoc(), Name, R,
1554 isInline, isExplicit);
1555
1556 if (InvalidDecl)
1557 NewFD->setInvalidDecl();
1558 }
1559 } else if (DC->isRecord()) {
1560 // This is a C++ method declaration.
1561 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1562 D.getIdentifierLoc(), Name, R,
1563 (SC == FunctionDecl::Static), isInline,
1564 LastDeclarator);
1565 } else {
1566 NewFD = FunctionDecl::Create(Context, DC,
1567 D.getIdentifierLoc(),
1568 Name, R, SC, isInline, LastDeclarator,
1569 // FIXME: Move to DeclGroup...
1570 D.getDeclSpec().getSourceRange().getBegin());
1571 }
1572
1573 // Set the lexical context. If the declarator has a C++
1574 // scope specifier, the lexical context will be different
1575 // from the semantic context.
1576 NewFD->setLexicalDeclContext(CurContext);
1577
1578 // Handle GNU asm-label extension (encoded as an attribute).
1579 if (Expr *E = (Expr*) D.getAsmLabel()) {
1580 // The parser guarantees this is a string.
1581 StringLiteral *SE = cast<StringLiteral>(E);
1582 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1583 SE->getByteLength())));
1584 }
1585
1586 // Copy the parameter declarations from the declarator D to
1587 // the function declaration NewFD, if they are available.
1588 if (D.getNumTypeObjects() > 0) {
1589 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1590
1591 // Create Decl objects for each parameter, adding them to the
1592 // FunctionDecl.
1593 llvm::SmallVector<ParmVarDecl*, 16> Params;
1594
1595 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1596 // function that takes no arguments, not a function that takes a
1597 // single void argument.
1598 // We let through "const void" here because Sema::GetTypeForDeclarator
1599 // already checks for that case.
1600 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1601 FTI.ArgInfo[0].Param &&
1602 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1603 // empty arg list, don't push any params.
1604 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1605
1606 // In C++, the empty parameter-type-list must be spelled "void"; a
1607 // typedef of void is not permitted.
1608 if (getLangOptions().CPlusPlus &&
1609 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1610 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1611 }
1612 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1613 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1614 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1615 }
1616
1617 NewFD->setParams(Context, &Params[0], Params.size());
1618 } else if (R->getAsTypedefType()) {
1619 // When we're declaring a function with a typedef, as in the
1620 // following example, we'll need to synthesize (unnamed)
1621 // parameters for use in the declaration.
1622 //
1623 // @code
1624 // typedef void fn(int);
1625 // fn f;
1626 // @endcode
1627 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1628 if (!FT) {
1629 // This is a typedef of a function with no prototype, so we
1630 // don't need to do anything.
1631 } else if ((FT->getNumArgs() == 0) ||
1632 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1633 FT->getArgType(0)->isVoidType())) {
1634 // This is a zero-argument function. We don't need to do anything.
1635 } else {
1636 // Synthesize a parameter for each argument type.
1637 llvm::SmallVector<ParmVarDecl*, 16> Params;
1638 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1639 ArgType != FT->arg_type_end(); ++ArgType) {
1640 Params.push_back(ParmVarDecl::Create(Context, DC,
1641 SourceLocation(), 0,
1642 *ArgType, VarDecl::None,
1643 0, 0));
1644 }
1645
1646 NewFD->setParams(Context, &Params[0], Params.size());
1647 }
1648 }
1649
1650 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1651 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1652 else if (isa<CXXDestructorDecl>(NewFD)) {
1653 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1654 Record->setUserDeclaredDestructor(true);
1655 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1656 // user-defined destructor.
1657 Record->setPOD(false);
1658 } else if (CXXConversionDecl *Conversion =
1659 dyn_cast<CXXConversionDecl>(NewFD))
1660 ActOnConversionDeclarator(Conversion);
1661
1662 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1663 if (NewFD->isOverloadedOperator() &&
1664 CheckOverloadedOperatorDeclaration(NewFD))
1665 NewFD->setInvalidDecl();
1666
1667 // Merge the decl with the existing one if appropriate. Since C functions
1668 // are in a flat namespace, make sure we consider decls in outer scopes.
1669 if (PrevDecl &&
1670 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1671 bool Redeclaration = false;
1672
1673 // If C++, determine whether NewFD is an overload of PrevDecl or
1674 // a declaration that requires merging. If it's an overload,
1675 // there's no more work to do here; we'll just add the new
1676 // function to the scope.
1677 OverloadedFunctionDecl::function_iterator MatchedDecl;
1678 if (!getLangOptions().CPlusPlus ||
1679 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1680 Decl *OldDecl = PrevDecl;
1681
1682 // If PrevDecl was an overloaded function, extract the
1683 // FunctionDecl that matched.
1684 if (isa<OverloadedFunctionDecl>(PrevDecl))
1685 OldDecl = *MatchedDecl;
1686
1687 // NewFD and PrevDecl represent declarations that need to be
1688 // merged.
1689 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1690
1691 if (NewFD == 0) return 0;
1692 if (Redeclaration) {
1693 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1694
1695 // An out-of-line member function declaration must also be a
1696 // definition (C++ [dcl.meaning]p1).
1697 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1698 !InvalidDecl) {
1699 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1700 << D.getCXXScopeSpec().getRange();
1701 NewFD->setInvalidDecl();
1702 }
1703 }
1704 }
1705
1706 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1707 // The user tried to provide an out-of-line definition for a
1708 // member function, but there was no such member function
1709 // declared (C++ [class.mfct]p2). For example:
1710 //
1711 // class X {
1712 // void f() const;
1713 // };
1714 //
1715 // void X::f() { } // ill-formed
1716 //
1717 // Complain about this problem, and attempt to suggest close
1718 // matches (e.g., those that differ only in cv-qualifiers and
1719 // whether the parameter types are references).
1720 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1721 << cast<CXXRecordDecl>(DC)->getDeclName()
1722 << D.getCXXScopeSpec().getRange();
1723 InvalidDecl = true;
1724
1725 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1726 if (!PrevDecl) {
1727 // Nothing to suggest.
1728 } else if (OverloadedFunctionDecl *Ovl
1729 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1730 for (OverloadedFunctionDecl::function_iterator
1731 Func = Ovl->function_begin(),
1732 FuncEnd = Ovl->function_end();
1733 Func != FuncEnd; ++Func) {
1734 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1735 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1736
1737 }
1738 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1739 // Suggest this no matter how mismatched it is; it's the only
1740 // thing we have.
1741 unsigned diag;
1742 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1743 diag = diag::note_member_def_close_match;
1744 else if (Method->getBody())
1745 diag = diag::note_previous_definition;
1746 else
1747 diag = diag::note_previous_declaration;
1748 Diag(Method->getLocation(), diag);
1749 }
1750
1751 PrevDecl = 0;
1752 }
1753 }
1754 // Handle attributes. We need to have merged decls when handling attributes
1755 // (for example to check for conflicts, etc).
1756 ProcessDeclAttributes(NewFD, D);
1757
1758 if (getLangOptions().CPlusPlus) {
1759 // In C++, check default arguments now that we have merged decls.
1760 CheckCXXDefaultArguments(NewFD);
1761
1762 // An out-of-line member function declaration must also be a
1763 // definition (C++ [dcl.meaning]p1).
1764 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1765 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1766 << D.getCXXScopeSpec().getRange();
1767 InvalidDecl = true;
1768 }
1769 }
1770 return NewFD;
1771}
1772
Steve Narofffc08f5e2008-10-27 11:34:16 +00001773void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001774 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1775 << Init->getSourceRange();
Steve Narofffc08f5e2008-10-27 11:34:16 +00001776}
1777
Eli Friedman02c22ce2008-05-20 13:48:25 +00001778bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1779 switch (Init->getStmtClass()) {
1780 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001781 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001782 return true;
1783 case Expr::ParenExprClass: {
1784 const ParenExpr* PE = cast<ParenExpr>(Init);
1785 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1786 }
1787 case Expr::CompoundLiteralExprClass:
1788 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor566782a2009-01-06 05:10:23 +00001789 case Expr::DeclRefExprClass:
1790 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001791 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001792 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1793 if (VD->hasGlobalStorage())
1794 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001795 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001796 return true;
1797 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001798 if (isa<FunctionDecl>(D))
1799 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001800 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001801 return true;
1802 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001803 case Expr::MemberExprClass: {
1804 const MemberExpr *M = cast<MemberExpr>(Init);
1805 if (M->isArrow())
1806 return CheckAddressConstantExpression(M->getBase());
1807 return CheckAddressConstantExpressionLValue(M->getBase());
1808 }
1809 case Expr::ArraySubscriptExprClass: {
1810 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1811 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1812 return CheckAddressConstantExpression(ASE->getBase()) ||
1813 CheckArithmeticConstantExpression(ASE->getIdx());
1814 }
1815 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001816 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001817 return false;
1818 case Expr::UnaryOperatorClass: {
1819 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1820
1821 // C99 6.6p9
1822 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001823 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001824
Steve Narofffc08f5e2008-10-27 11:34:16 +00001825 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001826 return true;
1827 }
1828 }
1829}
1830
1831bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1832 switch (Init->getStmtClass()) {
1833 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001834 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001835 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001836 case Expr::ParenExprClass:
1837 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001838 case Expr::StringLiteralClass:
1839 case Expr::ObjCStringLiteralClass:
1840 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001841 case Expr::CallExprClass:
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001842 case Expr::CXXOperatorCallExprClass:
Chris Lattner0903cba2008-10-06 07:26:43 +00001843 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1844 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1845 Builtin::BI__builtin___CFStringMakeConstantString)
1846 return false;
1847
Steve Narofffc08f5e2008-10-27 11:34:16 +00001848 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001849 return true;
1850
Eli Friedman02c22ce2008-05-20 13:48:25 +00001851 case Expr::UnaryOperatorClass: {
1852 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1853
1854 // C99 6.6p9
1855 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1856 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1857
1858 if (Exp->getOpcode() == UnaryOperator::Extension)
1859 return CheckAddressConstantExpression(Exp->getSubExpr());
1860
Steve Narofffc08f5e2008-10-27 11:34:16 +00001861 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001862 return true;
1863 }
1864 case Expr::BinaryOperatorClass: {
1865 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1866 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1867
1868 Expr *PExp = Exp->getLHS();
1869 Expr *IExp = Exp->getRHS();
1870 if (IExp->getType()->isPointerType())
1871 std::swap(PExp, IExp);
1872
1873 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1874 return CheckAddressConstantExpression(PExp) ||
1875 CheckArithmeticConstantExpression(IExp);
1876 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001877 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001878 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001879 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001880 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1881 // Check for implicit promotion
1882 if (SubExpr->getType()->isFunctionType() ||
1883 SubExpr->getType()->isArrayType())
1884 return CheckAddressConstantExpressionLValue(SubExpr);
1885 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001886
1887 // Check for pointer->pointer cast
1888 if (SubExpr->getType()->isPointerType())
1889 return CheckAddressConstantExpression(SubExpr);
1890
Eli Friedman1fad3c62008-08-25 20:46:57 +00001891 if (SubExpr->getType()->isIntegralType()) {
1892 // Check for the special-case of a pointer->int->pointer cast;
1893 // this isn't standard, but some code requires it. See
1894 // PR2720 for an example.
1895 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1896 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1897 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1898 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1899 if (IntWidth >= PointerWidth) {
1900 return CheckAddressConstantExpression(SubCast->getSubExpr());
1901 }
1902 }
1903 }
1904 }
1905 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001906 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001907 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001908
Steve Narofffc08f5e2008-10-27 11:34:16 +00001909 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001910 return true;
1911 }
1912 case Expr::ConditionalOperatorClass: {
1913 // FIXME: Should we pedwarn here?
1914 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1915 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001916 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001917 return true;
1918 }
1919 if (CheckArithmeticConstantExpression(Exp->getCond()))
1920 return true;
1921 if (Exp->getLHS() &&
1922 CheckAddressConstantExpression(Exp->getLHS()))
1923 return true;
1924 return CheckAddressConstantExpression(Exp->getRHS());
1925 }
1926 case Expr::AddrLabelExprClass:
1927 return false;
1928 }
1929}
1930
Eli Friedman998dffb2008-06-09 05:05:07 +00001931static const Expr* FindExpressionBaseAddress(const Expr* E);
1932
1933static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1934 switch (E->getStmtClass()) {
1935 default:
1936 return E;
1937 case Expr::ParenExprClass: {
1938 const ParenExpr* PE = cast<ParenExpr>(E);
1939 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1940 }
1941 case Expr::MemberExprClass: {
1942 const MemberExpr *M = cast<MemberExpr>(E);
1943 if (M->isArrow())
1944 return FindExpressionBaseAddress(M->getBase());
1945 return FindExpressionBaseAddressLValue(M->getBase());
1946 }
1947 case Expr::ArraySubscriptExprClass: {
1948 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1949 return FindExpressionBaseAddress(ASE->getBase());
1950 }
1951 case Expr::UnaryOperatorClass: {
1952 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1953
1954 if (Exp->getOpcode() == UnaryOperator::Deref)
1955 return FindExpressionBaseAddress(Exp->getSubExpr());
1956
1957 return E;
1958 }
1959 }
1960}
1961
1962static const Expr* FindExpressionBaseAddress(const Expr* E) {
1963 switch (E->getStmtClass()) {
1964 default:
1965 return E;
1966 case Expr::ParenExprClass: {
1967 const ParenExpr* PE = cast<ParenExpr>(E);
1968 return FindExpressionBaseAddress(PE->getSubExpr());
1969 }
1970 case Expr::UnaryOperatorClass: {
1971 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1972
1973 // C99 6.6p9
1974 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1975 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1976
1977 if (Exp->getOpcode() == UnaryOperator::Extension)
1978 return FindExpressionBaseAddress(Exp->getSubExpr());
1979
1980 return E;
1981 }
1982 case Expr::BinaryOperatorClass: {
1983 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1984
1985 Expr *PExp = Exp->getLHS();
1986 Expr *IExp = Exp->getRHS();
1987 if (IExp->getType()->isPointerType())
1988 std::swap(PExp, IExp);
1989
1990 return FindExpressionBaseAddress(PExp);
1991 }
1992 case Expr::ImplicitCastExprClass: {
1993 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1994
1995 // Check for implicit promotion
1996 if (SubExpr->getType()->isFunctionType() ||
1997 SubExpr->getType()->isArrayType())
1998 return FindExpressionBaseAddressLValue(SubExpr);
1999
2000 // Check for pointer->pointer cast
2001 if (SubExpr->getType()->isPointerType())
2002 return FindExpressionBaseAddress(SubExpr);
2003
2004 // We assume that we have an arithmetic expression here;
2005 // if we don't, we'll figure it out later
2006 return 0;
2007 }
Douglas Gregor035d0882008-10-28 15:36:24 +00002008 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00002009 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2010
2011 // Check for pointer->pointer cast
2012 if (SubExpr->getType()->isPointerType())
2013 return FindExpressionBaseAddress(SubExpr);
2014
2015 // We assume that we have an arithmetic expression here;
2016 // if we don't, we'll figure it out later
2017 return 0;
2018 }
2019 }
2020}
2021
Anders Carlssone8bd9f22008-11-22 21:04:56 +00002022bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002023 switch (Init->getStmtClass()) {
2024 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00002025 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002026 return true;
2027 case Expr::ParenExprClass: {
2028 const ParenExpr* PE = cast<ParenExpr>(Init);
2029 return CheckArithmeticConstantExpression(PE->getSubExpr());
2030 }
2031 case Expr::FloatingLiteralClass:
2032 case Expr::IntegerLiteralClass:
2033 case Expr::CharacterLiteralClass:
2034 case Expr::ImaginaryLiteralClass:
2035 case Expr::TypesCompatibleExprClass:
2036 case Expr::CXXBoolLiteralExprClass:
2037 return false;
Douglas Gregor65fedaf2008-11-14 16:09:21 +00002038 case Expr::CallExprClass:
2039 case Expr::CXXOperatorCallExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002040 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002041
2042 // Allow any constant foldable calls to builtins.
2043 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002044 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002045
Steve Narofffc08f5e2008-10-27 11:34:16 +00002046 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002047 return true;
2048 }
Douglas Gregor566782a2009-01-06 05:10:23 +00002049 case Expr::DeclRefExprClass:
2050 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002051 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2052 if (isa<EnumConstantDecl>(D))
2053 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002054 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002055 return true;
2056 }
2057 case Expr::CompoundLiteralExprClass:
2058 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2059 // but vectors are allowed to be magic.
2060 if (Init->getType()->isVectorType())
2061 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002062 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002063 return true;
2064 case Expr::UnaryOperatorClass: {
2065 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2066
2067 switch (Exp->getOpcode()) {
2068 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2069 // See C99 6.6p3.
2070 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00002071 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002072 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002073 case UnaryOperator::OffsetOf:
Eli Friedman02c22ce2008-05-20 13:48:25 +00002074 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2075 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002076 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002077 return true;
2078 case UnaryOperator::Extension:
2079 case UnaryOperator::LNot:
2080 case UnaryOperator::Plus:
2081 case UnaryOperator::Minus:
2082 case UnaryOperator::Not:
2083 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2084 }
2085 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002086 case Expr::SizeOfAlignOfExprClass: {
2087 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002088 // Special check for void types, which are allowed as an extension
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002089 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedman02c22ce2008-05-20 13:48:25 +00002090 return false;
2091 // alignof always evaluates to a constant.
2092 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002093 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00002094 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002095 return true;
2096 }
2097 return false;
2098 }
2099 case Expr::BinaryOperatorClass: {
2100 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2101
2102 if (Exp->getLHS()->getType()->isArithmeticType() &&
2103 Exp->getRHS()->getType()->isArithmeticType()) {
2104 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2105 CheckArithmeticConstantExpression(Exp->getRHS());
2106 }
2107
Eli Friedman998dffb2008-06-09 05:05:07 +00002108 if (Exp->getLHS()->getType()->isPointerType() &&
2109 Exp->getRHS()->getType()->isPointerType()) {
2110 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2111 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2112
2113 // Only allow a null (constant integer) base; we could
2114 // allow some additional cases if necessary, but this
2115 // is sufficient to cover offsetof-like constructs.
2116 if (!LHSBase && !RHSBase) {
2117 return CheckAddressConstantExpression(Exp->getLHS()) ||
2118 CheckAddressConstantExpression(Exp->getRHS());
2119 }
2120 }
2121
Steve Narofffc08f5e2008-10-27 11:34:16 +00002122 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002123 return true;
2124 }
2125 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00002126 case Expr::CStyleCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002127 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00002128 if (SubExpr->getType()->isArithmeticType())
2129 return CheckArithmeticConstantExpression(SubExpr);
2130
Eli Friedman266df142008-09-02 09:37:00 +00002131 if (SubExpr->getType()->isPointerType()) {
2132 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2133 // If the pointer has a null base, this is an offsetof-like construct
2134 if (!Base)
2135 return CheckAddressConstantExpression(SubExpr);
2136 }
2137
Steve Narofffc08f5e2008-10-27 11:34:16 +00002138 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00002139 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002140 }
2141 case Expr::ConditionalOperatorClass: {
2142 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00002143
2144 // If GNU extensions are disabled, we require all operands to be arithmetic
2145 // constant expressions.
2146 if (getLangOptions().NoExtensions) {
2147 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2148 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2149 CheckArithmeticConstantExpression(Exp->getRHS());
2150 }
2151
2152 // Otherwise, we have to emulate some of the behavior of fold here.
2153 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2154 // because it can constant fold things away. To retain compatibility with
2155 // GCC code, we see if we can fold the condition to a constant (which we
2156 // should always be able to do in theory). If so, we only require the
2157 // specified arm of the conditional to be a constant. This is a horrible
2158 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson8c3de802008-12-19 20:58:05 +00002159 Expr::EvalResult EvalResult;
2160 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2161 EvalResult.HasSideEffects) {
Chris Lattneref069662008-11-16 21:24:15 +00002162 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner94d45412008-10-06 05:42:39 +00002163 // won't be able to either. Use it to emit the diagnostic though.
2164 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattneref069662008-11-16 21:24:15 +00002165 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner94d45412008-10-06 05:42:39 +00002166 return Res;
2167 }
2168
2169 // Verify that the side following the condition is also a constant.
2170 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson8c3de802008-12-19 20:58:05 +00002171 if (EvalResult.Val.getInt() == 0)
Chris Lattner94d45412008-10-06 05:42:39 +00002172 std::swap(TrueSide, FalseSide);
2173
2174 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002175 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00002176
2177 // Okay, the evaluated side evaluates to a constant, so we accept this.
2178 // Check to see if the other side is obviously not a constant. If so,
2179 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002180 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00002181 Diag(Init->getExprLoc(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00002182 diag::ext_typecheck_expression_not_constant_but_accepted)
2183 << FalseSide->getSourceRange();
Chris Lattner94d45412008-10-06 05:42:39 +00002184 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002185 }
2186 }
2187}
2188
2189bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopese7280452008-07-07 16:46:50 +00002190 Init = Init->IgnoreParens();
2191
Nate Begemand6d2f772009-01-18 03:20:47 +00002192 if (Init->isEvaluatable(Context))
Anders Carlssonf6791c62008-12-05 05:09:56 +00002193 return false;
2194
Eli Friedman02c22ce2008-05-20 13:48:25 +00002195 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2196 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2197 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2198
Nuno Lopese7280452008-07-07 16:46:50 +00002199 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2200 return CheckForConstantInitializer(e->getInitializer(), DclT);
2201
Eli Friedman02c22ce2008-05-20 13:48:25 +00002202 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2203 unsigned numInits = Exp->getNumInits();
2204 for (unsigned i = 0; i < numInits; i++) {
2205 // FIXME: Need to get the type of the declaration for C++,
2206 // because it could be a reference?
2207 if (CheckForConstantInitializer(Exp->getInit(i),
2208 Exp->getInit(i)->getType()))
2209 return true;
2210 }
2211 return false;
2212 }
2213
Anders Carlssonf6791c62008-12-05 05:09:56 +00002214 // FIXME: We can probably remove some of this code below, now that
2215 // Expr::Evaluate is doing the heavy lifting for scalars.
2216
Eli Friedman02c22ce2008-05-20 13:48:25 +00002217 if (Init->isNullPointerConstant(Context))
2218 return false;
2219 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002220 QualType InitTy = Context.getCanonicalType(Init->getType())
2221 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00002222 if (InitTy == Context.BoolTy) {
2223 // Special handling for pointers implicitly cast to bool;
2224 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2225 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2226 Expr* SubE = ICE->getSubExpr();
2227 if (SubE->getType()->isPointerType() ||
2228 SubE->getType()->isArrayType() ||
2229 SubE->getType()->isFunctionType()) {
2230 return CheckAddressConstantExpression(Init);
2231 }
2232 }
2233 } else if (InitTy->isIntegralType()) {
2234 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002235 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00002236 SubE = CE->getSubExpr();
2237 // Special check for pointer cast to int; we allow as an extension
2238 // an address constant cast to an integer if the integer
2239 // is of an appropriate width (this sort of code is apparently used
2240 // in some places).
2241 // FIXME: Add pedwarn?
2242 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2243 if (SubE && (SubE->getType()->isPointerType() ||
2244 SubE->getType()->isArrayType() ||
2245 SubE->getType()->isFunctionType())) {
2246 unsigned IntWidth = Context.getTypeSize(Init->getType());
2247 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2248 if (IntWidth >= PointerWidth)
2249 return CheckAddressConstantExpression(Init);
2250 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00002251 }
2252
2253 return CheckArithmeticConstantExpression(Init);
2254 }
2255
2256 if (Init->getType()->isPointerType())
2257 return CheckAddressConstantExpression(Init);
2258
Eli Friedman25086f02008-05-30 18:14:48 +00002259 // An array type at the top level that isn't an init-list must
2260 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00002261 if (Init->getType()->isArrayType())
2262 return false;
2263
Nuno Lopes1dc26762008-09-01 18:42:41 +00002264 if (Init->getType()->isFunctionType())
2265 return false;
2266
Steve Naroffdff3fb22008-10-02 17:12:56 +00002267 // Allow block exprs at top level.
2268 if (Init->getType()->isBlockPointerType())
2269 return false;
Nuno Lopes8260d5d2009-01-15 16:44:45 +00002270
2271 // GCC cast to union extension
2272 // note: the validity of the cast expr is checked by CheckCastTypes()
2273 if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2274 QualType T = C->getType();
2275 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2276 }
2277
Steve Narofffc08f5e2008-10-27 11:34:16 +00002278 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002279 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00002280}
2281
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002282void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002283 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2284}
2285
2286/// AddInitializerToDecl - Adds the initializer Init to the
2287/// declaration dcl. If DirectInit is true, this is C++ direct
2288/// initialization rather than copy initialization.
2289void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002290 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002291 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002292 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00002293
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002294 // If there is no declaration, there was an error parsing it. Just ignore
2295 // the initializer.
2296 if (RealDecl == 0) {
2297 delete Init;
2298 return;
2299 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002300
Steve Naroff420d0f52007-09-12 20:13:48 +00002301 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2302 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00002303 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2304 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00002305 RealDecl->setInvalidDecl();
2306 return;
2307 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002308 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00002309 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00002310 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002311 if (VDecl->isBlockVarDecl()) {
2312 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002313 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00002314 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002315 VDecl->setInvalidDecl();
2316 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002317 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002318 VDecl->getDeclName(), DirectInit))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002319 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00002320
2321 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2322 if (!getLangOptions().CPlusPlus) {
2323 if (SC == VarDecl::Static) // C99 6.7.8p4.
2324 CheckForConstantInitializer(Init, DclT);
2325 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002326 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002327 } else if (VDecl->isFileVarDecl()) {
2328 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00002329 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002330 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00002331 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002332 VDecl->getDeclName(), DirectInit))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002333 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00002334
Anders Carlssonea7140a2008-08-22 05:00:02 +00002335 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2336 if (!getLangOptions().CPlusPlus) {
2337 // C99 6.7.8p4. All file scoped initializers need to be constant.
2338 CheckForConstantInitializer(Init, DclT);
2339 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002340 }
2341 // If the type changed, it means we had an incomplete type that was
2342 // completed by the initializer. For example:
2343 // int ary[] = { 1, 3, 5 };
2344 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00002345 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002346 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00002347 Init->setType(DclT);
2348 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002349
2350 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00002351 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00002352 return;
2353}
2354
Douglas Gregor81c29152008-10-29 00:13:59 +00002355void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2356 Decl *RealDecl = static_cast<Decl *>(dcl);
2357
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00002358 // If there is no declaration, there was an error parsing it. Just ignore it.
2359 if (RealDecl == 0)
2360 return;
2361
Douglas Gregor81c29152008-10-29 00:13:59 +00002362 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2363 QualType Type = Var->getType();
2364 // C++ [dcl.init.ref]p3:
2365 // The initializer can be omitted for a reference only in a
2366 // parameter declaration (8.3.5), in the declaration of a
2367 // function return type, in the declaration of a class member
2368 // within its class declaration (9.2), and where the extern
2369 // specifier is explicitly used.
Douglas Gregorb9213832008-12-15 21:24:18 +00002370 if (Type->isReferenceType() &&
2371 Var->getStorageClass() != VarDecl::Extern &&
2372 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002373 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattner271d4c22008-11-24 05:29:24 +00002374 << Var->getDeclName()
2375 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor5870a952008-11-03 20:45:27 +00002376 Var->setInvalidDecl();
2377 return;
2378 }
2379
2380 // C++ [dcl.init]p9:
2381 //
2382 // If no initializer is specified for an object, and the object
2383 // is of (possibly cv-qualified) non-POD class type (or array
2384 // thereof), the object shall be default-initialized; if the
2385 // object is of const-qualified type, the underlying class type
2386 // shall have a user-declared default constructor.
2387 if (getLangOptions().CPlusPlus) {
2388 QualType InitType = Type;
2389 if (const ArrayType *Array = Context.getAsArrayType(Type))
2390 InitType = Array->getElementType();
Douglas Gregorb9213832008-12-15 21:24:18 +00002391 if (Var->getStorageClass() != VarDecl::Extern &&
2392 Var->getStorageClass() != VarDecl::PrivateExtern &&
2393 InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002394 const CXXConstructorDecl *Constructor
2395 = PerformInitializationByConstructor(InitType, 0, 0,
2396 Var->getLocation(),
2397 SourceRange(Var->getLocation(),
2398 Var->getLocation()),
Chris Lattner271d4c22008-11-24 05:29:24 +00002399 Var->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00002400 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00002401 if (!Constructor)
2402 Var->setInvalidDecl();
2403 }
2404 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002405
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002406#if 0
2407 // FIXME: Temporarily disabled because we are not properly parsing
2408 // linkage specifications on declarations, e.g.,
2409 //
2410 // extern "C" const CGPoint CGPointerZero;
2411 //
Douglas Gregor81c29152008-10-29 00:13:59 +00002412 // C++ [dcl.init]p9:
2413 //
2414 // If no initializer is specified for an object, and the
2415 // object is of (possibly cv-qualified) non-POD class type (or
2416 // array thereof), the object shall be default-initialized; if
2417 // the object is of const-qualified type, the underlying class
2418 // type shall have a user-declared default
2419 // constructor. Otherwise, if no initializer is specified for
2420 // an object, the object and its subobjects, if any, have an
2421 // indeterminate initial value; if the object or any of its
2422 // subobjects are of const-qualified type, the program is
2423 // ill-formed.
2424 //
2425 // This isn't technically an error in C, so we don't diagnose it.
2426 //
2427 // FIXME: Actually perform the POD/user-defined default
2428 // constructor check.
2429 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002430 Context.getCanonicalType(Type).isConstQualified() &&
2431 Var->getStorageClass() != VarDecl::Extern)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002432 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2433 << Var->getName()
2434 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002435#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00002436 }
2437}
2438
Chris Lattner4b009652007-07-25 00:24:17 +00002439/// The declarators are chained together backwards, reverse the list.
2440Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2441 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002442 Decl *GroupDecl = static_cast<Decl*>(group);
2443 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00002444 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00002445
2446 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2447 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002448 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00002449 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002450 else { // reverse the list.
2451 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00002452 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002453 Group->setNextDeclarator(NewGroup);
2454 NewGroup = Group;
2455 Group = Next;
2456 }
2457 }
2458 // Perform semantic analysis that depends on having fully processed both
2459 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002460 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00002461 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2462 if (!IDecl)
2463 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002464 QualType T = IDecl->getType();
2465
Anders Carlsson68adbd12008-12-07 00:20:55 +00002466 if (T->isVariableArrayType()) {
Anders Carlssonef2f7df2008-12-20 21:51:53 +00002467 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002468
2469 // FIXME: This won't give the correct result for
2470 // int a[10][n];
2471 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002472 if (IDecl->isFileVarDecl()) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002473 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2474 SizeRange;
2475
Eli Friedman8ff07782008-02-15 18:16:39 +00002476 IDecl->setInvalidDecl();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002477 } else {
2478 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2479 // static storage duration, it shall not have a variable length array.
2480 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002481 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2482 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002483 IDecl->setInvalidDecl();
2484 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002485 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2486 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002487 IDecl->setInvalidDecl();
2488 }
2489 }
2490 } else if (T->isVariablyModifiedType()) {
2491 if (IDecl->isFileVarDecl()) {
2492 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2493 IDecl->setInvalidDecl();
2494 } else {
2495 if (IDecl->getStorageClass() == VarDecl::Extern) {
2496 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2497 IDecl->setInvalidDecl();
2498 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002499 }
2500 }
Anders Carlsson68adbd12008-12-07 00:20:55 +00002501
Steve Naroff6a0e2092007-09-12 14:07:44 +00002502 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2503 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002504 if (IDecl->isBlockVarDecl() &&
2505 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00002506 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner271d4c22008-11-24 05:29:24 +00002507 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002508 IDecl->setInvalidDecl();
2509 }
2510 }
2511 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2512 // object that has file scope without an initializer, and without a
2513 // storage-class specifier or with the storage-class specifier "static",
2514 // constitutes a tentative definition. Note: A tentative definition with
2515 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00002516 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00002517 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00002518 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2519 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00002520 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00002521 // C99 6.9.2p3: If the declaration of an identifier for an object is
2522 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2523 // declared type shall not be an incomplete type.
Chris Lattner271d4c22008-11-24 05:29:24 +00002524 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002525 IDecl->setInvalidDecl();
2526 }
2527 }
Steve Naroffb5e78152008-08-08 17:50:35 +00002528 if (IDecl->isFileVarDecl())
2529 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002530 }
2531 return NewGroup;
2532}
Steve Naroff91b03f72007-08-28 03:03:08 +00002533
Chris Lattner3e254fb2008-04-08 04:40:51 +00002534/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2535/// to introduce parameters into function prototype scope.
2536Sema::DeclTy *
2537Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00002538 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002539
Chris Lattner3e254fb2008-04-08 04:40:51 +00002540 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002541 VarDecl::StorageClass StorageClass = VarDecl::None;
2542 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2543 StorageClass = VarDecl::Register;
2544 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002545 Diag(DS.getStorageClassSpecLoc(),
2546 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002547 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002548 }
2549 if (DS.isThreadSpecified()) {
2550 Diag(DS.getThreadSpecLoc(),
2551 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002552 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002553 }
2554
Douglas Gregor2b9422f2008-05-07 04:49:29 +00002555 // Check that there are no default arguments inside the type of this
2556 // parameter (C++ only).
2557 if (getLangOptions().CPlusPlus)
2558 CheckExtraCXXDefaultArguments(D);
2559
Chris Lattner3e254fb2008-04-08 04:40:51 +00002560 // In this context, we *do not* check D.getInvalidType(). If the declarator
2561 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2562 // though it will not reflect the user specified type.
2563 QualType parmDeclType = GetTypeForDeclarator(D, S);
2564
2565 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2566
Chris Lattner4b009652007-07-25 00:24:17 +00002567 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2568 // Can this happen for params? We already checked that they don't conflict
2569 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002570 IdentifierInfo *II = D.getIdentifier();
2571 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002572 if (PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002573 // Maybe we will complain about the shadowed template parameter.
2574 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2575 // Just pretend that we didn't see the previous declaration.
2576 PrevDecl = 0;
2577 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002578 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002579
2580 // Recover by removing the name
2581 II = 0;
2582 D.SetIdentifier(0, D.getIdentifierLoc());
2583 }
Chris Lattner4b009652007-07-25 00:24:17 +00002584 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00002585
2586 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2587 // Doing the promotion here has a win and a loss. The win is the type for
2588 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2589 // code generator). The loss is the orginal type isn't preserved. For example:
2590 //
2591 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2592 // int blockvardecl[5];
2593 // sizeof(parmvardecl); // size == 4
2594 // sizeof(blockvardecl); // size == 20
2595 // }
2596 //
2597 // For expressions, all implicit conversions are captured using the
2598 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2599 //
2600 // FIXME: If a source translation tool needs to see the original type, then
2601 // we need to consider storing both types (in ParmVarDecl)...
2602 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00002603 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00002604 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00002605 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00002606 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00002607 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002608
Chris Lattner3e254fb2008-04-08 04:40:51 +00002609 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2610 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002611 parmDeclType, StorageClass,
Chris Lattner3e254fb2008-04-08 04:40:51 +00002612 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00002613
Chris Lattner3e254fb2008-04-08 04:40:51 +00002614 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00002615 New->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002616
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002617 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2618 if (D.getCXXScopeSpec().isSet()) {
2619 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2620 << D.getCXXScopeSpec().getRange();
2621 New->setInvalidDecl();
2622 }
2623
Douglas Gregor8acb7272008-12-11 16:49:14 +00002624 // Add the parameter declaration into this scope.
2625 S->AddDecl(New);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002626 if (II)
Douglas Gregor8acb7272008-12-11 16:49:14 +00002627 IdResolver.AddDecl(New);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00002628
Chris Lattner9b384ca2008-06-29 00:02:00 +00002629 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00002630 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002631
Chris Lattner4b009652007-07-25 00:24:17 +00002632}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00002633
Chris Lattnerea148702007-10-09 17:14:05 +00002634Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002635 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00002636 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2637 "Not a function declarator!");
2638 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002639
Chris Lattner4b009652007-07-25 00:24:17 +00002640 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2641 // for a K&R function.
2642 if (!FTI.hasPrototype) {
2643 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002644 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002645 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2646 << FTI.ArgInfo[i].Ident;
Chris Lattner4b009652007-07-25 00:24:17 +00002647 // Implicitly declare the argument as type 'int' for lack of a better
2648 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002649 DeclSpec DS;
2650 const char* PrevSpec; // unused
2651 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2652 PrevSpec);
2653 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2654 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2655 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00002656 }
2657 }
Chris Lattner4b009652007-07-25 00:24:17 +00002658 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002659 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00002660 }
2661
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002662 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00002663
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002664 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002665 ActOnDeclarator(ParentScope, D, 0,
2666 /*IsFunctionDefinition=*/true));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002667}
2668
2669Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2670 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002671 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002672
2673 // See if this is a redefinition.
2674 const FunctionDecl *Definition;
2675 if (FD->getBody(Definition)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002676 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00002677 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor56da7862008-10-29 15:10:40 +00002678 }
2679
Douglas Gregor8acb7272008-12-11 16:49:14 +00002680 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002681
Chris Lattner3e254fb2008-04-08 04:40:51 +00002682 // Check the validity of our function parameters
2683 CheckParmsForFunctionDef(FD);
2684
2685 // Introduce our parameters into the function scope
2686 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2687 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregord394a272009-01-09 18:51:29 +00002688 Param->setOwningFunction(FD);
2689
Chris Lattner3e254fb2008-04-08 04:40:51 +00002690 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002691 if (Param->getIdentifier())
2692 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002693 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002694
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002695 // Checking attributes of current function definition
2696 // dllimport attribute.
2697 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2698 // dllimport attribute cannot be applied to definition.
2699 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2700 Diag(FD->getLocation(),
2701 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2702 << "dllimport";
2703 FD->setInvalidDecl();
2704 return FD;
2705 } else {
2706 // If a symbol previously declared dllimport is later defined, the
2707 // attribute is ignored in subsequent references, and a warning is
2708 // emitted.
2709 Diag(FD->getLocation(),
2710 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2711 << FD->getNameAsCString() << "dllimport";
2712 }
2713 }
Chris Lattner4b009652007-07-25 00:24:17 +00002714 return FD;
2715}
2716
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002717Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002718 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002719 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff3ac43f92008-07-25 17:57:26 +00002720 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002721 FD->setBody(Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002722 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002723 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002724 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002725 } else
2726 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002727 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002728 // Verify and clean out per-function state.
2729
2730 // Check goto/label use.
2731 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2732 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2733 // Verify that we have no forward references left. If so, there was a goto
2734 // or address of a label taken, but no definition of it. Label fwd
2735 // definitions are indicated with a null substmt.
2736 if (I->second->getSubStmt() == 0) {
2737 LabelStmt *L = I->second;
2738 // Emit error.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002739 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Chris Lattner4b009652007-07-25 00:24:17 +00002740
2741 // At this point, we have gotos that use the bogus label. Stitch it into
2742 // the function body so that they aren't leaked and that the AST is well
2743 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002744 if (Body) {
2745 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002746 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner83343342008-01-25 00:01:10 +00002747 } else {
2748 // The whole function wasn't parsed correctly, just delete this.
2749 delete L;
2750 }
Chris Lattner4b009652007-07-25 00:24:17 +00002751 }
2752 }
2753 LabelMap.clear();
2754
Steve Naroff99ee4302007-11-11 23:20:51 +00002755 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002756}
2757
Chris Lattner4b009652007-07-25 00:24:17 +00002758/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2759/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00002760ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2761 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002762 // Extension in C99. Legal in C90, but warn about it.
2763 if (getLangOptions().C99)
Chris Lattner65cae292008-11-19 08:23:25 +00002764 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002765 else
Chris Lattner65cae292008-11-19 08:23:25 +00002766 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Chris Lattner4b009652007-07-25 00:24:17 +00002767
2768 // FIXME: handle stuff like:
2769 // void foo() { extern float X(); }
2770 // void bar() { X(); } <-- implicit decl for X in another scope.
2771
2772 // Set a Declarator for the implicit definition: int foo();
2773 const char *Dummy;
2774 DeclSpec DS;
2775 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2776 Error = Error; // Silence warning.
2777 assert(!Error && "Error setting up implicit decl!");
2778 Declarator D(DS, Declarator::BlockContext);
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00002779 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Chris Lattner4b009652007-07-25 00:24:17 +00002780 D.SetIdentifier(&II, Loc);
2781
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002782 // Insert this function into translation-unit scope.
2783
2784 DeclContext *PrevDC = CurContext;
2785 CurContext = Context.getTranslationUnitDecl();
2786
Steve Naroff9104f3c2008-04-04 14:32:09 +00002787 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002788 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002789 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002790
2791 CurContext = PrevDC;
2792
Steve Naroff9104f3c2008-04-04 14:32:09 +00002793 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002794}
2795
2796
Chris Lattner82bb4792007-11-14 06:34:38 +00002797TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00002798 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002799 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002800 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002801
2802 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002803 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2804 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002805 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00002806 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002807 if (D.getInvalidType())
2808 NewTD->setInvalidDecl();
2809 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002810}
2811
Steve Naroff0acc9c92007-09-15 18:49:24 +00002812/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002813/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregor98b27542009-01-17 00:42:38 +00002814/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Chris Lattner4b009652007-07-25 00:24:17 +00002815/// reference/declaration/definition of a tag.
Douglas Gregor98b27542009-01-17 00:42:38 +00002816Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002817 SourceLocation KWLoc, const CXXScopeSpec &SS,
2818 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregor52473432008-12-24 02:52:09 +00002819 AttributeList *Attr,
2820 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorae644892008-12-15 16:32:14 +00002821 // If this is not a definition, it must have a name.
Chris Lattner4b009652007-07-25 00:24:17 +00002822 assert((Name != 0 || TK == TK_Definition) &&
2823 "Nameless record must be a definition!");
2824
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002825 TagDecl::TagKind Kind;
Douglas Gregor98b27542009-01-17 00:42:38 +00002826 switch (TagSpec) {
Chris Lattner4b009652007-07-25 00:24:17 +00002827 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002828 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2829 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2830 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2831 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002832 }
2833
Douglas Gregorb748fc52009-01-12 22:49:06 +00002834 DeclContext *SearchDC = CurContext;
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002835 DeclContext *DC = CurContext;
Douglas Gregorcab994d2009-01-09 22:42:13 +00002836 DeclContext *LexicalContext = CurContext;
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002837 ScopedDecl *PrevDecl = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002838
Douglas Gregor98b27542009-01-17 00:42:38 +00002839 bool Invalid = false;
2840
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002841 if (Name && SS.isNotEmpty()) {
2842 // We have a nested-name tag ('struct foo::bar').
2843
2844 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002845 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002846 Name = 0;
2847 goto CreateNewDecl;
2848 }
2849
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002850 DC = static_cast<DeclContext*>(SS.getScopeRep());
2851 // Look-up name inside 'foo::'.
Douglas Gregor78d70132009-01-14 22:20:51 +00002852 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC)
2853 .getAsDecl());
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002854
2855 // A tag 'foo::bar' must already exist.
2856 if (PrevDecl == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002857 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002858 Name = 0;
2859 goto CreateNewDecl;
2860 }
2861 } else {
2862 // If this is a named struct, check to see if there was a previous forward
2863 // declaration or definition.
2864 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
Douglas Gregor78d70132009-01-14 22:20:51 +00002865 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S)
2866 .getAsDecl());
Douglas Gregordb568cf2009-01-08 20:45:30 +00002867
2868 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2869 // FIXME: This makes sure that we ignore the contexts associated
2870 // with C structs, unions, and enums when looking for a matching
2871 // tag declaration or definition. See the similar lookup tweak
2872 // in Sema::LookupDecl; is there a better way to deal with this?
Douglas Gregorb748fc52009-01-12 22:49:06 +00002873 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2874 SearchDC = SearchDC->getParent();
Douglas Gregordb568cf2009-01-08 20:45:30 +00002875 }
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002876 }
2877
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002878 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002879 // Maybe we will complain about the shadowed template parameter.
2880 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2881 // Just pretend that we didn't see the previous declaration.
2882 PrevDecl = 0;
2883 }
2884
Ted Kremenekd4434152008-09-02 21:26:19 +00002885 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002886 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2887 "unexpected Decl type");
2888 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002889 // If this is a use of a previous tag, or if the tag is already declared
2890 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002891 // rementions the tag), reuse the decl.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002892 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002893 // Make sure that this wasn't declared as an enum and now used as a
2894 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002895 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner65cae292008-11-19 08:23:25 +00002896 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002897 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002898 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002899 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002900 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002901 Invalid = true;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002902 } else {
Douglas Gregorae644892008-12-15 16:32:14 +00002903 // If this is a use, just return the declaration we found.
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002904
Douglas Gregorae644892008-12-15 16:32:14 +00002905 // FIXME: In the future, return a variant or some other clue
2906 // for the consumer of this Decl to know it doesn't own it.
2907 // For our current ASTs this shouldn't be a problem, but will
2908 // need to be changed with DeclGroups.
2909 if (TK == TK_Reference)
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002910 return PrevDecl;
Douglas Gregorae644892008-12-15 16:32:14 +00002911
2912 // Diagnose attempts to redefine a tag.
2913 if (TK == TK_Definition) {
2914 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2915 Diag(NameLoc, diag::err_redefinition) << Name;
2916 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor98b27542009-01-17 00:42:38 +00002917 // If this is a redefinition, recover by making this
2918 // struct be anonymous, which will make any later
2919 // references get the previous definition.
Douglas Gregorae644892008-12-15 16:32:14 +00002920 Name = 0;
2921 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002922 Invalid = true;
2923 } else {
2924 // If the type is currently being defined, complain
2925 // about a nested redefinition.
2926 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
2927 if (Tag->isBeingDefined()) {
2928 Diag(NameLoc, diag::err_nested_redefinition) << Name;
2929 Diag(PrevTagDecl->getLocation(),
2930 diag::note_previous_definition);
2931 Name = 0;
2932 PrevDecl = 0;
2933 Invalid = true;
2934 }
Douglas Gregorae644892008-12-15 16:32:14 +00002935 }
Douglas Gregor98b27542009-01-17 00:42:38 +00002936
Douglas Gregorae644892008-12-15 16:32:14 +00002937 // Okay, this is definition of a previously declared or referenced
2938 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor98b27542009-01-17 00:42:38 +00002939 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002940 }
Douglas Gregorae644892008-12-15 16:32:14 +00002941 // If we get here we have (another) forward declaration or we
2942 // have a definition. Just create a new decl.
2943 } else {
2944 // If we get here, this is a definition of a new tag type in a nested
2945 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2946 // new decl/type. We set PrevDecl to NULL so that the entities
2947 // have distinct types.
2948 PrevDecl = 0;
Chris Lattner4b009652007-07-25 00:24:17 +00002949 }
Douglas Gregorae644892008-12-15 16:32:14 +00002950 // If we get here, we're going to create a new Decl. If PrevDecl
2951 // is non-NULL, it's a definition of the tag declared by
2952 // PrevDecl. If it's NULL, we have a new definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002953 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002954 // PrevDecl is a namespace.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002955 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002956 // The tag name clashes with a namespace name, issue an error and
2957 // recover by making this tag be anonymous.
Chris Lattner65cae292008-11-19 08:23:25 +00002958 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002959 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002960 Name = 0;
Douglas Gregorae644892008-12-15 16:32:14 +00002961 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002962 Invalid = true;
Douglas Gregorae644892008-12-15 16:32:14 +00002963 } else {
2964 // The existing declaration isn't relevant to us; we're in a
2965 // new scope, so clear out the previous declaration.
2966 PrevDecl = 0;
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002967 }
Chris Lattner4b009652007-07-25 00:24:17 +00002968 }
Douglas Gregorcab994d2009-01-09 22:42:13 +00002969 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
2970 (Kind != TagDecl::TK_enum)) {
2971 // C++ [basic.scope.pdecl]p5:
2972 // -- for an elaborated-type-specifier of the form
2973 //
2974 // class-key identifier
2975 //
2976 // if the elaborated-type-specifier is used in the
2977 // decl-specifier-seq or parameter-declaration-clause of a
2978 // function defined in namespace scope, the identifier is
2979 // declared as a class-name in the namespace that contains
2980 // the declaration; otherwise, except as a friend
2981 // declaration, the identifier is declared in the smallest
2982 // non-class, non-function-prototype scope that contains the
2983 // declaration.
2984 //
2985 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
2986 // C structs and unions.
2987
2988 // Find the context where we'll be declaring the tag.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002989 // FIXME: We would like to maintain the current DeclContext as the
2990 // lexical context,
Douglas Gregorcab994d2009-01-09 22:42:13 +00002991 while (DC->isRecord())
2992 DC = DC->getParent();
2993 LexicalContext = DC;
2994
2995 // Find the scope where we'll be declaring the tag.
2996 while (S->isClassScope() ||
2997 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor5eca99e2009-01-12 18:45:55 +00002998 ((S->getFlags() & Scope::DeclScope) == 0) ||
2999 (S->getEntity() &&
3000 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregorcab994d2009-01-09 22:42:13 +00003001 S = S->getParent();
Chris Lattner4b009652007-07-25 00:24:17 +00003002 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00003003
Chris Lattner9bb9abf2008-12-17 07:13:27 +00003004CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00003005
3006 // If there is an identifier, use the location of the identifier as the
3007 // location of the decl, otherwise use the location of the struct/union
3008 // keyword.
3009 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3010
Douglas Gregorae644892008-12-15 16:32:14 +00003011 // Otherwise, create a new declaration. If there is a previous
3012 // declaration of the same entity, the two will be linked via
3013 // PrevDecl.
Chris Lattner4b009652007-07-25 00:24:17 +00003014 TagDecl *New;
Douglas Gregor723d3332009-01-07 00:43:41 +00003015
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003016 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00003017 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3018 // enum X { A, B, C } D; D should chain to X.
Douglas Gregorae644892008-12-15 16:32:14 +00003019 New = EnumDecl::Create(Context, DC, Loc, Name,
3020 cast_or_null<EnumDecl>(PrevDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003021 // If this is an undefined enum, warn.
3022 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003023 } else {
3024 // struct/union/class
3025
Chris Lattner4b009652007-07-25 00:24:17 +00003026 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3027 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003028 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00003029 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregorae644892008-12-15 16:32:14 +00003030 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
3031 cast_or_null<CXXRecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003032 else
Douglas Gregorae644892008-12-15 16:32:14 +00003033 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
3034 cast_or_null<RecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003035 }
Douglas Gregorae644892008-12-15 16:32:14 +00003036
3037 if (Kind != TagDecl::TK_enum) {
3038 // Handle #pragma pack: if the #pragma pack stack has non-default
3039 // alignment, make up a packed attribute for this decl. These
3040 // attributes are checked when the ASTContext lays out the
3041 // structure.
3042 //
3043 // It is important for implementing the correct semantics that this
3044 // happen here (in act on tag decl). The #pragma pack stack is
3045 // maintained as a result of parser callbacks which can occur at
3046 // many points during the parsing of a struct declaration (because
3047 // the #pragma tokens are effectively skipped over during the
3048 // parsing of the struct).
3049 if (unsigned Alignment = PackContext.getAlignment())
3050 New->addAttr(new PackedAttr(Alignment * 8));
3051 }
3052
Douglas Gregor98b27542009-01-17 00:42:38 +00003053 if (Invalid)
3054 New->setInvalidDecl();
3055
Douglas Gregorae644892008-12-15 16:32:14 +00003056 if (Attr)
3057 ProcessDeclAttributeList(New, Attr);
3058
Douglas Gregor98b27542009-01-17 00:42:38 +00003059 // If we're declaring or defining a tag in function prototype scope
3060 // in C, note that this type can only be used within the function.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003061 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3062 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3063
Douglas Gregorae644892008-12-15 16:32:14 +00003064 // Set the lexical context. If the tag has a C++ scope specifier, the
3065 // lexical context will be different from the semantic context.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003066 New->setLexicalDeclContext(LexicalContext);
Douglas Gregor98b27542009-01-17 00:42:38 +00003067
3068 if (TK == TK_Definition)
3069 New->startDefinition();
Chris Lattner4b009652007-07-25 00:24:17 +00003070
3071 // If this has an identifier, add it to the scope stack.
3072 if (Name) {
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003073 S = getNonFieldDeclScope(S);
Chris Lattnera7549902007-08-26 06:24:45 +00003074
3075 // Add it to the decl chain.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003076 if (LexicalContext != CurContext) {
3077 // FIXME: PushOnScopeChains should not rely on CurContext!
3078 DeclContext *OldContext = CurContext;
3079 CurContext = LexicalContext;
3080 PushOnScopeChains(New, S);
3081 CurContext = OldContext;
3082 } else
3083 PushOnScopeChains(New, S);
Douglas Gregorb748fc52009-01-12 22:49:06 +00003084 } else {
Douglas Gregor03b2ad22009-01-12 23:27:07 +00003085 LexicalContext->addDecl(New);
Chris Lattner4b009652007-07-25 00:24:17 +00003086 }
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00003087
Chris Lattner4b009652007-07-25 00:24:17 +00003088 return New;
3089}
3090
Douglas Gregordb568cf2009-01-08 20:45:30 +00003091void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3092 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3093
3094 // Enter the tag context.
3095 PushDeclContext(S, Tag);
3096
3097 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3098 FieldCollector->StartClass();
3099
3100 if (Record->getIdentifier()) {
3101 // C++ [class]p2:
3102 // [...] The class-name is also inserted into the scope of the
3103 // class itself; this is known as the injected-class-name. For
3104 // purposes of access checking, the injected-class-name is treated
3105 // as if it were a public member name.
3106 RecordDecl *InjectedClassName
3107 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3108 CurContext, Record->getLocation(),
3109 Record->getIdentifier(), Record);
3110 InjectedClassName->setImplicit();
3111 PushOnScopeChains(InjectedClassName, S);
3112 }
3113 }
3114}
3115
3116void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3117 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3118
3119 if (isa<CXXRecordDecl>(Tag))
3120 FieldCollector->FinishClass();
3121
3122 // Exit this scope of this tag's definition.
3123 PopDeclContext();
3124
3125 // Notify the consumer that we've defined a tag.
3126 Consumer.HandleTagDeclDefinition(Tag);
3127}
Chris Lattner1bf58f62008-06-21 19:39:06 +00003128
Chris Lattnera73e2202008-11-12 21:17:48 +00003129/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3130/// types into constant array types in certain situations which would otherwise
3131/// be errors (for GCC compatibility).
3132static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3133 ASTContext &Context) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003134 // This method tries to turn a variable array into a constant
3135 // array even when the size isn't an ICE. This is necessary
3136 // for compatibility with code that depends on gcc's buggy
3137 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003138 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3139 if (!VLATy) return QualType();
3140
Anders Carlsson8c3de802008-12-19 20:58:05 +00003141 Expr::EvalResult EvalResult;
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003142 if (!VLATy->getSizeExpr() ||
Anders Carlsson8c3de802008-12-19 20:58:05 +00003143 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003144 return QualType();
3145
Anders Carlsson8c3de802008-12-19 20:58:05 +00003146 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3147 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003148 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3149 return Context.getConstantArrayType(VLATy->getElementType(),
3150 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003151 return QualType();
3152}
3153
Anders Carlsson108229a2008-12-06 20:33:04 +00003154bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattner8464c372008-12-12 04:56:04 +00003155 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson108229a2008-12-06 20:33:04 +00003156 // FIXME: 6.7.2.1p4 - verify the field type.
3157
3158 llvm::APSInt Value;
3159 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3160 return true;
3161
Chris Lattner8464c372008-12-12 04:56:04 +00003162 // Zero-width bitfield is ok for anonymous field.
3163 if (Value == 0 && FieldName)
3164 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3165
3166 if (Value.isNegative())
3167 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson108229a2008-12-06 20:33:04 +00003168
3169 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3170 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattner8464c372008-12-12 04:56:04 +00003171 if (TypeSize && Value.getZExtValue() > TypeSize)
3172 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3173 << FieldName << (unsigned)TypeSize;
Anders Carlsson108229a2008-12-06 20:33:04 +00003174
3175 return false;
3176}
3177
Steve Naroff0acc9c92007-09-15 18:49:24 +00003178/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00003179/// to create a FieldDecl object for it.
Douglas Gregor8acb7272008-12-11 16:49:14 +00003180Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Chris Lattner4b009652007-07-25 00:24:17 +00003181 SourceLocation DeclStart,
3182 Declarator &D, ExprTy *BitfieldWidth) {
3183 IdentifierInfo *II = D.getIdentifier();
3184 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00003185 SourceLocation Loc = DeclStart;
Douglas Gregor8acb7272008-12-11 16:49:14 +00003186 RecordDecl *Record = (RecordDecl *)TagD;
Chris Lattner4b009652007-07-25 00:24:17 +00003187 if (II) Loc = D.getIdentifierLoc();
3188
3189 // FIXME: Unnamed fields can be handled in various different ways, for
3190 // example, unnamed unions inject all members into the struct namespace!
Chris Lattner4b009652007-07-25 00:24:17 +00003191
Chris Lattner4b009652007-07-25 00:24:17 +00003192 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003193 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3194 bool InvalidDecl = false;
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003195
Chris Lattner4b009652007-07-25 00:24:17 +00003196 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3197 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00003198 if (T->isVariablyModifiedType()) {
Chris Lattnera73e2202008-11-12 21:17:48 +00003199 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003200 if (!FixedTy.isNull()) {
Chris Lattner86be8572008-11-13 18:49:38 +00003201 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003202 T = FixedTy;
3203 } else {
Chris Lattner86be8572008-11-13 18:49:38 +00003204 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner2a884752008-11-12 19:45:49 +00003205 T = Context.IntTy;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003206 InvalidDecl = true;
3207 }
Chris Lattner4b009652007-07-25 00:24:17 +00003208 }
Anders Carlsson108229a2008-12-06 20:33:04 +00003209
3210 if (BitWidth) {
3211 if (VerifyBitField(Loc, II, T, BitWidth))
3212 InvalidDecl = true;
3213 } else {
3214 // Not a bitfield.
3215
3216 // validate II.
3217
3218 }
3219
Chris Lattner4b009652007-07-25 00:24:17 +00003220 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003221 FieldDecl *NewFD;
3222
Douglas Gregor8acb7272008-12-11 16:49:14 +00003223 NewFD = FieldDecl::Create(Context, Record,
3224 Loc, II, T, BitWidth,
3225 D.getDeclSpec().getStorageClassSpec() ==
3226 DeclSpec::SCS_mutable,
3227 /*PrevDecl=*/0);
3228
Douglas Gregordb568cf2009-01-08 20:45:30 +00003229 if (II) {
3230 Decl *PrevDecl
3231 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3232 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3233 && !isa<TagDecl>(PrevDecl)) {
3234 Diag(Loc, diag::err_duplicate_member) << II;
3235 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3236 NewFD->setInvalidDecl();
3237 Record->setInvalidDecl();
3238 }
3239 }
3240
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003241 if (getLangOptions().CPlusPlus) {
Douglas Gregor605de8d2008-12-16 21:30:33 +00003242 CheckExtraCXXDefaultArguments(D);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003243 if (!T->isPODType())
3244 cast<CXXRecordDecl>(Record)->setPOD(false);
3245 }
Douglas Gregor605de8d2008-12-16 21:30:33 +00003246
Chris Lattner9b384ca2008-06-29 00:02:00 +00003247 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00003248
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003249 if (D.getInvalidType() || InvalidDecl)
3250 NewFD->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00003251
Douglas Gregordb568cf2009-01-08 20:45:30 +00003252 if (II) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003253 PushOnScopeChains(NewFD, S);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003254 } else
Douglas Gregor03b2ad22009-01-12 23:27:07 +00003255 Record->addDecl(NewFD);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003256
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003257 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00003258}
3259
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003260/// TranslateIvarVisibility - Translate visibility from a token ID to an
3261/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00003262static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003263TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00003264 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00003265 default: assert(0 && "Unknown visitibility kind");
3266 case tok::objc_private: return ObjCIvarDecl::Private;
3267 case tok::objc_public: return ObjCIvarDecl::Public;
3268 case tok::objc_protected: return ObjCIvarDecl::Protected;
3269 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00003270 }
3271}
3272
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003273/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3274/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003275Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003276 SourceLocation DeclStart,
3277 Declarator &D, ExprTy *BitfieldWidth,
3278 tok::ObjCKeywordKind Visibility) {
Douglas Gregordb568cf2009-01-08 20:45:30 +00003279
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003280 IdentifierInfo *II = D.getIdentifier();
3281 Expr *BitWidth = (Expr*)BitfieldWidth;
3282 SourceLocation Loc = DeclStart;
3283 if (II) Loc = D.getIdentifierLoc();
3284
3285 // FIXME: Unnamed fields can be handled in various different ways, for
3286 // example, unnamed unions inject all members into the struct namespace!
3287
Anders Carlsson108229a2008-12-06 20:33:04 +00003288 QualType T = GetTypeForDeclarator(D, S);
3289 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3290 bool InvalidDecl = false;
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003291
3292 if (BitWidth) {
3293 // TODO: Validate.
3294 //printf("WARNING: BITFIELDS IGNORED!\n");
3295
3296 // 6.7.2.1p3
3297 // 6.7.2.1p4
3298
3299 } else {
3300 // Not a bitfield.
3301
3302 // validate II.
3303
3304 }
3305
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003306 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3307 // than a variably modified type.
3308 if (T->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00003309 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003310 InvalidDecl = true;
3311 }
3312
Ted Kremenek173dd312008-07-23 18:04:17 +00003313 // Get the visibility (access control) for this ivar.
3314 ObjCIvarDecl::AccessControl ac =
3315 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3316 : ObjCIvarDecl::None;
3317
3318 // Construct the decl.
3319 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00003320 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003321
Douglas Gregordb568cf2009-01-08 20:45:30 +00003322 if (II) {
3323 Decl *PrevDecl
3324 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3325 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3326 && !isa<TagDecl>(PrevDecl)) {
3327 Diag(Loc, diag::err_duplicate_member) << II;
3328 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3329 NewID->setInvalidDecl();
3330 }
3331 }
3332
Ted Kremenek173dd312008-07-23 18:04:17 +00003333 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00003334 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003335
3336 if (D.getInvalidType() || InvalidDecl)
3337 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00003338
Douglas Gregordb568cf2009-01-08 20:45:30 +00003339 if (II) {
3340 // FIXME: When interfaces are DeclContexts, we'll need to add
3341 // these to the interface.
3342 S->AddDecl(NewID);
3343 IdResolver.AddDecl(NewID);
3344 }
3345
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003346 return NewID;
3347}
3348
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00003349void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003350 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00003351 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00003352 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00003353 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003354 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3355 assert(EnclosingDecl && "missing record or interface decl");
3356 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3357
Chris Lattner4b009652007-07-25 00:24:17 +00003358 // Verify that all the fields are okay.
3359 unsigned NumNamedMembers = 0;
3360 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorc7f01612009-01-07 19:46:03 +00003361
Chris Lattner4b009652007-07-25 00:24:17 +00003362 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003363 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3364 assert(FD && "missing field decl");
3365
Chris Lattner4b009652007-07-25 00:24:17 +00003366 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00003367 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorc7f01612009-01-07 19:46:03 +00003368
Douglas Gregordb568cf2009-01-08 20:45:30 +00003369 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorc7f01612009-01-07 19:46:03 +00003370 // Remember all fields written by the user.
3371 RecFields.push_back(FD);
3372 }
Steve Naroffffeaa552007-09-14 23:09:53 +00003373
Chris Lattner4b009652007-07-25 00:24:17 +00003374 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00003375 if (FDTy->isFunctionType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003376 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattner271d4c22008-11-24 05:29:24 +00003377 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003378 FD->setInvalidDecl();
3379 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003380 continue;
3381 }
Chris Lattner4b009652007-07-25 00:24:17 +00003382 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3383 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003384 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattner271d4c22008-11-24 05:29:24 +00003385 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003386 FD->setInvalidDecl();
3387 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003388 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003389 }
Chris Lattner4b009652007-07-25 00:24:17 +00003390 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003391 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00003392 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner271d4c22008-11-24 05:29:24 +00003393 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003394 FD->setInvalidDecl();
3395 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003396 continue;
3397 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003398 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003399 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003400 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003401 FD->setInvalidDecl();
3402 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003403 continue;
3404 }
Chris Lattner4b009652007-07-25 00:24:17 +00003405 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003406 if (Record)
3407 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003408 }
Chris Lattner4b009652007-07-25 00:24:17 +00003409 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3410 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00003411 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003412 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3413 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003414 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003415 Record->setHasFlexibleArrayMember(true);
3416 } else {
3417 // If this is a struct/class and this is not the last element, reject
3418 // it. Note that GCC supports variable sized arrays in the middle of
3419 // structures.
3420 if (i != NumFields-1) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003421 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003422 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003423 FD->setInvalidDecl();
3424 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003425 continue;
3426 }
Chris Lattner4b009652007-07-25 00:24:17 +00003427 // We support flexible arrays at the end of structs in other structs
3428 // as an extension.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003429 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003430 << FD->getDeclName();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003431 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003432 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003433 }
3434 }
3435 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003436 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00003437 if (FDTy->isObjCInterfaceType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003438 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattnerb1753422008-11-23 21:45:46 +00003439 << FD->getDeclName();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003440 FD->setInvalidDecl();
3441 EnclosingDecl->setInvalidDecl();
3442 continue;
3443 }
Chris Lattner4b009652007-07-25 00:24:17 +00003444 // Keep track of the number of named members.
Douglas Gregordb568cf2009-01-08 20:45:30 +00003445 if (FD->getIdentifier())
Chris Lattner4b009652007-07-25 00:24:17 +00003446 ++NumNamedMembers;
Chris Lattner4b009652007-07-25 00:24:17 +00003447 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003448
Chris Lattner4b009652007-07-25 00:24:17 +00003449 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00003450 if (Record) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003451 Record->completeDefinition(Context);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003452 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003453 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003454 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003455 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003456 // Must enforce the rule that ivars in the base classes may not be
3457 // duplicates.
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003458 if (ID->getSuperClass()) {
3459 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3460 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3461 ObjCIvarDecl* Ivar = (*IVI);
3462 IdentifierInfo *II = Ivar->getIdentifier();
3463 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3464 if (prevIvar) {
3465 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregordb568cf2009-01-08 20:45:30 +00003466 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003467 }
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003468 }
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003469 }
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003470 }
Chris Lattner1100cfb2008-02-05 22:40:55 +00003471 else if (ObjCImplementationDecl *IMPDecl =
3472 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003473 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3474 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00003475 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00003476 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00003477 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00003478
3479 if (Attr)
3480 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00003481}
3482
Steve Naroff0acc9c92007-09-15 18:49:24 +00003483Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00003484 DeclTy *lastEnumConst,
3485 SourceLocation IdLoc, IdentifierInfo *Id,
3486 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00003487 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003488 EnumConstantDecl *LastEnumConst =
3489 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3490 Expr *Val = static_cast<Expr*>(val);
3491
Chris Lattnera7549902007-08-26 06:24:45 +00003492 // The scope passed in may not be a decl scope. Zip up the scope tree until
3493 // we find one that is.
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003494 S = getNonFieldDeclScope(S);
Chris Lattnera7549902007-08-26 06:24:45 +00003495
Chris Lattner4b009652007-07-25 00:24:17 +00003496 // Verify that there isn't already something declared with this name in this
3497 // scope.
Douglas Gregordd861062008-12-05 18:15:24 +00003498 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregor2715a1f2008-12-08 18:40:42 +00003499 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00003500 // Maybe we will complain about the shadowed template parameter.
3501 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3502 // Just pretend that we didn't see the previous declaration.
3503 PrevDecl = 0;
3504 }
3505
3506 if (PrevDecl) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00003507 // When in C++, we may get a TagDecl with the same name; in this case the
3508 // enum constant will 'hide' the tag.
3509 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3510 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00003511 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003512 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner65cae292008-11-19 08:23:25 +00003513 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner4b009652007-07-25 00:24:17 +00003514 else
Chris Lattner65cae292008-11-19 08:23:25 +00003515 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner1336cab2008-11-23 23:12:31 +00003516 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003517 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00003518 return 0;
3519 }
3520 }
3521
3522 llvm::APSInt EnumVal(32);
3523 QualType EltTy;
3524 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00003525 // Make sure to promote the operand type to int.
3526 UsualUnaryConversions(Val);
3527
Chris Lattner4b009652007-07-25 00:24:17 +00003528 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3529 SourceLocation ExpLoc;
Anders Carlsson5374c6b2008-12-05 16:33:57 +00003530 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003531 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00003532 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00003533 } else {
3534 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003535 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00003536 }
3537
3538 if (!Val) {
3539 if (LastEnumConst) {
3540 // Assign the last value + 1.
3541 EnumVal = LastEnumConst->getInitVal();
3542 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00003543
3544 // Check for overflow on increment.
3545 if (EnumVal < LastEnumConst->getInitVal())
3546 Diag(IdLoc, diag::warn_enum_value_overflow);
3547
Chris Lattnere7f53a42007-08-27 17:37:24 +00003548 EltTy = LastEnumConst->getType();
3549 } else {
3550 // First value, set to zero.
3551 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003552 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00003553 }
Chris Lattner4b009652007-07-25 00:24:17 +00003554 }
3555
Chris Lattnere4650482008-03-15 06:12:44 +00003556 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00003557 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3558 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00003559 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00003560
3561 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00003562 PushOnScopeChains(New, S);
Douglas Gregor0c3ab042008-12-17 02:04:30 +00003563
Chris Lattner4b009652007-07-25 00:24:17 +00003564 return New;
3565}
3566
Steve Naroffb0726b82008-08-07 14:08:16 +00003567// FIXME: For consistency with ActOnFields(), we should have the parser
3568// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00003569void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00003570 DeclTy **Elements, unsigned NumElements) {
3571 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregord8028382009-01-05 19:45:36 +00003572 QualType EnumType = Context.getTypeDeclType(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003573
Chris Lattner435c3fd2007-08-28 05:10:31 +00003574 // TODO: If the result value doesn't fit in an int, it must be a long or long
3575 // long value. ISO C does not support this, but GCC does as an extension,
3576 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00003577 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00003578
Chris Lattner206754a2007-08-28 06:15:15 +00003579 // Verify that all the values are okay, compute the size of the values, and
3580 // reverse the list.
3581 unsigned NumNegativeBits = 0;
3582 unsigned NumPositiveBits = 0;
3583
3584 // Keep track of whether all elements have type int.
3585 bool AllElementsInt = true;
3586
Chris Lattner4b009652007-07-25 00:24:17 +00003587 for (unsigned i = 0; i != NumElements; ++i) {
3588 EnumConstantDecl *ECD =
3589 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3590 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003591
3592 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003593 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003594 assert(InitVal.getBitWidth() >= IntWidth &&
3595 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00003596 if (InitVal.getBitWidth() > IntWidth) {
3597 llvm::APSInt V(InitVal);
3598 V.trunc(IntWidth);
3599 V.extend(InitVal.getBitWidth());
3600 if (V != InitVal)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003601 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3602 << InitVal.toString(10);
Chris Lattnercb33ae12007-08-28 05:27:00 +00003603 }
Chris Lattner206754a2007-08-28 06:15:15 +00003604
3605 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003606 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00003607 NumPositiveBits = std::max(NumPositiveBits,
3608 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00003609 else
Chris Lattneraff63f02008-01-14 21:47:29 +00003610 NumNegativeBits = std::max(NumNegativeBits,
3611 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00003612
Chris Lattner206754a2007-08-28 06:15:15 +00003613 // Keep track of whether every enum element has type int (very commmon).
3614 if (AllElementsInt)
3615 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003616 }
3617
Chris Lattner206754a2007-08-28 06:15:15 +00003618 // Figure out the type that should be used for this enum.
3619 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3620 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003621 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00003622
3623 if (NumNegativeBits) {
3624 // If there is a negative value, figure out the smallest integer type (of
3625 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003626 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003627 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003628 BestWidth = IntWidth;
3629 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003630 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003631
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003632 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003633 BestType = Context.LongTy;
3634 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003635 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003636
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003637 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003638 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3639 BestType = Context.LongLongTy;
3640 }
3641 }
3642 } else {
3643 // If there is no negative value, figure out which of uint, ulong, ulonglong
3644 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003645 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003646 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003647 BestWidth = IntWidth;
3648 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00003649 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00003650 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003651 } else {
3652 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003653 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00003654 "How could an initializer get larger than ULL?");
3655 BestType = Context.UnsignedLongLongTy;
3656 }
3657 }
3658
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003659 // Loop over all of the enumerator constants, changing their types to match
3660 // the type of the enum if needed.
3661 for (unsigned i = 0; i != NumElements; ++i) {
3662 EnumConstantDecl *ECD =
3663 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3664 if (!ECD) continue; // Already issued a diagnostic.
3665
3666 // Standard C says the enumerators have int type, but we allow, as an
3667 // extension, the enumerators to be larger than int size. If each
3668 // enumerator value fits in an int, type it as an int, otherwise type it the
3669 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3670 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003671 if (ECD->getType() == Context.IntTy) {
3672 // Make sure the init value is signed.
3673 llvm::APSInt IV = ECD->getInitVal();
3674 IV.setIsSigned(true);
3675 ECD->setInitVal(IV);
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003676
3677 if (getLangOptions().CPlusPlus)
3678 // C++ [dcl.enum]p4: Following the closing brace of an
3679 // enum-specifier, each enumerator has the type of its
3680 // enumeration.
3681 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003682 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003683 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003684
3685 // Determine whether the value fits into an int.
3686 llvm::APSInt InitVal = ECD->getInitVal();
3687 bool FitsInInt;
3688 if (InitVal.isUnsigned() || !InitVal.isNegative())
3689 FitsInInt = InitVal.getActiveBits() < IntWidth;
3690 else
3691 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3692
3693 // If it fits into an integer type, force it. Otherwise force it to match
3694 // the enum decl type.
3695 QualType NewTy;
3696 unsigned NewWidth;
3697 bool NewSign;
3698 if (FitsInInt) {
3699 NewTy = Context.IntTy;
3700 NewWidth = IntWidth;
3701 NewSign = true;
3702 } else if (ECD->getType() == BestType) {
3703 // Already the right type!
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003704 if (getLangOptions().CPlusPlus)
3705 // C++ [dcl.enum]p4: Following the closing brace of an
3706 // enum-specifier, each enumerator has the type of its
3707 // enumeration.
3708 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003709 continue;
3710 } else {
3711 NewTy = BestType;
3712 NewWidth = BestWidth;
3713 NewSign = BestType->isSignedIntegerType();
3714 }
3715
3716 // Adjust the APSInt value.
3717 InitVal.extOrTrunc(NewWidth);
3718 InitVal.setIsSigned(NewSign);
3719 ECD->setInitVal(InitVal);
3720
3721 // Adjust the Expr initializer and type.
Chris Lattner8c6dc7a2009-01-15 19:19:42 +00003722 if (ECD->getInitExpr())
3723 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3724 /*isLvalue=*/false));
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003725 if (getLangOptions().CPlusPlus)
3726 // C++ [dcl.enum]p4: Following the closing brace of an
3727 // enum-specifier, each enumerator has the type of its
3728 // enumeration.
3729 ECD->setType(EnumType);
3730 else
3731 ECD->setType(NewTy);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003732 }
Chris Lattner206754a2007-08-28 06:15:15 +00003733
Douglas Gregor8acb7272008-12-11 16:49:14 +00003734 Enum->completeDefinition(Context, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00003735}
3736
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003737Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00003738 ExprArg expr) {
3739 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3740
Chris Lattner81db64a2008-03-16 00:16:02 +00003741 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003742}
3743
Douglas Gregorad17e372008-12-16 22:23:02 +00003744
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003745void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3746 ExprTy *alignment, SourceLocation PragmaLoc,
3747 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3748 Expr *Alignment = static_cast<Expr *>(alignment);
3749
3750 // If specified then alignment must be a "small" power of two.
3751 unsigned AlignmentVal = 0;
3752 if (Alignment) {
3753 llvm::APSInt Val;
3754 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3755 !Val.isPowerOf2() ||
3756 Val.getZExtValue() > 16) {
3757 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3758 delete Alignment;
3759 return; // Ignore
3760 }
3761
3762 AlignmentVal = (unsigned) Val.getZExtValue();
3763 }
3764
3765 switch (Kind) {
3766 case Action::PPK_Default: // pack([n])
3767 PackContext.setAlignment(AlignmentVal);
3768 break;
3769
3770 case Action::PPK_Show: // pack(show)
3771 // Show the current alignment, making sure to show the right value
3772 // for the default.
3773 AlignmentVal = PackContext.getAlignment();
3774 // FIXME: This should come from the target.
3775 if (AlignmentVal == 0)
3776 AlignmentVal = 8;
Chris Lattnera5cc1882008-11-19 07:25:44 +00003777 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003778 break;
3779
3780 case Action::PPK_Push: // pack(push [, id] [, [n])
3781 PackContext.push(Name);
3782 // Set the new alignment if specified.
3783 if (Alignment)
3784 PackContext.setAlignment(AlignmentVal);
3785 break;
3786
3787 case Action::PPK_Pop: // pack(pop [, id] [, n])
3788 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3789 // "#pragma pack(pop, identifier, n) is undefined"
3790 if (Alignment && Name)
3791 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3792
3793 // Do the pop.
3794 if (!PackContext.pop(Name)) {
3795 // If a name was specified then failure indicates the name
3796 // wasn't found. Otherwise failure indicates the stack was
3797 // empty.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003798 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3799 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003800
3801 // FIXME: Warn about popping named records as MSVC does.
3802 } else {
3803 // Pop succeeded, set the new alignment if specified.
3804 if (Alignment)
3805 PackContext.setAlignment(AlignmentVal);
3806 }
3807 break;
3808
3809 default:
3810 assert(0 && "Invalid #pragma pack kind.");
3811 }
3812}
3813
3814bool PragmaPackStack::pop(IdentifierInfo *Name) {
3815 if (Stack.empty())
3816 return false;
3817
3818 // If name is empty just pop top.
3819 if (!Name) {
3820 Alignment = Stack.back().first;
3821 Stack.pop_back();
3822 return true;
3823 }
3824
3825 // Otherwise, find the named record.
3826 for (unsigned i = Stack.size(); i != 0; ) {
3827 --i;
Daniel Dunbarc13c54c2008-11-19 10:32:38 +00003828 if (Stack[i].second == Name) {
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003829 // Found it, pop up to and including this record.
3830 Alignment = Stack[i].first;
3831 Stack.erase(Stack.begin() + i, Stack.end());
3832 return true;
3833 }
3834 }
3835
3836 return false;
3837}