blob: a3e0232987c194178bc20fee28cb1ae8aab4af3a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000020#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/Parse/DeclSpec.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregore267ff32008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Douglas Gregore267ff32008-12-11 20:41:00 +000031
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
Douglas Gregord6efafa2009-02-04 19:16:12 +000034/// \brief If the identifier refers to a type name within this scope,
35/// return the declaration of that type.
36///
37/// This routine performs ordinary name lookup of the identifier II
38/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000039/// determine whether the name refers to a type. If so, returns an
40/// opaque pointer (actually a QualType) corresponding to that
41/// type. Otherwise, returns NULL.
Douglas Gregord6efafa2009-02-04 19:16:12 +000042///
43/// If name lookup results in an ambiguity, this routine will complain
44/// and then return NULL.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000045Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
Douglas Gregorb696ea32009-02-04 17:00:24 +000046 Scope *S, const CXXScopeSpec *SS) {
Douglas Gregor7176fff2009-01-15 00:26:24 +000047 Decl *IIDecl = 0;
Douglas Gregor4c921ae2009-01-30 01:04:22 +000048 LookupResult Result = LookupParsedName(S, SS, &II, LookupOrdinaryName, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +000049 switch (Result.getKind()) {
Steve Naroffa5189032009-01-29 18:09:31 +000050 case LookupResult::NotFound:
51 case LookupResult::FoundOverloaded:
Douglas Gregorb696ea32009-02-04 17:00:24 +000052 return 0;
53
Steve Naroffa5189032009-01-29 18:09:31 +000054 case LookupResult::AmbiguousBaseSubobjectTypes:
55 case LookupResult::AmbiguousBaseSubobjects:
Douglas Gregor2a3009a2009-02-03 19:21:40 +000056 case LookupResult::AmbiguousReference:
Douglas Gregorb696ea32009-02-04 17:00:24 +000057 DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc);
Steve Naroffa5189032009-01-29 18:09:31 +000058 return 0;
Douglas Gregorb696ea32009-02-04 17:00:24 +000059
Steve Naroffa5189032009-01-29 18:09:31 +000060 case LookupResult::Found:
61 IIDecl = Result.getAsDecl();
62 break;
Douglas Gregor7176fff2009-01-15 00:26:24 +000063 }
64
Steve Naroffa5189032009-01-29 18:09:31 +000065 if (IIDecl) {
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000066 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl))
67 return Context.getTypeDeclType(TD).getAsOpaquePtr();
68 else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl))
69 return Context.getObjCInterfaceType(IDecl).getAsOpaquePtr();
Steve Naroffa5189032009-01-29 18:09:31 +000070 }
Steve Naroff3536b442007-09-06 21:24:23 +000071 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000072}
73
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000074DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000075 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000076 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000077 if (MD->isOutOfLineDefinition())
78 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000079
80 // A C++ inline method is parsed *after* the topmost class it was declared in
81 // is fully parsed (it's "complete").
82 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000083 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000084 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
85 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000086 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000087 DC = RD;
88
89 // Return the declaration context of the topmost class the inline method is
90 // declared in.
91 return DC;
92 }
93
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000094 if (isa<ObjCMethodDecl>(DC))
95 return Context.getTranslationUnitDecl();
96
Douglas Gregor4afa39d2009-01-20 01:17:11 +000097 if (Decl *D = dyn_cast<Decl>(DC))
98 return D->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000099
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000100 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000101}
102
Douglas Gregor44b43212008-12-11 16:49:14 +0000103void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000104 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +0000105 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +0000106 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +0000107 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000108}
109
Chris Lattnerb048c982008-04-06 04:47:34 +0000110void Sema::PopDeclContext() {
111 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +0000112
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000113 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000114}
115
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000116/// Add this decl to the scope shadowed decl chains.
117void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000118 // Move up the scope chain until we find the nearest enclosing
119 // non-transparent context. The declaration will be introduced into this
120 // scope.
121 while (S->getEntity() &&
122 ((DeclContext *)S->getEntity())->isTransparentContext())
123 S = S->getParent();
124
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000125 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000126
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000127 // Add scoped declarations into their context, so that they can be
128 // found later. Declarations without a context won't be inserted
129 // into any context.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000130 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000131
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000132 // C++ [basic.scope]p4:
133 // -- exactly one declaration shall declare a class name or
134 // enumeration name that is not a typedef name and the other
135 // declarations shall all refer to the same object or
136 // enumerator, or all refer to functions and function templates;
137 // in this case the class name or enumeration name is hidden.
138 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
139 // We are pushing the name of a tag (enum or class).
Douglas Gregore21b9942009-01-07 16:34:42 +0000140 if (CurContext->getLookupContext()
141 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000142 // We're pushing the tag into the current context, which might
143 // require some reshuffling in the identifier resolver.
144 IdentifierResolver::iterator
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000145 I = IdResolver.begin(TD->getDeclName()),
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000146 IEnd = IdResolver.end();
147 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
148 NamedDecl *PrevDecl = *I;
149 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
150 PrevDecl = *I, ++I) {
151 if (TD->declarationReplaces(*I)) {
152 // This is a redeclaration. Remove it from the chain and
153 // break out, so that we'll add in the shadowed
154 // declaration.
155 S->RemoveDecl(*I);
156 if (PrevDecl == *I) {
157 IdResolver.RemoveDecl(*I);
158 IdResolver.AddDecl(TD);
159 return;
160 } else {
161 IdResolver.RemoveDecl(*I);
162 break;
163 }
164 }
165 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000166
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000167 // There is already a declaration with the same name in the same
168 // scope, which is not a tag declaration. It must be found
169 // before we find the new declaration, so insert the new
170 // declaration at the end of the chain.
171 IdResolver.AddShadowedDecl(TD, PrevDecl);
172
173 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000174 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000175 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000176 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000177 // We are pushing the name of a function, which might be an
178 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000179 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000180 IdentifierResolver::iterator Redecl
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000181 = std::find_if(IdResolver.begin(FD->getDeclName()),
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000182 IdResolver.end(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000183 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000184 FD));
185 if (Redecl != IdResolver.end()) {
186 // There is already a declaration of a function on our
187 // IdResolver chain. Replace it with this declaration.
188 S->RemoveDecl(*Redecl);
189 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000190 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000191 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000192
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000193 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000194}
195
Steve Naroffb216c882007-10-09 22:01:59 +0000196void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000197 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000198 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
199 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000200
Reid Spencer5f016e22007-07-11 17:01:13 +0000201 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
202 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000203 Decl *TmpD = static_cast<Decl*>(*I);
204 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000205
Douglas Gregor44b43212008-12-11 16:49:14 +0000206 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
207 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000208
Douglas Gregor44b43212008-12-11 16:49:14 +0000209 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000210
Douglas Gregor44b43212008-12-11 16:49:14 +0000211 // Remove this name from our lexical scope.
212 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 }
214}
215
Steve Naroffe8043c32008-04-01 23:04:06 +0000216/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
217/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000218ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000219 // The third "scope" argument is 0 since we aren't enabling lazy built-in
220 // creation from this context.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000221 NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000222
Steve Naroffb327ce02008-04-02 14:35:35 +0000223 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000224}
225
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000226/// getNonFieldDeclScope - Retrieves the innermost scope, starting
227/// from S, where a non-field would be declared. This routine copes
228/// with the difference between C and C++ scoping rules in structs and
229/// unions. For example, the following code is well-formed in C but
230/// ill-formed in C++:
231/// @code
232/// struct S6 {
233/// enum { BAR } e;
234/// };
235///
236/// void test_S6() {
237/// struct S6 a;
238/// a.e = BAR;
239/// }
240/// @endcode
241/// For the declaration of BAR, this routine will return a different
242/// scope. The scope S will be the scope of the unnamed enumeration
243/// within S6. In C++, this routine will return the scope associated
244/// with S6, because the enumeration's scope is a transparent
245/// context but structures can contain non-field names. In C, this
246/// routine will return the translation unit scope, since the
247/// enumeration's scope is a transparent context and structures cannot
248/// contain non-field names.
249Scope *Sema::getNonFieldDeclScope(Scope *S) {
250 while (((S->getFlags() & Scope::DeclScope) == 0) ||
251 (S->getEntity() &&
252 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
253 (S->isClassScope() && !getLangOptions().CPlusPlus))
254 S = S->getParent();
255 return S;
256}
257
Chris Lattner95e2c712008-05-05 22:18:14 +0000258void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000259 if (!Context.getBuiltinVaListType().isNull())
260 return;
261
262 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000263 NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
Steve Naroff733002f2007-10-18 22:17:45 +0000264 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000265 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
266}
267
Reid Spencer5f016e22007-07-11 17:01:13 +0000268/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
269/// lazily create a decl for it.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000270NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
271 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 Builtin::ID BID = (Builtin::ID)bid;
273
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000274 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000275 InitBuiltinVaListType();
276
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000277 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000278 FunctionDecl *New = FunctionDecl::Create(Context,
279 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000280 SourceLocation(), II, R,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000281 FunctionDecl::Extern, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000282
Chris Lattner95e2c712008-05-05 22:18:14 +0000283 // Create Decl objects for each parameter, adding them to the
284 // FunctionDecl.
285 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
286 llvm::SmallVector<ParmVarDecl*, 16> Params;
287 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
288 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000289 FT->getArgType(i), VarDecl::None, 0));
Ted Kremenekfc767612009-01-14 00:42:25 +0000290 New->setParams(Context, &Params[0], Params.size());
Chris Lattner95e2c712008-05-05 22:18:14 +0000291 }
292
293
294
Chris Lattner7f925cc2008-04-11 07:00:53 +0000295 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000296 // FIXME: This is hideous. We need to teach PushOnScopeChains to
297 // relate Scopes to DeclContexts, and probably eliminate CurContext
298 // entirely, but we're not there yet.
299 DeclContext *SavedContext = CurContext;
300 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000301 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000302 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 return New;
304}
305
Sebastian Redlc42e1182008-11-11 11:37:55 +0000306/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
307/// everything from the standard library is defined.
308NamespaceDecl *Sema::GetStdNamespace() {
309 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000310 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000311 DeclContext *Global = Context.getTranslationUnitDecl();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000312 Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000313 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
314 }
315 return StdNamespace;
316}
317
Reid Spencer5f016e22007-07-11 17:01:13 +0000318/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
319/// and scope as a previous declaration 'Old'. Figure out how to resolve this
320/// situation, merging decls or emitting diagnostics as appropriate.
321///
Steve Naroffe8043c32008-04-01 23:04:06 +0000322TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000323 bool objc_types = false;
Steve Naroff2b255c42008-09-09 14:32:20 +0000324 // Allow multiple definitions for ObjC built-in typedefs.
325 // FIXME: Verify the underlying types are equivalent!
326 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000327 const IdentifierInfo *TypeID = New->getIdentifier();
328 switch (TypeID->getLength()) {
329 default: break;
330 case 2:
331 if (!TypeID->isStr("id"))
332 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000333 Context.setObjCIdType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000334 objc_types = true;
335 break;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000336 case 5:
337 if (!TypeID->isStr("Class"))
338 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000339 Context.setObjCClassType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000340 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000341 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000342 case 3:
343 if (!TypeID->isStr("SEL"))
344 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000345 Context.setObjCSelType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000346 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000347 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000348 case 8:
349 if (!TypeID->isStr("Protocol"))
350 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000351 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000352 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000353 return New;
354 }
355 // Fall through - the typedef name was not a builtin type.
356 }
Douglas Gregor66973122009-01-28 17:15:10 +0000357 // Verify the old decl was also a type.
358 TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 if (!Old) {
Douglas Gregor66973122009-01-28 17:15:10 +0000360 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000361 << New->getDeclName();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000362 if (!objc_types)
363 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000364 return New;
365 }
Douglas Gregor66973122009-01-28 17:15:10 +0000366
367 // Determine the "old" type we'll use for checking and diagnostics.
368 QualType OldType;
369 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
370 OldType = OldTypedef->getUnderlyingType();
371 else
372 OldType = Context.getTypeDeclType(Old);
373
Chris Lattner99cb9972008-07-25 18:44:27 +0000374 // If the typedef types are not identical, reject them in all languages and
375 // with any extensions enabled.
Douglas Gregor66973122009-01-28 17:15:10 +0000376
377 if (OldType != New->getUnderlyingType() &&
378 Context.getCanonicalType(OldType) !=
Chris Lattner99cb9972008-07-25 18:44:27 +0000379 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000380 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregor66973122009-01-28 17:15:10 +0000381 << New->getUnderlyingType() << OldType;
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000382 if (!objc_types)
383 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000384 return New;
Chris Lattner99cb9972008-07-25 18:44:27 +0000385 }
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000386 if (objc_types) return New;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000387 if (getLangOptions().Microsoft) return New;
388
Douglas Gregorbbe27432008-11-21 16:29:06 +0000389 // C++ [dcl.typedef]p2:
390 // In a given non-class scope, a typedef specifier can be used to
391 // redefine the name of any type declared in that scope to refer
392 // to the type to which it already refers.
393 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
394 return New;
395
396 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000397 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
398 // *either* declaration is in a system header. The code below implements
399 // this adhoc compatibility rule. FIXME: The following code will not
400 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000401 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
402 SourceManager &SrcMgr = Context.getSourceManager();
403 if (SrcMgr.isInSystemHeader(Old->getLocation()))
404 return New;
405 if (SrcMgr.isInSystemHeader(New->getLocation()))
406 return New;
407 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000408
Chris Lattner08631c52008-11-23 21:45:46 +0000409 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000410 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 return New;
412}
413
Chris Lattner6b6b5372008-06-26 18:38:35 +0000414/// DeclhasAttr - returns true if decl Declaration already has the target
415/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000416static bool DeclHasAttr(const Decl *decl, const Attr *target) {
417 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
418 if (attr->getKind() == target->getKind())
419 return true;
420
421 return false;
422}
423
424/// MergeAttributes - append attributes from the Old decl to the New one.
425static void MergeAttributes(Decl *New, Decl *Old) {
426 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
427
Chris Lattnerddee4232008-03-03 03:28:21 +0000428 while (attr) {
429 tmp = attr;
430 attr = attr->getNext();
431
432 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000433 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000434 New->addAttr(tmp);
435 } else {
436 tmp->setNext(0);
437 delete(tmp);
438 }
439 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000440
441 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000442}
443
Chris Lattner04421082008-04-08 04:40:51 +0000444/// MergeFunctionDecl - We just parsed a function 'New' from
445/// declarator D which has the same name and scope as a previous
446/// declaration 'Old'. Figure out how to resolve this situation,
447/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000448/// Redeclaration will be set true if this New is a redeclaration OldD.
449///
450/// In C++, New and Old must be declarations that are not
451/// overloaded. Use IsOverload to determine whether New and Old are
452/// overloaded, and to select the Old declaration that New should be
453/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000454FunctionDecl *
455Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000456 assert(!isa<OverloadedFunctionDecl>(OldD) &&
457 "Cannot merge with an overloaded function declaration");
458
Douglas Gregorf0097952008-04-21 02:02:58 +0000459 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000460 // Verify the old decl was also a function.
461 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
462 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000463 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000464 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000465 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 return New;
467 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000468
469 // Determine whether the previous declaration was a definition,
470 // implicit declaration, or a declaration.
471 diag::kind PrevDiag;
472 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000473 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000475 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000476 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000477 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000478
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000479 QualType OldQType = Context.getCanonicalType(Old->getType());
480 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000481
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000482 if (getLangOptions().CPlusPlus) {
483 // (C++98 13.1p2):
484 // Certain function declarations cannot be overloaded:
485 // -- Function declarations that differ only in the return type
486 // cannot be overloaded.
487 QualType OldReturnType
488 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
489 QualType NewReturnType
490 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
491 if (OldReturnType != NewReturnType) {
492 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
493 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000494 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000495 return New;
496 }
497
498 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
499 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
500 if (OldMethod && NewMethod) {
501 // -- Member function declarations with the same name and the
502 // same parameter types cannot be overloaded if any of them
503 // is a static member function declaration.
504 if (OldMethod->isStatic() || NewMethod->isStatic()) {
505 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
506 Diag(Old->getLocation(), PrevDiag);
507 return New;
508 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000509
510 // C++ [class.mem]p1:
511 // [...] A member shall not be declared twice in the
512 // member-specification, except that a nested class or member
513 // class template can be declared and then later defined.
514 if (OldMethod->getLexicalDeclContext() ==
515 NewMethod->getLexicalDeclContext()) {
516 unsigned NewDiag;
517 if (isa<CXXConstructorDecl>(OldMethod))
518 NewDiag = diag::err_constructor_redeclared;
519 else if (isa<CXXDestructorDecl>(NewMethod))
520 NewDiag = diag::err_destructor_redeclared;
521 else if (isa<CXXConversionDecl>(NewMethod))
522 NewDiag = diag::err_conv_function_redeclared;
523 else
524 NewDiag = diag::err_member_redeclared;
525
526 Diag(New->getLocation(), NewDiag);
527 Diag(Old->getLocation(), PrevDiag);
528 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529 }
530
531 // (C++98 8.3.5p3):
532 // All declarations for a function shall agree exactly in both the
533 // return type and the parameter-type-list.
534 if (OldQType == NewQType) {
535 // We have a redeclaration.
536 MergeAttributes(New, Old);
537 Redeclaration = true;
538 return MergeCXXFunctionDecl(New, Old);
539 }
540
541 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000542 }
Chris Lattner04421082008-04-08 04:40:51 +0000543
544 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000545 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000546 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000547 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000548 MergeAttributes(New, Old);
549 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000550 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000551 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000552
Steve Naroff837618c2008-01-16 15:01:34 +0000553 // A function that has already been declared has been redeclared or defined
554 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000555
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
557 // TODO: This is totally simplistic. It should handle merging functions
558 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000559 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000560 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 return New;
562}
563
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000564/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000565static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000566 if (VD->isFileVarDecl())
567 return (!VD->getInit() &&
568 (VD->getStorageClass() == VarDecl::None ||
569 VD->getStorageClass() == VarDecl::Static));
570 return false;
571}
572
573/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
574/// when dealing with C "tentative" external object definitions (C99 6.9.2).
575void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
576 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000577 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000578
Douglas Gregore21b9942009-01-07 16:34:42 +0000579 // FIXME: I don't think this will actually see all of the
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000580 // redefinitions. Can't we check this property on-the-fly?
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000581 for (IdentifierResolver::iterator I = IdResolver.begin(VD->getIdentifier()),
582 E = IdResolver.end();
583 I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000584 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000585 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
586
Steve Narofff855e6f2008-08-10 15:20:13 +0000587 // Handle the following case:
588 // int a[10];
589 // int a[]; - the code below makes sure we set the correct type.
590 // int a[11]; - this is an error, size isn't 10.
591 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
592 OldDecl->getType()->isConstantArrayType())
593 VD->setType(OldDecl->getType());
594
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000595 // Check for "tentative" definitions. We can't accomplish this in
596 // MergeVarDecl since the initializer hasn't been attached.
597 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
598 continue;
599
600 // Handle __private_extern__ just like extern.
601 if (OldDecl->getStorageClass() != VarDecl::Extern &&
602 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
603 VD->getStorageClass() != VarDecl::Extern &&
604 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000605 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000606 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Sebastian Redl89ef6e02009-02-08 10:49:44 +0000607 // One redefinition error is enough.
608 break;
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000609 }
610 }
611 }
612}
613
Reid Spencer5f016e22007-07-11 17:01:13 +0000614/// MergeVarDecl - We just parsed a variable 'New' which has the same name
615/// and scope as a previous declaration 'Old'. Figure out how to resolve this
616/// situation, merging decls or emitting diagnostics as appropriate.
617///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000618/// Tentative definition rules (C99 6.9.2p2) are checked by
619/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
620/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000621///
Steve Naroffe8043c32008-04-01 23:04:06 +0000622VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000623 // Verify the old decl was also a variable.
624 VarDecl *Old = dyn_cast<VarDecl>(OldD);
625 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000626 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000627 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000628 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000629 return New;
630 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000631
632 MergeAttributes(New, Old);
633
Eli Friedman13ca96a2009-01-24 23:49:55 +0000634 // Merge the types
635 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
636 if (MergedT.isNull()) {
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000637 Diag(New->getLocation(), diag::err_redefinition_different_type)
638 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000639 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 return New;
641 }
Eli Friedman13ca96a2009-01-24 23:49:55 +0000642 New->setType(MergedT);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000643 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
644 if (New->getStorageClass() == VarDecl::Static &&
645 (Old->getStorageClass() == VarDecl::None ||
646 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000647 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000648 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000649 return New;
650 }
651 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
652 if (New->getStorageClass() != VarDecl::Static &&
653 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000654 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000655 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000656 return New;
657 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000658 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
659 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000660 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000661 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000662 }
663 return New;
664}
665
Chris Lattner04421082008-04-08 04:40:51 +0000666/// CheckParmsForFunctionDef - Check that the parameters of the given
667/// function are appropriate for the definition of a function. This
668/// takes care of any checks that cannot be performed on the
669/// declaration itself, e.g., that the types of each of the function
670/// parameters are complete.
671bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
672 bool HasInvalidParm = false;
673 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
674 ParmVarDecl *Param = FD->getParamDecl(p);
675
676 // C99 6.7.5.3p4: the parameters in a parameter type list in a
677 // function declarator that is part of a function definition of
678 // that function shall not have incomplete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000679 if (!Param->isInvalidDecl() &&
680 DiagnoseIncompleteType(Param->getLocation(), Param->getType(),
681 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattner04421082008-04-08 04:40:51 +0000682 Param->setInvalidDecl();
683 HasInvalidParm = true;
684 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000685
686 // C99 6.9.1p5: If the declarator includes a parameter type list, the
687 // declaration of each parameter shall include an identifier.
688 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
689 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000690 }
691
692 return HasInvalidParm;
693}
694
Reid Spencer5f016e22007-07-11 17:01:13 +0000695/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
696/// no declarator (e.g. "struct foo;") is parsed.
697Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000698 TagDecl *Tag = 0;
699 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
700 DS.getTypeSpecType() == DeclSpec::TST_struct ||
701 DS.getTypeSpecType() == DeclSpec::TST_union ||
702 DS.getTypeSpecType() == DeclSpec::TST_enum)
703 Tag = dyn_cast<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
704
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000705 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
706 if (!Record->getDeclName() && Record->isDefinition() &&
707 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
708 return BuildAnonymousStructOrUnion(S, DS, Record);
709
710 // Microsoft allows unnamed struct/union fields. Don't complain
711 // about them.
712 // FIXME: Should we support Microsoft's extensions in this area?
713 if (Record->getDeclName() && getLangOptions().Microsoft)
714 return Tag;
715 }
716
Douglas Gregorddc29e12009-02-06 22:42:48 +0000717 if (!DS.isMissingDeclaratorOk() &&
718 DS.getTypeSpecType() != DeclSpec::TST_error) {
Douglas Gregor21282df2009-01-22 16:23:54 +0000719 // Warn about typedefs of enums without names, since this is an
720 // extension in both Microsoft an GNU.
Douglas Gregor8158f692009-01-17 02:55:50 +0000721 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
722 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor21282df2009-01-22 16:23:54 +0000723 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregoree159c12009-01-13 23:10:51 +0000724 << DS.getSourceRange();
725 return Tag;
726 }
727
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000728 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
729 << DS.getSourceRange();
730 return 0;
731 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000732
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000733 return Tag;
734}
735
736/// InjectAnonymousStructOrUnionMembers - Inject the members of the
737/// anonymous struct or union AnonRecord into the owning context Owner
738/// and scope S. This routine will be invoked just after we realize
739/// that an unnamed union or struct is actually an anonymous union or
740/// struct, e.g.,
741///
742/// @code
743/// union {
744/// int i;
745/// float f;
746/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
747/// // f into the surrounding scope.x
748/// @endcode
749///
750/// This routine is recursive, injecting the names of nested anonymous
751/// structs/unions into the owning context and scope as well.
752bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
753 RecordDecl *AnonRecord) {
754 bool Invalid = false;
755 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
756 FEnd = AnonRecord->field_end();
757 F != FEnd; ++F) {
758 if ((*F)->getDeclName()) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000759 NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
760 LookupOrdinaryName, true);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000761 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
762 // C++ [class.union]p2:
763 // The names of the members of an anonymous union shall be
764 // distinct from the names of any other entity in the
765 // scope in which the anonymous union is declared.
766 unsigned diagKind
767 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
768 : diag::err_anonymous_struct_member_redecl;
769 Diag((*F)->getLocation(), diagKind)
770 << (*F)->getDeclName();
771 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
772 Invalid = true;
773 } else {
774 // C++ [class.union]p2:
775 // For the purpose of name lookup, after the anonymous union
776 // definition, the members of the anonymous union are
777 // considered to have been defined in the scope in which the
778 // anonymous union is declared.
Douglas Gregor40f4e692009-01-20 16:54:50 +0000779 Owner->makeDeclVisibleInContext(*F);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000780 S->AddDecl(*F);
781 IdResolver.AddDecl(*F);
782 }
783 } else if (const RecordType *InnerRecordType
784 = (*F)->getType()->getAsRecordType()) {
785 RecordDecl *InnerRecord = InnerRecordType->getDecl();
786 if (InnerRecord->isAnonymousStructOrUnion())
787 Invalid = Invalid ||
788 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
789 }
790 }
791
792 return Invalid;
793}
794
795/// ActOnAnonymousStructOrUnion - Handle the declaration of an
796/// anonymous structure or union. Anonymous unions are a C++ feature
797/// (C++ [class.union]) and a GNU C extension; anonymous structures
798/// are a GNU C and GNU C++ extension.
799Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
800 RecordDecl *Record) {
801 DeclContext *Owner = Record->getDeclContext();
802
803 // Diagnose whether this anonymous struct/union is an extension.
804 if (Record->isUnion() && !getLangOptions().CPlusPlus)
805 Diag(Record->getLocation(), diag::ext_anonymous_union);
806 else if (!Record->isUnion())
807 Diag(Record->getLocation(), diag::ext_anonymous_struct);
808
809 // C and C++ require different kinds of checks for anonymous
810 // structs/unions.
811 bool Invalid = false;
812 if (getLangOptions().CPlusPlus) {
813 const char* PrevSpec = 0;
814 // C++ [class.union]p3:
815 // Anonymous unions declared in a named namespace or in the
816 // global namespace shall be declared static.
817 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
818 (isa<TranslationUnitDecl>(Owner) ||
819 (isa<NamespaceDecl>(Owner) &&
820 cast<NamespaceDecl>(Owner)->getDeclName()))) {
821 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
822 Invalid = true;
823
824 // Recover by adding 'static'.
825 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
826 }
827 // C++ [class.union]p3:
828 // A storage class is not allowed in a declaration of an
829 // anonymous union in a class scope.
830 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
831 isa<RecordDecl>(Owner)) {
832 Diag(DS.getStorageClassSpecLoc(),
833 diag::err_anonymous_union_with_storage_spec);
834 Invalid = true;
835
836 // Recover by removing the storage specifier.
837 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
838 PrevSpec);
839 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000840
841 // C++ [class.union]p2:
842 // The member-specification of an anonymous union shall only
843 // define non-static data members. [Note: nested types and
844 // functions cannot be declared within an anonymous union. ]
845 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
846 MemEnd = Record->decls_end();
847 Mem != MemEnd; ++Mem) {
848 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
849 // C++ [class.union]p3:
850 // An anonymous union shall not have private or protected
851 // members (clause 11).
852 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
853 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
854 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
855 Invalid = true;
856 }
857 } else if ((*Mem)->isImplicit()) {
858 // Any implicit members are fine.
Douglas Gregor1931b442009-02-03 00:34:39 +0000859 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
860 // This is a type that showed up in an
861 // elaborated-type-specifier inside the anonymous struct or
862 // union, but which actually declares a type outside of the
863 // anonymous struct or union. It's okay.
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000864 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
865 if (!MemRecord->isAnonymousStructOrUnion() &&
866 MemRecord->getDeclName()) {
867 // This is a nested type declaration.
868 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
869 << (int)Record->isUnion();
870 Invalid = true;
871 }
872 } else {
873 // We have something that isn't a non-static data
874 // member. Complain about it.
875 unsigned DK = diag::err_anonymous_record_bad_member;
876 if (isa<TypeDecl>(*Mem))
877 DK = diag::err_anonymous_record_with_type;
878 else if (isa<FunctionDecl>(*Mem))
879 DK = diag::err_anonymous_record_with_function;
880 else if (isa<VarDecl>(*Mem))
881 DK = diag::err_anonymous_record_with_static;
882 Diag((*Mem)->getLocation(), DK)
883 << (int)Record->isUnion();
884 Invalid = true;
885 }
886 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000887 } else {
888 // FIXME: Check GNU C semantics
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000889 if (Record->isUnion() && !Owner->isRecord()) {
890 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
891 << (int)getLangOptions().CPlusPlus;
892 Invalid = true;
893 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000894 }
895
896 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000897 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
898 << (int)getLangOptions().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000899 Invalid = true;
900 }
901
902 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000903 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000904 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
905 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
906 /*IdentifierInfo=*/0,
907 Context.getTypeDeclType(Record),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000908 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000909 Anon->setAccess(AS_public);
910 if (getLangOptions().CPlusPlus)
911 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000912 } else {
913 VarDecl::StorageClass SC;
914 switch (DS.getStorageClassSpec()) {
915 default: assert(0 && "Unknown storage class!");
916 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
917 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
918 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
919 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
920 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
921 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
922 case DeclSpec::SCS_mutable:
923 // mutable can only appear on non-static class members, so it's always
924 // an error here
925 Diag(Record->getLocation(), diag::err_mutable_nonmember);
926 Invalid = true;
927 SC = VarDecl::None;
928 break;
929 }
930
931 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
932 /*IdentifierInfo=*/0,
933 Context.getTypeDeclType(Record),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000934 SC, DS.getSourceRange().getBegin());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000935 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000936 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000937
938 // Add the anonymous struct/union object to the current
939 // context. We'll be referencing this object when we refer to one of
940 // its members.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000941 Owner->addDecl(Anon);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000942
943 // Inject the members of the anonymous struct/union into the owning
944 // context and into the identifier resolver chain for name lookup
945 // purposes.
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000946 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
947 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000948
949 // Mark this as an anonymous struct/union type. Note that we do not
950 // do this until after we have already checked and injected the
951 // members of this anonymous struct/union type, because otherwise
952 // the members could be injected twice: once by DeclContext when it
953 // builds its lookup table, and once by
954 // InjectAnonymousStructOrUnionMembers.
955 Record->setAnonymousStructOrUnion(true);
956
957 if (Invalid)
958 Anon->setInvalidDecl();
959
960 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +0000961}
962
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000963bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
964 bool DirectInit) {
Steve Narofff0090632007-09-02 02:04:30 +0000965 // Get the type before calling CheckSingleAssignmentConstraints(), since
966 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000967 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +0000968
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000969 if (getLangOptions().CPlusPlus) {
970 // FIXME: I dislike this error message. A lot.
971 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
972 return Diag(Init->getSourceRange().getBegin(),
973 diag::err_typecheck_convert_incompatible)
974 << DeclType << Init->getType() << "initializing"
975 << Init->getSourceRange();
976
977 return false;
978 }
Douglas Gregor45920e82008-12-19 17:40:08 +0000979
Chris Lattner5cf216b2008-01-04 18:04:52 +0000980 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
981 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
982 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000983}
984
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000985bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000986 const ArrayType *AT = Context.getAsArrayType(DeclT);
987
988 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000989 // C99 6.7.8p14. We have an array of character type with unknown size
990 // being initialized to a string literal.
991 llvm::APSInt ConstVal(32);
992 ConstVal = strLiteral->getByteLength() + 1;
993 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000994 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000995 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000996 } else {
997 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000998 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000999 // FIXME: Avoid truncation for 64-bit length strings.
1000 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001001 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001002 diag::warn_initializer_string_for_char_array_too_long)
1003 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001004 }
1005 // Set type from "char *" to "constant array of char".
1006 strLiteral->setType(DeclT);
1007 // For now, we always return false (meaning success).
1008 return false;
1009}
1010
1011StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001012 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +00001013 if (AT && AT->getElementType()->isCharType()) {
Anders Carlsson91b9f202009-01-24 17:47:50 +00001014 return dyn_cast<StringLiteral>(Init->IgnoreParens());
Steve Naroffa9960332008-01-25 00:51:06 +00001015 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001016 return 0;
1017}
1018
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001019bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1020 SourceLocation InitLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001021 DeclarationName InitEntity,
1022 bool DirectInit) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +00001023 if (DeclType->isDependentType() || Init->isTypeDependent())
1024 return false;
1025
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001026 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +00001027 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001028 // (8.3.2), shall be initialized by an object, or function, of
1029 // type T or by an object that can be converted into a T.
1030 if (DeclType->isReferenceType())
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001031 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001032
Steve Naroffca107302008-01-21 23:53:58 +00001033 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1034 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001035 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001036 return Diag(InitLoc, diag::err_variable_object_no_init)
1037 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +00001038
Steve Naroff2fdc3742007-12-10 22:44:33 +00001039 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1040 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001041 // FIXME: Handle wide strings
1042 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1043 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +00001044
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001045 // C++ [dcl.init]p14:
1046 // -- If the destination type is a (possibly cv-qualified) class
1047 // type:
1048 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1049 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1050 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1051
1052 // -- If the initialization is direct-initialization, or if it is
1053 // copy-initialization where the cv-unqualified version of the
1054 // source type is the same class as, or a derived class of, the
1055 // class of the destination, constructors are considered.
1056 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1057 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1058 CXXConstructorDecl *Constructor
1059 = PerformInitializationByConstructor(DeclType, &Init, 1,
1060 InitLoc, Init->getSourceRange(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001061 InitEntity,
1062 DirectInit? IK_Direct : IK_Copy);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001063 return Constructor == 0;
1064 }
1065
1066 // -- Otherwise (i.e., for the remaining copy-initialization
1067 // cases), user-defined conversion sequences that can
1068 // convert from the source type to the destination type or
1069 // (when a conversion function is used) to a derived class
1070 // thereof are enumerated as described in 13.3.1.4, and the
1071 // best one is chosen through overload resolution
1072 // (13.3). If the conversion cannot be done or is
1073 // ambiguous, the initialization is ill-formed. The
1074 // function selected is called with the initializer
1075 // expression as its argument; if the function is a
1076 // constructor, the call initializes a temporary of the
1077 // destination type.
1078 // FIXME: We're pretending to do copy elision here; return to
1079 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +00001080 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001081 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001082
Douglas Gregor61366e92008-12-24 00:01:03 +00001083 if (InitEntity)
1084 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1085 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1086 << Init->getType() << Init->getSourceRange();
1087 else
1088 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1089 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1090 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001091 }
1092
Steve Naroff1ac6fdd2008-09-29 20:07:05 +00001093 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +00001094 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001095 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1096 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +00001097
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001098 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregor930d8b52009-01-30 22:09:00 +00001099 }
Eli Friedmane6f058f2008-06-06 19:40:52 +00001100
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001101 bool hadError = CheckInitList(InitList, DeclType);
1102 Init = InitList;
1103 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +00001104}
1105
Douglas Gregor10bd3682008-11-17 22:58:34 +00001106/// GetNameForDeclarator - Determine the full declaration name for the
1107/// given Declarator.
1108DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1109 switch (D.getKind()) {
1110 case Declarator::DK_Abstract:
1111 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1112 return DeclarationName();
1113
1114 case Declarator::DK_Normal:
1115 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1116 return DeclarationName(D.getIdentifier());
1117
1118 case Declarator::DK_Constructor: {
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001119 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001120 Ty = Context.getCanonicalType(Ty);
1121 return Context.DeclarationNames.getCXXConstructorName(Ty);
1122 }
1123
1124 case Declarator::DK_Destructor: {
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001125 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001126 Ty = Context.getCanonicalType(Ty);
1127 return Context.DeclarationNames.getCXXDestructorName(Ty);
1128 }
1129
1130 case Declarator::DK_Conversion: {
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001131 // FIXME: We'd like to keep the non-canonical type for diagnostics!
Douglas Gregor10bd3682008-11-17 22:58:34 +00001132 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1133 Ty = Context.getCanonicalType(Ty);
1134 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1135 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001136
1137 case Declarator::DK_Operator:
1138 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1139 return Context.DeclarationNames.getCXXOperatorName(
1140 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001141 }
1142
1143 assert(false && "Unknown name kind");
1144 return DeclarationName();
1145}
1146
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001147/// isNearlyMatchingFunction - Determine whether the C++ functions
1148/// Declaration and Definition are "nearly" matching. This heuristic
1149/// is used to improve diagnostics in the case where an out-of-line
1150/// function definition doesn't match any declaration within
1151/// the class or namespace.
1152static bool isNearlyMatchingFunction(ASTContext &Context,
1153 FunctionDecl *Declaration,
1154 FunctionDecl *Definition) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001155 if (Declaration->param_size() != Definition->param_size())
1156 return false;
1157 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1158 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1159 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1160
1161 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1162 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1163 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1164 return false;
1165 }
1166
1167 return true;
1168}
1169
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001170Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001171Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1172 bool IsFunctionDefinition) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001173 NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001174 DeclarationName Name = GetNameForDeclarator(D);
1175
Chris Lattnere80a59c2007-07-25 00:24:17 +00001176 // All of these full declarators require an identifier. If it doesn't have
1177 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001178 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001179 if (!D.getInvalidType()) // Reject this if we think it is valid.
1180 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001181 diag::err_declarator_need_ident)
1182 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001183 return 0;
1184 }
1185
Chris Lattner31e05722007-08-26 06:24:45 +00001186 // The scope passed in may not be a decl scope. Zip up the scope tree until
1187 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001188 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregoraaba5e32009-02-04 19:02:06 +00001189 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001190 S = S->getParent();
1191
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001192 DeclContext *DC;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001193 NamedDecl *PrevDecl;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001194 NamedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001195 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001196
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001197 // See if this is a redefinition of a variable in the same scope.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001198 if (!D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid()) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001199 DC = CurContext;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001200 PrevDecl = LookupName(S, Name, LookupOrdinaryName);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001201 } else { // Something like "int foo::x;"
1202 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001203 PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001204
1205 // C++ 7.3.1.2p2:
1206 // Members (including explicit specializations of templates) of a named
1207 // namespace can also be defined outside that namespace by explicit
1208 // qualification of the name being defined, provided that the entity being
1209 // defined was already declared in the namespace and the definition appears
1210 // after the point of declaration in a namespace that encloses the
1211 // declarations namespace.
1212 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001213 // Note that we only check the context at this point. We don't yet
1214 // have enough information to make sure that PrevDecl is actually
1215 // the declaration we want to match. For example, given:
1216 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001217 // class X {
1218 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001219 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001220 // };
1221 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001222 // void X::f(int) { } // ill-formed
1223 //
1224 // In this case, PrevDecl will point to the overload set
1225 // containing the two f's declared in X, but neither of them
1226 // matches.
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001227
1228 // First check whether we named the global scope.
1229 if (isa<TranslationUnitDecl>(DC)) {
1230 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
1231 << Name << D.getCXXScopeSpec().getRange();
1232 } else if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001233 // The qualifying scope doesn't enclose the original declaration.
1234 // Emit diagnostic based on current scope.
1235 SourceLocation L = D.getIdentifierLoc();
1236 SourceRange R = D.getCXXScopeSpec().getRange();
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001237 if (isa<FunctionDecl>(CurContext))
Chris Lattner011bb4e2008-11-23 20:28:15 +00001238 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001239 else
Chris Lattner011bb4e2008-11-23 20:28:15 +00001240 Diag(L, diag::err_invalid_declarator_scope)
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001241 << Name << cast<NamedDecl>(DC) << R;
Douglas Gregor44b43212008-12-11 16:49:14 +00001242 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001243 }
1244 }
1245
Douglas Gregorf57172b2008-12-08 18:40:42 +00001246 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001247 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001248 InvalidDecl = InvalidDecl
1249 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001250 // Just pretend that we didn't see the previous declaration.
1251 PrevDecl = 0;
1252 }
1253
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001254 // In C++, the previous declaration we find might be a tag type
1255 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00001256 // tag type. Note that this does does not apply if we're declaring a
1257 // typedef (C++ [dcl.typedef]p4).
1258 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1259 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001260 PrevDecl = 0;
1261
Chris Lattner41af0932007-11-14 06:34:38 +00001262 QualType R = GetTypeForDeclarator(D, S);
1263 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1264
Reid Spencer5f016e22007-07-11 17:01:13 +00001265 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001266 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1267 InvalidDecl);
Chris Lattner41af0932007-11-14 06:34:38 +00001268 } else if (R.getTypePtr()->isFunctionType()) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001269 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1270 IsFunctionDefinition, InvalidDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001271 } else {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001272 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1273 InvalidDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001274 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001275
1276 if (New == 0)
1277 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001278
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001279 // Set the lexical context. If the declarator has a C++ scope specifier, the
1280 // lexical context will be different from the semantic context.
1281 New->setLexicalDeclContext(CurContext);
1282
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001284 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001285 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001286 // If any semantic error occurred, mark the decl as invalid.
1287 if (D.getInvalidType() || InvalidDecl)
1288 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001289
1290 return New;
1291}
1292
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001293NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001294Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001295 QualType R, Decl* LastDeclarator,
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001296 Decl* PrevDecl, bool& InvalidDecl) {
1297 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1298 if (D.getCXXScopeSpec().isSet()) {
1299 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1300 << D.getCXXScopeSpec().getRange();
1301 InvalidDecl = true;
1302 // Pretend we didn't see the scope specifier.
1303 DC = 0;
1304 }
1305
1306 // Check that there are no default arguments (C++ only).
1307 if (getLangOptions().CPlusPlus)
1308 CheckExtraCXXDefaultArguments(D);
1309
1310 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1311 if (!NewTD) return 0;
1312
1313 // Handle attributes prior to checking for duplicates in MergeVarDecl
1314 ProcessDeclAttributes(NewTD, D);
1315 // Merge the decl with the existing one if appropriate. If the decl is
1316 // in an outer scope, it isn't the same thing.
1317 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1318 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1319 if (NewTD == 0) return 0;
1320 }
1321
1322 if (S->getFnParent() == 0) {
1323 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1324 // then it shall have block scope.
1325 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1326 if (NewTD->getUnderlyingType()->isVariableArrayType())
1327 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1328 else
1329 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1330
1331 InvalidDecl = true;
1332 }
1333 }
1334 return NewTD;
1335}
1336
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001337NamedDecl*
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001338Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001339 QualType R, Decl* LastDeclarator,
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001340 Decl* PrevDecl, bool& InvalidDecl) {
1341 DeclarationName Name = GetNameForDeclarator(D);
1342
1343 // Check that there are no default arguments (C++ only).
1344 if (getLangOptions().CPlusPlus)
1345 CheckExtraCXXDefaultArguments(D);
1346
1347 if (R.getTypePtr()->isObjCInterfaceType()) {
1348 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1349 << D.getIdentifier();
1350 InvalidDecl = true;
1351 }
1352
1353 VarDecl *NewVD;
1354 VarDecl::StorageClass SC;
1355 switch (D.getDeclSpec().getStorageClassSpec()) {
1356 default: assert(0 && "Unknown storage class!");
1357 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1358 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1359 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1360 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1361 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1362 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1363 case DeclSpec::SCS_mutable:
1364 // mutable can only appear on non-static class members, so it's always
1365 // an error here
1366 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1367 InvalidDecl = true;
1368 SC = VarDecl::None;
1369 break;
1370 }
1371
1372 IdentifierInfo *II = Name.getAsIdentifierInfo();
1373 if (!II) {
1374 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1375 << Name.getAsString();
1376 return 0;
1377 }
1378
1379 if (DC->isRecord()) {
1380 // This is a static data member for a C++ class.
1381 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1382 D.getIdentifierLoc(), II,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001383 R);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001384 } else {
1385 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1386 if (S->getFnParent() == 0) {
1387 // C99 6.9p2: The storage-class specifiers auto and register shall not
1388 // appear in the declaration specifiers in an external declaration.
1389 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1390 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1391 InvalidDecl = true;
1392 }
1393 }
1394 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001395 II, R, SC,
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001396 // FIXME: Move to DeclGroup...
1397 D.getDeclSpec().getSourceRange().getBegin());
1398 NewVD->setThreadSpecified(ThreadSpecified);
1399 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001400 NewVD->setNextDeclarator(LastDeclarator);
1401
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001402 // Handle attributes prior to checking for duplicates in MergeVarDecl
1403 ProcessDeclAttributes(NewVD, D);
1404
1405 // Handle GNU asm-label extension (encoded as an attribute).
1406 if (Expr *E = (Expr*) D.getAsmLabel()) {
1407 // The parser guarantees this is a string.
1408 StringLiteral *SE = cast<StringLiteral>(E);
1409 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1410 SE->getByteLength())));
1411 }
1412
1413 // Emit an error if an address space was applied to decl with local storage.
1414 // This includes arrays of objects with address space qualifiers, but not
1415 // automatic variables that point to other address spaces.
1416 // ISO/IEC TR 18037 S5.1.2
1417 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1418 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1419 InvalidDecl = true;
1420 }
1421 // Merge the decl with the existing one if appropriate. If the decl is
1422 // in an outer scope, it isn't the same thing.
1423 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1424 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1425 // The user tried to define a non-static data member
1426 // out-of-line (C++ [dcl.meaning]p1).
1427 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1428 << D.getCXXScopeSpec().getRange();
1429 NewVD->Destroy(Context);
1430 return 0;
1431 }
1432
1433 NewVD = MergeVarDecl(NewVD, PrevDecl);
1434 if (NewVD == 0) return 0;
1435
1436 if (D.getCXXScopeSpec().isSet()) {
1437 // No previous declaration in the qualifying scope.
1438 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1439 << Name << D.getCXXScopeSpec().getRange();
1440 InvalidDecl = true;
1441 }
1442 }
1443 return NewVD;
1444}
1445
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001446NamedDecl*
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001447Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001448 QualType R, Decl *LastDeclarator,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001449 Decl* PrevDecl, bool IsFunctionDefinition,
1450 bool& InvalidDecl) {
1451 assert(R.getTypePtr()->isFunctionType());
1452
1453 DeclarationName Name = GetNameForDeclarator(D);
1454 FunctionDecl::StorageClass SC = FunctionDecl::None;
1455 switch (D.getDeclSpec().getStorageClassSpec()) {
1456 default: assert(0 && "Unknown storage class!");
1457 case DeclSpec::SCS_auto:
1458 case DeclSpec::SCS_register:
1459 case DeclSpec::SCS_mutable:
1460 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1461 InvalidDecl = true;
1462 break;
1463 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1464 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1465 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
1466 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1467 }
1468
1469 bool isInline = D.getDeclSpec().isInlineSpecified();
1470 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1471 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1472
1473 FunctionDecl *NewFD;
1474 if (D.getKind() == Declarator::DK_Constructor) {
1475 // This is a C++ constructor declaration.
1476 assert(DC->isRecord() &&
1477 "Constructors can only be declared in a member context");
1478
1479 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1480
1481 // Create the new declaration
1482 NewFD = CXXConstructorDecl::Create(Context,
1483 cast<CXXRecordDecl>(DC),
1484 D.getIdentifierLoc(), Name, R,
1485 isExplicit, isInline,
1486 /*isImplicitlyDeclared=*/false);
1487
1488 if (InvalidDecl)
1489 NewFD->setInvalidDecl();
1490 } else if (D.getKind() == Declarator::DK_Destructor) {
1491 // This is a C++ destructor declaration.
1492 if (DC->isRecord()) {
1493 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1494
1495 NewFD = CXXDestructorDecl::Create(Context,
1496 cast<CXXRecordDecl>(DC),
1497 D.getIdentifierLoc(), Name, R,
1498 isInline,
1499 /*isImplicitlyDeclared=*/false);
1500
1501 if (InvalidDecl)
1502 NewFD->setInvalidDecl();
1503 } else {
1504 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1505
1506 // Create a FunctionDecl to satisfy the function definition parsing
1507 // code path.
1508 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001509 Name, R, SC, isInline,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001510 // FIXME: Move to DeclGroup...
1511 D.getDeclSpec().getSourceRange().getBegin());
1512 InvalidDecl = true;
1513 NewFD->setInvalidDecl();
1514 }
1515 } else if (D.getKind() == Declarator::DK_Conversion) {
1516 if (!DC->isRecord()) {
1517 Diag(D.getIdentifierLoc(),
1518 diag::err_conv_function_not_member);
1519 return 0;
1520 } else {
1521 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1522
1523 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1524 D.getIdentifierLoc(), Name, R,
1525 isInline, isExplicit);
1526
1527 if (InvalidDecl)
1528 NewFD->setInvalidDecl();
1529 }
1530 } else if (DC->isRecord()) {
1531 // This is a C++ method declaration.
1532 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1533 D.getIdentifierLoc(), Name, R,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001534 (SC == FunctionDecl::Static), isInline);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001535 } else {
1536 NewFD = FunctionDecl::Create(Context, DC,
1537 D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001538 Name, R, SC, isInline,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001539 // FIXME: Move to DeclGroup...
1540 D.getDeclSpec().getSourceRange().getBegin());
1541 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001542 NewFD->setNextDeclarator(LastDeclarator);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001543
1544 // Set the lexical context. If the declarator has a C++
1545 // scope specifier, the lexical context will be different
1546 // from the semantic context.
1547 NewFD->setLexicalDeclContext(CurContext);
1548
1549 // Handle GNU asm-label extension (encoded as an attribute).
1550 if (Expr *E = (Expr*) D.getAsmLabel()) {
1551 // The parser guarantees this is a string.
1552 StringLiteral *SE = cast<StringLiteral>(E);
1553 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1554 SE->getByteLength())));
1555 }
1556
1557 // Copy the parameter declarations from the declarator D to
1558 // the function declaration NewFD, if they are available.
1559 if (D.getNumTypeObjects() > 0) {
1560 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1561
1562 // Create Decl objects for each parameter, adding them to the
1563 // FunctionDecl.
1564 llvm::SmallVector<ParmVarDecl*, 16> Params;
1565
1566 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1567 // function that takes no arguments, not a function that takes a
1568 // single void argument.
1569 // We let through "const void" here because Sema::GetTypeForDeclarator
1570 // already checks for that case.
1571 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1572 FTI.ArgInfo[0].Param &&
1573 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1574 // empty arg list, don't push any params.
1575 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1576
1577 // In C++, the empty parameter-type-list must be spelled "void"; a
1578 // typedef of void is not permitted.
1579 if (getLangOptions().CPlusPlus &&
1580 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1581 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1582 }
1583 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1584 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1585 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1586 }
1587
1588 NewFD->setParams(Context, &Params[0], Params.size());
1589 } else if (R->getAsTypedefType()) {
1590 // When we're declaring a function with a typedef, as in the
1591 // following example, we'll need to synthesize (unnamed)
1592 // parameters for use in the declaration.
1593 //
1594 // @code
1595 // typedef void fn(int);
1596 // fn f;
1597 // @endcode
1598 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1599 if (!FT) {
1600 // This is a typedef of a function with no prototype, so we
1601 // don't need to do anything.
1602 } else if ((FT->getNumArgs() == 0) ||
1603 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1604 FT->getArgType(0)->isVoidType())) {
1605 // This is a zero-argument function. We don't need to do anything.
1606 } else {
1607 // Synthesize a parameter for each argument type.
1608 llvm::SmallVector<ParmVarDecl*, 16> Params;
1609 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1610 ArgType != FT->arg_type_end(); ++ArgType) {
1611 Params.push_back(ParmVarDecl::Create(Context, DC,
1612 SourceLocation(), 0,
1613 *ArgType, VarDecl::None,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001614 0));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001615 }
1616
1617 NewFD->setParams(Context, &Params[0], Params.size());
1618 }
1619 }
1620
1621 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1622 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1623 else if (isa<CXXDestructorDecl>(NewFD)) {
1624 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1625 Record->setUserDeclaredDestructor(true);
1626 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1627 // user-defined destructor.
1628 Record->setPOD(false);
1629 } else if (CXXConversionDecl *Conversion =
1630 dyn_cast<CXXConversionDecl>(NewFD))
1631 ActOnConversionDeclarator(Conversion);
1632
1633 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1634 if (NewFD->isOverloadedOperator() &&
1635 CheckOverloadedOperatorDeclaration(NewFD))
1636 NewFD->setInvalidDecl();
1637
1638 // Merge the decl with the existing one if appropriate. Since C functions
1639 // are in a flat namespace, make sure we consider decls in outer scopes.
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001640 bool Redeclaration = false;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001641 if (PrevDecl &&
1642 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001643 // If C++, determine whether NewFD is an overload of PrevDecl or
1644 // a declaration that requires merging. If it's an overload,
1645 // there's no more work to do here; we'll just add the new
1646 // function to the scope.
1647 OverloadedFunctionDecl::function_iterator MatchedDecl;
1648 if (!getLangOptions().CPlusPlus ||
1649 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1650 Decl *OldDecl = PrevDecl;
1651
1652 // If PrevDecl was an overloaded function, extract the
1653 // FunctionDecl that matched.
1654 if (isa<OverloadedFunctionDecl>(PrevDecl))
1655 OldDecl = *MatchedDecl;
1656
1657 // NewFD and PrevDecl represent declarations that need to be
1658 // merged.
1659 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1660
1661 if (NewFD == 0) return 0;
1662 if (Redeclaration) {
1663 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1664
1665 // An out-of-line member function declaration must also be a
1666 // definition (C++ [dcl.meaning]p1).
1667 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1668 !InvalidDecl) {
1669 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1670 << D.getCXXScopeSpec().getRange();
1671 NewFD->setInvalidDecl();
1672 }
1673 }
1674 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001675 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001676
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001677 if (D.getCXXScopeSpec().isSet() &&
1678 (!PrevDecl || !Redeclaration)) {
1679 // The user tried to provide an out-of-line definition for a
1680 // function that is a member of a class or namespace, but there
1681 // was no such member function declared (C++ [class.mfct]p2,
1682 // C++ [namespace.memdef]p2). For example:
1683 //
1684 // class X {
1685 // void f() const;
1686 // };
1687 //
1688 // void X::f() { } // ill-formed
1689 //
1690 // Complain about this problem, and attempt to suggest close
1691 // matches (e.g., those that differ only in cv-qualifiers and
1692 // whether the parameter types are references).
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001693 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
Douglas Gregor4b99bae2009-02-06 22:58:38 +00001694 << cast<NamedDecl>(DC) << D.getCXXScopeSpec().getRange();
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001695 InvalidDecl = true;
1696
1697 LookupResult Prev = LookupQualifiedName(DC, Name, LookupOrdinaryName,
1698 true);
1699 assert(!Prev.isAmbiguous() &&
1700 "Cannot have an ambiguity in previous-declaration lookup");
1701 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
1702 Func != FuncEnd; ++Func) {
1703 if (isa<FunctionDecl>(*Func) &&
1704 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
1705 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001706 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001707
1708 PrevDecl = 0;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001709 }
Douglas Gregord8635172009-02-02 21:35:47 +00001710
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001711 // Handle attributes. We need to have merged decls when handling attributes
1712 // (for example to check for conflicts, etc).
1713 ProcessDeclAttributes(NewFD, D);
1714
1715 if (getLangOptions().CPlusPlus) {
Sebastian Redl00d50742009-02-08 14:56:26 +00001716 // In C++, check default arguments now that we have merged decls. Unless
1717 // the lexical context is the class, because in this case this is done
1718 // during delayed parsing anyway.
1719 if (!CurContext->isRecord())
1720 CheckCXXDefaultArguments(NewFD);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001721
1722 // An out-of-line member function declaration must also be a
1723 // definition (C++ [dcl.meaning]p1).
1724 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1725 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1726 << D.getCXXScopeSpec().getRange();
1727 InvalidDecl = true;
1728 }
1729 }
1730 return NewFD;
1731}
1732
Steve Naroff6594a702008-10-27 11:34:16 +00001733void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001734 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1735 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001736}
1737
Eli Friedmanc594b322008-05-20 13:48:25 +00001738bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1739 switch (Init->getStmtClass()) {
1740 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001741 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001742 return true;
1743 case Expr::ParenExprClass: {
1744 const ParenExpr* PE = cast<ParenExpr>(Init);
1745 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1746 }
1747 case Expr::CompoundLiteralExprClass:
1748 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor1a49af92009-01-06 05:10:23 +00001749 case Expr::DeclRefExprClass:
1750 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001751 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001752 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1753 if (VD->hasGlobalStorage())
1754 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001755 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001756 return true;
1757 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001758 if (isa<FunctionDecl>(D))
1759 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001760 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001761 return true;
1762 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001763 case Expr::MemberExprClass: {
1764 const MemberExpr *M = cast<MemberExpr>(Init);
1765 if (M->isArrow())
1766 return CheckAddressConstantExpression(M->getBase());
1767 return CheckAddressConstantExpressionLValue(M->getBase());
1768 }
1769 case Expr::ArraySubscriptExprClass: {
1770 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1771 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1772 return CheckAddressConstantExpression(ASE->getBase()) ||
1773 CheckArithmeticConstantExpression(ASE->getIdx());
1774 }
1775 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001776 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001777 return false;
1778 case Expr::UnaryOperatorClass: {
1779 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1780
1781 // C99 6.6p9
1782 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001783 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001784
Steve Naroff6594a702008-10-27 11:34:16 +00001785 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001786 return true;
1787 }
1788 }
1789}
1790
1791bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1792 switch (Init->getStmtClass()) {
1793 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001794 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001795 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001796 case Expr::ParenExprClass:
1797 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001798 case Expr::StringLiteralClass:
1799 case Expr::ObjCStringLiteralClass:
1800 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001801 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001802 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001803 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1804 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1805 Builtin::BI__builtin___CFStringMakeConstantString)
1806 return false;
1807
Steve Naroff6594a702008-10-27 11:34:16 +00001808 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001809 return true;
1810
Eli Friedmanc594b322008-05-20 13:48:25 +00001811 case Expr::UnaryOperatorClass: {
1812 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1813
1814 // C99 6.6p9
1815 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1816 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1817
1818 if (Exp->getOpcode() == UnaryOperator::Extension)
1819 return CheckAddressConstantExpression(Exp->getSubExpr());
1820
Steve Naroff6594a702008-10-27 11:34:16 +00001821 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001822 return true;
1823 }
1824 case Expr::BinaryOperatorClass: {
1825 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1826 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1827
1828 Expr *PExp = Exp->getLHS();
1829 Expr *IExp = Exp->getRHS();
1830 if (IExp->getType()->isPointerType())
1831 std::swap(PExp, IExp);
1832
1833 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1834 return CheckAddressConstantExpression(PExp) ||
1835 CheckArithmeticConstantExpression(IExp);
1836 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001837 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001838 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001839 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001840 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1841 // Check for implicit promotion
1842 if (SubExpr->getType()->isFunctionType() ||
1843 SubExpr->getType()->isArrayType())
1844 return CheckAddressConstantExpressionLValue(SubExpr);
1845 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001846
1847 // Check for pointer->pointer cast
1848 if (SubExpr->getType()->isPointerType())
1849 return CheckAddressConstantExpression(SubExpr);
1850
Eli Friedmanc3f07642008-08-25 20:46:57 +00001851 if (SubExpr->getType()->isIntegralType()) {
1852 // Check for the special-case of a pointer->int->pointer cast;
1853 // this isn't standard, but some code requires it. See
1854 // PR2720 for an example.
1855 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1856 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1857 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1858 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1859 if (IntWidth >= PointerWidth) {
1860 return CheckAddressConstantExpression(SubCast->getSubExpr());
1861 }
1862 }
1863 }
1864 }
1865 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001866 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001867 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001868
Steve Naroff6594a702008-10-27 11:34:16 +00001869 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001870 return true;
1871 }
1872 case Expr::ConditionalOperatorClass: {
1873 // FIXME: Should we pedwarn here?
1874 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1875 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001876 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001877 return true;
1878 }
1879 if (CheckArithmeticConstantExpression(Exp->getCond()))
1880 return true;
1881 if (Exp->getLHS() &&
1882 CheckAddressConstantExpression(Exp->getLHS()))
1883 return true;
1884 return CheckAddressConstantExpression(Exp->getRHS());
1885 }
1886 case Expr::AddrLabelExprClass:
1887 return false;
1888 }
1889}
1890
Eli Friedman4caf0552008-06-09 05:05:07 +00001891static const Expr* FindExpressionBaseAddress(const Expr* E);
1892
1893static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1894 switch (E->getStmtClass()) {
1895 default:
1896 return E;
1897 case Expr::ParenExprClass: {
1898 const ParenExpr* PE = cast<ParenExpr>(E);
1899 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1900 }
1901 case Expr::MemberExprClass: {
1902 const MemberExpr *M = cast<MemberExpr>(E);
1903 if (M->isArrow())
1904 return FindExpressionBaseAddress(M->getBase());
1905 return FindExpressionBaseAddressLValue(M->getBase());
1906 }
1907 case Expr::ArraySubscriptExprClass: {
1908 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1909 return FindExpressionBaseAddress(ASE->getBase());
1910 }
1911 case Expr::UnaryOperatorClass: {
1912 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1913
1914 if (Exp->getOpcode() == UnaryOperator::Deref)
1915 return FindExpressionBaseAddress(Exp->getSubExpr());
1916
1917 return E;
1918 }
1919 }
1920}
1921
1922static const Expr* FindExpressionBaseAddress(const Expr* E) {
1923 switch (E->getStmtClass()) {
1924 default:
1925 return E;
1926 case Expr::ParenExprClass: {
1927 const ParenExpr* PE = cast<ParenExpr>(E);
1928 return FindExpressionBaseAddress(PE->getSubExpr());
1929 }
1930 case Expr::UnaryOperatorClass: {
1931 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1932
1933 // C99 6.6p9
1934 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1935 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1936
1937 if (Exp->getOpcode() == UnaryOperator::Extension)
1938 return FindExpressionBaseAddress(Exp->getSubExpr());
1939
1940 return E;
1941 }
1942 case Expr::BinaryOperatorClass: {
1943 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1944
1945 Expr *PExp = Exp->getLHS();
1946 Expr *IExp = Exp->getRHS();
1947 if (IExp->getType()->isPointerType())
1948 std::swap(PExp, IExp);
1949
1950 return FindExpressionBaseAddress(PExp);
1951 }
1952 case Expr::ImplicitCastExprClass: {
1953 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1954
1955 // Check for implicit promotion
1956 if (SubExpr->getType()->isFunctionType() ||
1957 SubExpr->getType()->isArrayType())
1958 return FindExpressionBaseAddressLValue(SubExpr);
1959
1960 // Check for pointer->pointer cast
1961 if (SubExpr->getType()->isPointerType())
1962 return FindExpressionBaseAddress(SubExpr);
1963
1964 // We assume that we have an arithmetic expression here;
1965 // if we don't, we'll figure it out later
1966 return 0;
1967 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001968 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001969 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1970
1971 // Check for pointer->pointer cast
1972 if (SubExpr->getType()->isPointerType())
1973 return FindExpressionBaseAddress(SubExpr);
1974
1975 // We assume that we have an arithmetic expression here;
1976 // if we don't, we'll figure it out later
1977 return 0;
1978 }
1979 }
1980}
1981
Anders Carlsson51fe9962008-11-22 21:04:56 +00001982bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001983 switch (Init->getStmtClass()) {
1984 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001985 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001986 return true;
1987 case Expr::ParenExprClass: {
1988 const ParenExpr* PE = cast<ParenExpr>(Init);
1989 return CheckArithmeticConstantExpression(PE->getSubExpr());
1990 }
1991 case Expr::FloatingLiteralClass:
1992 case Expr::IntegerLiteralClass:
1993 case Expr::CharacterLiteralClass:
1994 case Expr::ImaginaryLiteralClass:
1995 case Expr::TypesCompatibleExprClass:
1996 case Expr::CXXBoolLiteralExprClass:
1997 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001998 case Expr::CallExprClass:
1999 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002000 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002001
2002 // Allow any constant foldable calls to builtins.
2003 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00002004 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002005
Steve Naroff6594a702008-10-27 11:34:16 +00002006 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002007 return true;
2008 }
Douglas Gregor1a49af92009-01-06 05:10:23 +00002009 case Expr::DeclRefExprClass:
2010 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002011 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2012 if (isa<EnumConstantDecl>(D))
2013 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002014 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002015 return true;
2016 }
2017 case Expr::CompoundLiteralExprClass:
2018 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2019 // but vectors are allowed to be magic.
2020 if (Init->getType()->isVectorType())
2021 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002022 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002023 return true;
2024 case Expr::UnaryOperatorClass: {
2025 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2026
2027 switch (Exp->getOpcode()) {
2028 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2029 // See C99 6.6p3.
2030 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002031 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002032 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002033 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00002034 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2035 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002036 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002037 return true;
2038 case UnaryOperator::Extension:
2039 case UnaryOperator::LNot:
2040 case UnaryOperator::Plus:
2041 case UnaryOperator::Minus:
2042 case UnaryOperator::Not:
2043 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2044 }
2045 }
Sebastian Redl05189992008-11-11 17:56:53 +00002046 case Expr::SizeOfAlignOfExprClass: {
2047 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002048 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00002049 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00002050 return false;
2051 // alignof always evaluates to a constant.
2052 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00002053 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00002054 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002055 return true;
2056 }
2057 return false;
2058 }
2059 case Expr::BinaryOperatorClass: {
2060 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2061
2062 if (Exp->getLHS()->getType()->isArithmeticType() &&
2063 Exp->getRHS()->getType()->isArithmeticType()) {
2064 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2065 CheckArithmeticConstantExpression(Exp->getRHS());
2066 }
2067
Eli Friedman4caf0552008-06-09 05:05:07 +00002068 if (Exp->getLHS()->getType()->isPointerType() &&
2069 Exp->getRHS()->getType()->isPointerType()) {
2070 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2071 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2072
2073 // Only allow a null (constant integer) base; we could
2074 // allow some additional cases if necessary, but this
2075 // is sufficient to cover offsetof-like constructs.
2076 if (!LHSBase && !RHSBase) {
2077 return CheckAddressConstantExpression(Exp->getLHS()) ||
2078 CheckAddressConstantExpression(Exp->getRHS());
2079 }
2080 }
2081
Steve Naroff6594a702008-10-27 11:34:16 +00002082 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002083 return true;
2084 }
2085 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002086 case Expr::CStyleCastExprClass: {
Nuno Lopesff776452009-02-02 22:57:15 +00002087 const CastExpr *CE = cast<CastExpr>(Init);
2088 const Expr *SubExpr = CE->getSubExpr();
2089
Eli Friedman6d4abe12008-09-01 22:08:17 +00002090 if (SubExpr->getType()->isArithmeticType())
2091 return CheckArithmeticConstantExpression(SubExpr);
2092
Eli Friedmanb529d832008-09-02 09:37:00 +00002093 if (SubExpr->getType()->isPointerType()) {
2094 const Expr* Base = FindExpressionBaseAddress(SubExpr);
Nuno Lopesff776452009-02-02 22:57:15 +00002095 if (Base) {
2096 // the cast is only valid if done to a wide enough type
2097 if (Context.getTypeSize(CE->getType()) >=
2098 Context.getTypeSize(SubExpr->getType()))
2099 return false;
2100 } else {
2101 // If the pointer has a null base, this is an offsetof-like construct
2102 return CheckAddressConstantExpression(SubExpr);
2103 }
Eli Friedmanb529d832008-09-02 09:37:00 +00002104 }
2105
Steve Naroff6594a702008-10-27 11:34:16 +00002106 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00002107 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002108 }
2109 case Expr::ConditionalOperatorClass: {
2110 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00002111
2112 // If GNU extensions are disabled, we require all operands to be arithmetic
2113 // constant expressions.
2114 if (getLangOptions().NoExtensions) {
2115 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2116 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2117 CheckArithmeticConstantExpression(Exp->getRHS());
2118 }
2119
2120 // Otherwise, we have to emulate some of the behavior of fold here.
2121 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2122 // because it can constant fold things away. To retain compatibility with
2123 // GCC code, we see if we can fold the condition to a constant (which we
2124 // should always be able to do in theory). If so, we only require the
2125 // specified arm of the conditional to be a constant. This is a horrible
2126 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002127 Expr::EvalResult EvalResult;
2128 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2129 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002130 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00002131 // won't be able to either. Use it to emit the diagnostic though.
2132 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002133 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00002134 return Res;
2135 }
2136
2137 // Verify that the side following the condition is also a constant.
2138 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002139 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00002140 std::swap(TrueSide, FalseSide);
2141
2142 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00002143 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00002144
2145 // Okay, the evaluated side evaluates to a constant, so we accept this.
2146 // Check to see if the other side is obviously not a constant. If so,
2147 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002148 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00002149 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002150 diag::ext_typecheck_expression_not_constant_but_accepted)
2151 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00002152 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00002153 }
2154 }
2155}
2156
2157bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002158 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init))
2159 Init = DIE->getInit();
2160
Nuno Lopes9a979c32008-07-07 16:46:50 +00002161 Init = Init->IgnoreParens();
2162
Nate Begeman59b5da62009-01-18 03:20:47 +00002163 if (Init->isEvaluatable(Context))
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002164 return false;
2165
Eli Friedmanc594b322008-05-20 13:48:25 +00002166 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2167 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2168 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2169
Nuno Lopes9a979c32008-07-07 16:46:50 +00002170 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2171 return CheckForConstantInitializer(e->getInitializer(), DclT);
2172
Douglas Gregor3498bdb2009-01-29 17:44:32 +00002173 if (isa<ImplicitValueInitExpr>(Init)) {
2174 // FIXME: In C++, check for non-POD types.
2175 return false;
2176 }
2177
Eli Friedmanc594b322008-05-20 13:48:25 +00002178 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2179 unsigned numInits = Exp->getNumInits();
2180 for (unsigned i = 0; i < numInits; i++) {
2181 // FIXME: Need to get the type of the declaration for C++,
2182 // because it could be a reference?
Douglas Gregor4c678342009-01-28 21:54:33 +00002183
Eli Friedmanc594b322008-05-20 13:48:25 +00002184 if (CheckForConstantInitializer(Exp->getInit(i),
2185 Exp->getInit(i)->getType()))
2186 return true;
2187 }
2188 return false;
2189 }
2190
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002191 // FIXME: We can probably remove some of this code below, now that
2192 // Expr::Evaluate is doing the heavy lifting for scalars.
2193
Eli Friedmanc594b322008-05-20 13:48:25 +00002194 if (Init->isNullPointerConstant(Context))
2195 return false;
2196 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002197 QualType InitTy = Context.getCanonicalType(Init->getType())
2198 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002199 if (InitTy == Context.BoolTy) {
2200 // Special handling for pointers implicitly cast to bool;
2201 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2202 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2203 Expr* SubE = ICE->getSubExpr();
2204 if (SubE->getType()->isPointerType() ||
2205 SubE->getType()->isArrayType() ||
2206 SubE->getType()->isFunctionType()) {
2207 return CheckAddressConstantExpression(Init);
2208 }
2209 }
2210 } else if (InitTy->isIntegralType()) {
2211 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002212 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002213 SubE = CE->getSubExpr();
2214 // Special check for pointer cast to int; we allow as an extension
2215 // an address constant cast to an integer if the integer
2216 // is of an appropriate width (this sort of code is apparently used
2217 // in some places).
2218 // FIXME: Add pedwarn?
2219 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2220 if (SubE && (SubE->getType()->isPointerType() ||
2221 SubE->getType()->isArrayType() ||
2222 SubE->getType()->isFunctionType())) {
2223 unsigned IntWidth = Context.getTypeSize(Init->getType());
2224 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2225 if (IntWidth >= PointerWidth)
2226 return CheckAddressConstantExpression(Init);
2227 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002228 }
2229
2230 return CheckArithmeticConstantExpression(Init);
2231 }
2232
2233 if (Init->getType()->isPointerType())
2234 return CheckAddressConstantExpression(Init);
2235
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002236 // An array type at the top level that isn't an init-list must
2237 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002238 if (Init->getType()->isArrayType())
2239 return false;
2240
Nuno Lopes73419bf2008-09-01 18:42:41 +00002241 if (Init->getType()->isFunctionType())
2242 return false;
2243
Steve Naroff8af6a452008-10-02 17:12:56 +00002244 // Allow block exprs at top level.
2245 if (Init->getType()->isBlockPointerType())
2246 return false;
Nuno Lopes6ed2ef82009-01-15 16:44:45 +00002247
2248 // GCC cast to union extension
2249 // note: the validity of the cast expr is checked by CheckCastTypes()
2250 if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2251 QualType T = C->getType();
2252 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2253 }
2254
Steve Naroff6594a702008-10-27 11:34:16 +00002255 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002256 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002257}
2258
Sebastian Redl798d1192008-12-13 16:23:55 +00002259void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002260 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2261}
2262
2263/// AddInitializerToDecl - Adds the initializer Init to the
2264/// declaration dcl. If DirectInit is true, this is C++ direct
2265/// initialization rather than copy initialization.
2266void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002267 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002268 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002269 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002270
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002271 // If there is no declaration, there was an error parsing it. Just ignore
2272 // the initializer.
2273 if (RealDecl == 0) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00002274 Init->Destroy(Context);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002275 return;
2276 }
Steve Naroffbb204692007-09-12 14:07:44 +00002277
Steve Naroff410e3e22007-09-12 20:13:48 +00002278 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2279 if (!VDecl) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002280 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002281 RealDecl->setInvalidDecl();
2282 return;
2283 }
Steve Naroffbb204692007-09-12 14:07:44 +00002284 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002285 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002286 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002287 if (VDecl->isBlockVarDecl()) {
2288 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002289 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002290 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002291 VDecl->setInvalidDecl();
2292 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002293 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002294 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002295 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002296
2297 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2298 if (!getLangOptions().CPlusPlus) {
2299 if (SC == VarDecl::Static) // C99 6.7.8p4.
2300 CheckForConstantInitializer(Init, DclT);
2301 }
Steve Naroffbb204692007-09-12 14:07:44 +00002302 }
Steve Naroff248a7532008-04-15 22:42:06 +00002303 } else if (VDecl->isFileVarDecl()) {
2304 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002305 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002306 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002307 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002308 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002309 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002310
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002311 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2312 if (!getLangOptions().CPlusPlus) {
2313 // C99 6.7.8p4. All file scoped initializers need to be constant.
2314 CheckForConstantInitializer(Init, DclT);
2315 }
Steve Naroffbb204692007-09-12 14:07:44 +00002316 }
2317 // If the type changed, it means we had an incomplete type that was
2318 // completed by the initializer. For example:
2319 // int ary[] = { 1, 3, 5 };
2320 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002321 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002322 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002323 Init->setType(DclT);
2324 }
Steve Naroffbb204692007-09-12 14:07:44 +00002325
2326 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002327 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002328 return;
2329}
2330
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002331void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2332 Decl *RealDecl = static_cast<Decl *>(dcl);
2333
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002334 // If there is no declaration, there was an error parsing it. Just ignore it.
2335 if (RealDecl == 0)
2336 return;
2337
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002338 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2339 QualType Type = Var->getType();
2340 // C++ [dcl.init.ref]p3:
2341 // The initializer can be omitted for a reference only in a
2342 // parameter declaration (8.3.5), in the declaration of a
2343 // function return type, in the declaration of a class member
2344 // within its class declaration (9.2), and where the extern
2345 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002346 if (Type->isReferenceType() &&
2347 Var->getStorageClass() != VarDecl::Extern &&
2348 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002349 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002350 << Var->getDeclName()
2351 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002352 Var->setInvalidDecl();
2353 return;
2354 }
2355
2356 // C++ [dcl.init]p9:
2357 //
2358 // If no initializer is specified for an object, and the object
2359 // is of (possibly cv-qualified) non-POD class type (or array
2360 // thereof), the object shall be default-initialized; if the
2361 // object is of const-qualified type, the underlying class type
2362 // shall have a user-declared default constructor.
2363 if (getLangOptions().CPlusPlus) {
2364 QualType InitType = Type;
2365 if (const ArrayType *Array = Context.getAsArrayType(Type))
2366 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002367 if (Var->getStorageClass() != VarDecl::Extern &&
2368 Var->getStorageClass() != VarDecl::PrivateExtern &&
2369 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002370 const CXXConstructorDecl *Constructor
2371 = PerformInitializationByConstructor(InitType, 0, 0,
2372 Var->getLocation(),
2373 SourceRange(Var->getLocation(),
2374 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002375 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002376 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002377 if (!Constructor)
2378 Var->setInvalidDecl();
2379 }
2380 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002381
Douglas Gregor818ce482008-10-29 13:50:18 +00002382#if 0
2383 // FIXME: Temporarily disabled because we are not properly parsing
2384 // linkage specifications on declarations, e.g.,
2385 //
2386 // extern "C" const CGPoint CGPointerZero;
2387 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002388 // C++ [dcl.init]p9:
2389 //
2390 // If no initializer is specified for an object, and the
2391 // object is of (possibly cv-qualified) non-POD class type (or
2392 // array thereof), the object shall be default-initialized; if
2393 // the object is of const-qualified type, the underlying class
2394 // type shall have a user-declared default
2395 // constructor. Otherwise, if no initializer is specified for
2396 // an object, the object and its subobjects, if any, have an
2397 // indeterminate initial value; if the object or any of its
2398 // subobjects are of const-qualified type, the program is
2399 // ill-formed.
2400 //
2401 // This isn't technically an error in C, so we don't diagnose it.
2402 //
2403 // FIXME: Actually perform the POD/user-defined default
2404 // constructor check.
2405 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002406 Context.getCanonicalType(Type).isConstQualified() &&
2407 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002408 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2409 << Var->getName()
2410 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002411#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002412 }
2413}
2414
Reid Spencer5f016e22007-07-11 17:01:13 +00002415/// The declarators are chained together backwards, reverse the list.
2416Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2417 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002418 Decl *GroupDecl = static_cast<Decl*>(group);
2419 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002420 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002421
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002422 Decl *Group = dyn_cast<Decl>(GroupDecl);
2423 Decl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002424 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002425 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002426 else { // reverse the list.
2427 while (Group) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002428 Decl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002429 Group->setNextDeclarator(NewGroup);
2430 NewGroup = Group;
2431 Group = Next;
2432 }
2433 }
2434 // Perform semantic analysis that depends on having fully processed both
2435 // the declarator and initializer.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002436 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002437 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2438 if (!IDecl)
2439 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002440 QualType T = IDecl->getType();
2441
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002442 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002443 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002444
2445 // FIXME: This won't give the correct result for
2446 // int a[10][n];
2447 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002448 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002449 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2450 SizeRange;
2451
Eli Friedmanc5773c42008-02-15 18:16:39 +00002452 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002453 } else {
2454 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2455 // static storage duration, it shall not have a variable length array.
2456 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002457 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2458 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002459 IDecl->setInvalidDecl();
2460 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002461 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2462 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002463 IDecl->setInvalidDecl();
2464 }
2465 }
2466 } else if (T->isVariablyModifiedType()) {
2467 if (IDecl->isFileVarDecl()) {
2468 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2469 IDecl->setInvalidDecl();
2470 } else {
2471 if (IDecl->getStorageClass() == VarDecl::Extern) {
2472 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2473 IDecl->setInvalidDecl();
2474 }
Steve Naroffbb204692007-09-12 14:07:44 +00002475 }
2476 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002477
Steve Naroffbb204692007-09-12 14:07:44 +00002478 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2479 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002480 if (IDecl->isBlockVarDecl() &&
2481 IDecl->getStorageClass() != VarDecl::Extern) {
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002482 if (!IDecl->isInvalidDecl() &&
2483 DiagnoseIncompleteType(IDecl->getLocation(), T,
2484 diag::err_typecheck_decl_incomplete_type))
Steve Naroffbb204692007-09-12 14:07:44 +00002485 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00002486 }
2487 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2488 // object that has file scope without an initializer, and without a
2489 // storage-class specifier or with the storage-class specifier "static",
2490 // constitutes a tentative definition. Note: A tentative definition with
2491 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002492 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002493 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002494 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2495 // array to be completed. Don't issue a diagnostic.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002496 } else if (!IDecl->isInvalidDecl() &&
2497 DiagnoseIncompleteType(IDecl->getLocation(), T,
2498 diag::err_typecheck_decl_incomplete_type))
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002499 // C99 6.9.2p3: If the declaration of an identifier for an object is
2500 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2501 // declared type shall not be an incomplete type.
Steve Naroffbb204692007-09-12 14:07:44 +00002502 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00002503 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002504 if (IDecl->isFileVarDecl())
2505 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002506 }
2507 return NewGroup;
2508}
Steve Naroffe1223f72007-08-28 03:03:08 +00002509
Chris Lattner04421082008-04-08 04:40:51 +00002510/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2511/// to introduce parameters into function prototype scope.
2512Sema::DeclTy *
2513Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002514 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002515
Chris Lattner04421082008-04-08 04:40:51 +00002516 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002517 VarDecl::StorageClass StorageClass = VarDecl::None;
2518 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2519 StorageClass = VarDecl::Register;
2520 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002521 Diag(DS.getStorageClassSpecLoc(),
2522 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002523 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002524 }
2525 if (DS.isThreadSpecified()) {
2526 Diag(DS.getThreadSpecLoc(),
2527 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002528 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002529 }
2530
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002531 // Check that there are no default arguments inside the type of this
2532 // parameter (C++ only).
2533 if (getLangOptions().CPlusPlus)
2534 CheckExtraCXXDefaultArguments(D);
2535
Chris Lattner04421082008-04-08 04:40:51 +00002536 // In this context, we *do not* check D.getInvalidType(). If the declarator
2537 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2538 // though it will not reflect the user specified type.
2539 QualType parmDeclType = GetTypeForDeclarator(D, S);
2540
2541 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2542
Reid Spencer5f016e22007-07-11 17:01:13 +00002543 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2544 // Can this happen for params? We already checked that they don't conflict
2545 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002546 IdentifierInfo *II = D.getIdentifier();
Chris Lattnercf79b012009-01-21 02:38:50 +00002547 if (II) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002548 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00002549 if (PrevDecl->isTemplateParameter()) {
2550 // Maybe we will complain about the shadowed template parameter.
2551 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2552 // Just pretend that we didn't see the previous declaration.
2553 PrevDecl = 0;
2554 } else if (S->isDeclScope(PrevDecl)) {
2555 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002556
Chris Lattnercf79b012009-01-21 02:38:50 +00002557 // Recover by removing the name
2558 II = 0;
2559 D.SetIdentifier(0, D.getIdentifierLoc());
2560 }
Chris Lattner04421082008-04-08 04:40:51 +00002561 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002562 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002563
2564 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2565 // Doing the promotion here has a win and a loss. The win is the type for
2566 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2567 // code generator). The loss is the orginal type isn't preserved. For example:
2568 //
2569 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2570 // int blockvardecl[5];
2571 // sizeof(parmvardecl); // size == 4
2572 // sizeof(blockvardecl); // size == 20
2573 // }
2574 //
2575 // For expressions, all implicit conversions are captured using the
2576 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2577 //
2578 // FIXME: If a source translation tool needs to see the original type, then
2579 // we need to consider storing both types (in ParmVarDecl)...
2580 //
Chris Lattnere6327742008-04-02 05:18:44 +00002581 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002582 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002583 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002584 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002585 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002586
Chris Lattner04421082008-04-08 04:40:51 +00002587 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2588 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002589 parmDeclType, StorageClass,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002590 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002591
Chris Lattner04421082008-04-08 04:40:51 +00002592 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002593 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002594
Douglas Gregor584049d2008-12-15 23:53:10 +00002595 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2596 if (D.getCXXScopeSpec().isSet()) {
2597 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2598 << D.getCXXScopeSpec().getRange();
2599 New->setInvalidDecl();
2600 }
2601
Douglas Gregor44b43212008-12-11 16:49:14 +00002602 // Add the parameter declaration into this scope.
2603 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002604 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002605 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002606
Chris Lattner3ff30c82008-06-29 00:02:00 +00002607 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002608 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002609
Reid Spencer5f016e22007-07-11 17:01:13 +00002610}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002611
Douglas Gregorbe109b32009-01-23 16:23:13 +00002612void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002613 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2614 "Not a function declarator!");
2615 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002616
Reid Spencer5f016e22007-07-11 17:01:13 +00002617 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2618 // for a K&R function.
2619 if (!FTI.hasPrototype) {
2620 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002621 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002622 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2623 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002624 // Implicitly declare the argument as type 'int' for lack of a better
2625 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002626 DeclSpec DS;
2627 const char* PrevSpec; // unused
2628 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2629 PrevSpec);
2630 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2631 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00002632 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002633 }
2634 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00002635 }
2636}
2637
2638Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2639 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2640 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2641 "Not a function declarator!");
2642 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2643
2644 if (FTI.hasPrototype) {
Chris Lattner04421082008-04-08 04:40:51 +00002645 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002646 }
2647
Douglas Gregor584049d2008-12-15 23:53:10 +00002648 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002649
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002650 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002651 ActOnDeclarator(ParentScope, D, 0,
2652 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002653}
2654
2655Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2656 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002657 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002658
2659 // See if this is a redefinition.
2660 const FunctionDecl *Definition;
2661 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002662 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002663 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002664 }
2665
Douglas Gregor44b43212008-12-11 16:49:14 +00002666 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002667
Chris Lattner04421082008-04-08 04:40:51 +00002668 // Check the validity of our function parameters
2669 CheckParmsForFunctionDef(FD);
2670
2671 // Introduce our parameters into the function scope
2672 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2673 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00002674 Param->setOwningFunction(FD);
2675
Chris Lattner04421082008-04-08 04:40:51 +00002676 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002677 if (Param->getIdentifier())
2678 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002679 }
Chris Lattner04421082008-04-08 04:40:51 +00002680
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002681 // Checking attributes of current function definition
2682 // dllimport attribute.
2683 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2684 // dllimport attribute cannot be applied to definition.
2685 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2686 Diag(FD->getLocation(),
2687 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2688 << "dllimport";
2689 FD->setInvalidDecl();
2690 return FD;
2691 } else {
2692 // If a symbol previously declared dllimport is later defined, the
2693 // attribute is ignored in subsequent references, and a warning is
2694 // emitted.
2695 Diag(FD->getLocation(),
2696 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2697 << FD->getNameAsCString() << "dllimport";
2698 }
2699 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002700 return FD;
2701}
2702
Sebastian Redl798d1192008-12-13 16:23:55 +00002703Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002704 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002705 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002706 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002707 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002708 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002709 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002710 MD->setBody((Stmt*)Body);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002711 } else {
2712 Body->Destroy(Context);
Steve Naroff394f3f42008-07-25 17:57:26 +00002713 return 0;
Ted Kremenek8189cde2009-02-07 01:47:29 +00002714 }
Chris Lattnerb048c982008-04-06 04:47:34 +00002715 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002716 // Verify and clean out per-function state.
2717
2718 // Check goto/label use.
2719 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2720 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2721 // Verify that we have no forward references left. If so, there was a goto
2722 // or address of a label taken, but no definition of it. Label fwd
2723 // definitions are indicated with a null substmt.
2724 if (I->second->getSubStmt() == 0) {
2725 LabelStmt *L = I->second;
2726 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002727 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002728
2729 // At this point, we have gotos that use the bogus label. Stitch it into
2730 // the function body so that they aren't leaked and that the AST is well
2731 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002732 if (Body) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00002733#if 0
2734 // FIXME: Why do this? Having a 'push_back' in CompoundStmt is ugly,
2735 // and the AST is malformed anyway. We should just blow away 'L'.
2736 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
2737 cast<CompoundStmt>(Body)->push_back(L);
2738#else
2739 L->Destroy(Context);
2740#endif
Chris Lattner0cbc2152008-01-25 00:01:10 +00002741 } else {
2742 // The whole function wasn't parsed correctly, just delete this.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002743 L->Destroy(Context);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002744 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002745 }
2746 }
2747 LabelMap.clear();
2748
Steve Naroffd6d054d2007-11-11 23:20:51 +00002749 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002750}
2751
Reid Spencer5f016e22007-07-11 17:01:13 +00002752/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2753/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002754NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2755 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002756 // Extension in C99. Legal in C90, but warn about it.
2757 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002758 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002759 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002760 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002761
2762 // FIXME: handle stuff like:
2763 // void foo() { extern float X(); }
2764 // void bar() { X(); } <-- implicit decl for X in another scope.
2765
2766 // Set a Declarator for the implicit definition: int foo();
2767 const char *Dummy;
2768 DeclSpec DS;
2769 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2770 Error = Error; // Silence warning.
2771 assert(!Error && "Error setting up implicit decl!");
2772 Declarator D(DS, Declarator::BlockContext);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002773 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc, D),
2774 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002775 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002776
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002777 // Insert this function into translation-unit scope.
2778
2779 DeclContext *PrevDC = CurContext;
2780 CurContext = Context.getTranslationUnitDecl();
2781
Steve Naroffe2ef8152008-04-04 14:32:09 +00002782 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002783 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002784 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002785
2786 CurContext = PrevDC;
2787
Steve Naroffe2ef8152008-04-04 14:32:09 +00002788 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002789}
2790
2791
Chris Lattner41af0932007-11-14 06:34:38 +00002792TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002793 Decl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002794 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002795 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002796
2797 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002798 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2799 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002800 D.getIdentifier(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002801 T);
2802 NewTD->setNextDeclarator(LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002803 if (D.getInvalidType())
2804 NewTD->setInvalidDecl();
2805 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002806}
2807
Steve Naroff08d92e42007-09-15 18:49:24 +00002808/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002809/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002810/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +00002811/// reference/declaration/definition of a tag.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002812Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002813 SourceLocation KWLoc, const CXXScopeSpec &SS,
2814 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorddc29e12009-02-06 22:42:48 +00002815 AttributeList *Attr) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002816 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002817 assert((Name != 0 || TK == TK_Definition) &&
2818 "Nameless record must be a definition!");
Douglas Gregoraaba5e32009-02-04 19:02:06 +00002819
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002820 TagDecl::TagKind Kind;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002821 switch (TagSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002822 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002823 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2824 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2825 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2826 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002827 }
2828
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002829 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002830 DeclContext *DC = CurContext;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002831 NamedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002832
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002833 bool Invalid = false;
2834
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002835 if (Name && SS.isNotEmpty()) {
2836 // We have a nested-name tag ('struct foo::bar').
2837
2838 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002839 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002840 Name = 0;
2841 goto CreateNewDecl;
2842 }
2843
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002844 DC = static_cast<DeclContext*>(SS.getScopeRep());
Douglas Gregor1931b442009-02-03 00:34:39 +00002845 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002846 // Look-up name inside 'foo::'.
Steve Naroff3e8ffd22009-01-29 00:07:50 +00002847 PrevDecl = dyn_cast_or_null<TagDecl>(
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002848 LookupQualifiedName(DC, Name, LookupTagName, true).getAsDecl());
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002849
2850 // A tag 'foo::bar' must already exist.
2851 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002852 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002853 Name = 0;
2854 goto CreateNewDecl;
2855 }
Chris Lattnercf79b012009-01-21 02:38:50 +00002856 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002857 // If this is a named struct, check to see if there was a previous forward
2858 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002859 // FIXME: We're looking into outer scopes here, even when we
2860 // shouldn't be. Doing so can result in ambiguities that we
2861 // shouldn't be diagnosing.
Douglas Gregore2c565d2009-02-03 19:26:08 +00002862 LookupResult R = LookupName(S, Name, LookupTagName,
2863 /*RedeclarationOnly=*/(TK != TK_Reference));
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002864 if (R.isAmbiguous()) {
2865 DiagnoseAmbiguousLookup(R, Name, NameLoc);
2866 // FIXME: This is not best way to recover from case like:
2867 //
2868 // struct S s;
2869 //
2870 // causes needless err_ovl_no_viable_function_in_init latter.
2871 Name = 0;
2872 PrevDecl = 0;
2873 Invalid = true;
2874 }
2875 else
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002876 PrevDecl = R;
Douglas Gregor72de6672009-01-08 20:45:30 +00002877
2878 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2879 // FIXME: This makes sure that we ignore the contexts associated
2880 // with C structs, unions, and enums when looking for a matching
2881 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +00002882 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002883 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2884 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +00002885 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002886 }
2887
Douglas Gregorf57172b2008-12-08 18:40:42 +00002888 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002889 // Maybe we will complain about the shadowed template parameter.
2890 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2891 // Just pretend that we didn't see the previous declaration.
2892 PrevDecl = 0;
2893 }
2894
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002895 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002896 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002897 // If this is a use of a previous tag, or if the tag is already declared
2898 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002899 // rementions the tag), reuse the decl.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002900 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002901 // Make sure that this wasn't declared as an enum and now used as a
2902 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002903 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002904 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002905 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002906 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002907 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002908 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002909 Invalid = true;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002910 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002911 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002912
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002913 // FIXME: In the future, return a variant or some other clue
2914 // for the consumer of this Decl to know it doesn't own it.
2915 // For our current ASTs this shouldn't be a problem, but will
2916 // need to be changed with DeclGroups.
2917 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002918 return PrevDecl;
Douglas Gregoraaba5e32009-02-04 19:02:06 +00002919
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002920 // Diagnose attempts to redefine a tag.
2921 if (TK == TK_Definition) {
2922 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2923 Diag(NameLoc, diag::err_redefinition) << Name;
2924 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002925 // If this is a redefinition, recover by making this
2926 // struct be anonymous, which will make any later
2927 // references get the previous definition.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002928 Name = 0;
2929 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002930 Invalid = true;
2931 } else {
2932 // If the type is currently being defined, complain
2933 // about a nested redefinition.
2934 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
2935 if (Tag->isBeingDefined()) {
2936 Diag(NameLoc, diag::err_nested_redefinition) << Name;
2937 Diag(PrevTagDecl->getLocation(),
2938 diag::note_previous_definition);
2939 Name = 0;
2940 PrevDecl = 0;
2941 Invalid = true;
2942 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002943 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002944
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002945 // Okay, this is definition of a previously declared or referenced
2946 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002947 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002948 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002949 // If we get here we have (another) forward declaration or we
2950 // have a definition. Just create a new decl.
2951 } else {
2952 // If we get here, this is a definition of a new tag type in a nested
2953 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2954 // new decl/type. We set PrevDecl to NULL so that the entities
2955 // have distinct types.
2956 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002957 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002958 // If we get here, we're going to create a new Decl. If PrevDecl
2959 // is non-NULL, it's a definition of the tag declared by
2960 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002961 } else {
Douglas Gregor66973122009-01-28 17:15:10 +00002962 // PrevDecl is a namespace, template, or anything else
2963 // that lives in the IDNS_Tag identifier namespace.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002964 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002965 // The tag name clashes with a namespace name, issue an error and
2966 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002967 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002968 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002969 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002970 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002971 Invalid = true;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002972 } else {
2973 // The existing declaration isn't relevant to us; we're in a
2974 // new scope, so clear out the previous declaration.
2975 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002976 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002977 }
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002978 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
2979 (Kind != TagDecl::TK_enum)) {
2980 // C++ [basic.scope.pdecl]p5:
2981 // -- for an elaborated-type-specifier of the form
2982 //
2983 // class-key identifier
2984 //
2985 // if the elaborated-type-specifier is used in the
2986 // decl-specifier-seq or parameter-declaration-clause of a
2987 // function defined in namespace scope, the identifier is
2988 // declared as a class-name in the namespace that contains
2989 // the declaration; otherwise, except as a friend
2990 // declaration, the identifier is declared in the smallest
2991 // non-class, non-function-prototype scope that contains the
2992 // declaration.
2993 //
2994 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
2995 // C structs and unions.
2996
2997 // Find the context where we'll be declaring the tag.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002998 // FIXME: We would like to maintain the current DeclContext as the
2999 // lexical context,
Douglas Gregor1931b442009-02-03 00:34:39 +00003000 while (SearchDC->isRecord())
3001 SearchDC = SearchDC->getParent();
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003002
3003 // Find the scope where we'll be declaring the tag.
3004 while (S->isClassScope() ||
3005 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003006 ((S->getFlags() & Scope::DeclScope) == 0) ||
3007 (S->getEntity() &&
3008 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003009 S = S->getParent();
Reid Spencer5f016e22007-07-11 17:01:13 +00003010 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00003011
Chris Lattnercc98eac2008-12-17 07:13:27 +00003012CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00003013
3014 // If there is an identifier, use the location of the identifier as the
3015 // location of the decl, otherwise use the location of the struct/union
3016 // keyword.
3017 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3018
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003019 // Otherwise, create a new declaration. If there is a previous
3020 // declaration of the same entity, the two will be linked via
3021 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00003022 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003023
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003024 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003025 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3026 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor1931b442009-02-03 00:34:39 +00003027 New = EnumDecl::Create(Context, SearchDC, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003028 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003029 // If this is an undefined enum, warn.
3030 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003031 } else {
3032 // struct/union/class
3033
Reid Spencer5f016e22007-07-11 17:01:13 +00003034 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3035 // struct X { int A; } D; D should chain to X.
Douglas Gregorddc29e12009-02-06 22:42:48 +00003036 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00003037 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor1931b442009-02-03 00:34:39 +00003038 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003039 cast_or_null<CXXRecordDecl>(PrevDecl));
Douglas Gregorddc29e12009-02-06 22:42:48 +00003040 else
Douglas Gregor1931b442009-02-03 00:34:39 +00003041 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003042 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003043 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003044
3045 if (Kind != TagDecl::TK_enum) {
3046 // Handle #pragma pack: if the #pragma pack stack has non-default
3047 // alignment, make up a packed attribute for this decl. These
3048 // attributes are checked when the ASTContext lays out the
3049 // structure.
3050 //
3051 // It is important for implementing the correct semantics that this
3052 // happen here (in act on tag decl). The #pragma pack stack is
3053 // maintained as a result of parser callbacks which can occur at
3054 // many points during the parsing of a struct declaration (because
3055 // the #pragma tokens are effectively skipped over during the
3056 // parsing of the struct).
3057 if (unsigned Alignment = PackContext.getAlignment())
3058 New->addAttr(new PackedAttr(Alignment * 8));
3059 }
3060
Douglas Gregor66973122009-01-28 17:15:10 +00003061 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
3062 // C++ [dcl.typedef]p3:
3063 // [...] Similarly, in a given scope, a class or enumeration
3064 // shall not be declared with the same name as a typedef-name
3065 // that is declared in that scope and refers to a type other
3066 // than the class or enumeration itself.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00003067 LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true);
Douglas Gregor66973122009-01-28 17:15:10 +00003068 TypedefDecl *PrevTypedef = 0;
3069 if (Lookup.getKind() == LookupResult::Found)
3070 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
3071
3072 if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
3073 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
3074 Context.getCanonicalType(Context.getTypeDeclType(New))) {
3075 Diag(Loc, diag::err_tag_definition_of_typedef)
3076 << Context.getTypeDeclType(New)
3077 << PrevTypedef->getUnderlyingType();
3078 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
3079 Invalid = true;
3080 }
3081 }
3082
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003083 if (Invalid)
3084 New->setInvalidDecl();
3085
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003086 if (Attr)
3087 ProcessDeclAttributeList(New, Attr);
3088
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003089 // If we're declaring or defining a tag in function prototype scope
3090 // in C, note that this type can only be used within the function.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003091 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3092 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3093
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003094 // Set the lexical context. If the tag has a C++ scope specifier, the
3095 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +00003096 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003097
3098 if (TK == TK_Definition)
3099 New->startDefinition();
Reid Spencer5f016e22007-07-11 17:01:13 +00003100
3101 // If this has an identifier, add it to the scope stack.
3102 if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003103 S = getNonFieldDeclScope(S);
Douglas Gregor1931b442009-02-03 00:34:39 +00003104 PushOnScopeChains(New, S);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003105 } else {
Douglas Gregor1931b442009-02-03 00:34:39 +00003106 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00003107 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00003108
Reid Spencer5f016e22007-07-11 17:01:13 +00003109 return New;
3110}
3111
Douglas Gregor72de6672009-01-08 20:45:30 +00003112void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +00003113 AdjustDeclIfTemplate(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +00003114 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3115
3116 // Enter the tag context.
3117 PushDeclContext(S, Tag);
3118
3119 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3120 FieldCollector->StartClass();
3121
3122 if (Record->getIdentifier()) {
3123 // C++ [class]p2:
3124 // [...] The class-name is also inserted into the scope of the
3125 // class itself; this is known as the injected-class-name. For
3126 // purposes of access checking, the injected-class-name is treated
3127 // as if it were a public member name.
3128 RecordDecl *InjectedClassName
3129 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3130 CurContext, Record->getLocation(),
3131 Record->getIdentifier(), Record);
3132 InjectedClassName->setImplicit();
3133 PushOnScopeChains(InjectedClassName, S);
3134 }
3135 }
3136}
3137
3138void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +00003139 AdjustDeclIfTemplate(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +00003140 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3141
3142 if (isa<CXXRecordDecl>(Tag))
3143 FieldCollector->FinishClass();
3144
3145 // Exit this scope of this tag's definition.
3146 PopDeclContext();
3147
3148 // Notify the consumer that we've defined a tag.
3149 Consumer.HandleTagDeclDefinition(Tag);
3150}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00003151
Chris Lattner1d353ba2008-11-12 21:17:48 +00003152/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3153/// types into constant array types in certain situations which would otherwise
3154/// be errors (for GCC compatibility).
3155static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3156 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00003157 // This method tries to turn a variable array into a constant
3158 // array even when the size isn't an ICE. This is necessary
3159 // for compatibility with code that depends on gcc's buggy
3160 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00003161 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3162 if (!VLATy) return QualType();
3163
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003164 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00003165 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003166 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00003167 return QualType();
3168
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003169 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3170 llvm::APSInt &Res = EvalResult.Val.getInt();
Nuno Lopes1dfa6e12009-02-02 22:32:08 +00003171 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3172 return Context.getConstantArrayType(VLATy->getElementType(),
3173 Res, ArrayType::Normal, 0);
3174 return QualType();
Eli Friedman1b76ada2008-06-03 21:01:11 +00003175}
3176
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003177bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00003178 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003179 // FIXME: 6.7.2.1p4 - verify the field type.
3180
3181 llvm::APSInt Value;
3182 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3183 return true;
3184
Chris Lattnercd087072008-12-12 04:56:04 +00003185 // Zero-width bitfield is ok for anonymous field.
3186 if (Value == 0 && FieldName)
3187 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3188
3189 if (Value.isNegative())
3190 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003191
3192 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3193 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00003194 if (TypeSize && Value.getZExtValue() > TypeSize)
3195 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3196 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003197
3198 return false;
3199}
3200
Steve Naroff08d92e42007-09-15 18:49:24 +00003201/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00003202/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00003203Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00003204 SourceLocation DeclStart,
3205 Declarator &D, ExprTy *BitfieldWidth) {
3206 IdentifierInfo *II = D.getIdentifier();
3207 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00003208 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00003209 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003210 if (II) Loc = D.getIdentifierLoc();
3211
3212 // FIXME: Unnamed fields can be handled in various different ways, for
3213 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00003214
Reid Spencer5f016e22007-07-11 17:01:13 +00003215 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00003216 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3217 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00003218
Reid Spencer5f016e22007-07-11 17:01:13 +00003219 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3220 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00003221 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00003222 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003223 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003224 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003225 T = FixedTy;
3226 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003227 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00003228 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00003229 InvalidDecl = true;
3230 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003231 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003232
3233 if (BitWidth) {
3234 if (VerifyBitField(Loc, II, T, BitWidth))
3235 InvalidDecl = true;
3236 } else {
3237 // Not a bitfield.
3238
3239 // validate II.
3240
3241 }
3242
Reid Spencer5f016e22007-07-11 17:01:13 +00003243 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003244 FieldDecl *NewFD;
3245
Douglas Gregor44b43212008-12-11 16:49:14 +00003246 NewFD = FieldDecl::Create(Context, Record,
3247 Loc, II, T, BitWidth,
3248 D.getDeclSpec().getStorageClassSpec() ==
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003249 DeclSpec::SCS_mutable);
Douglas Gregor44b43212008-12-11 16:49:14 +00003250
Douglas Gregor72de6672009-01-08 20:45:30 +00003251 if (II) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003252 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregor72de6672009-01-08 20:45:30 +00003253 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3254 && !isa<TagDecl>(PrevDecl)) {
3255 Diag(Loc, diag::err_duplicate_member) << II;
3256 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3257 NewFD->setInvalidDecl();
3258 Record->setInvalidDecl();
3259 }
3260 }
3261
Sebastian Redl64b45f72009-01-05 20:52:13 +00003262 if (getLangOptions().CPlusPlus) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003263 CheckExtraCXXDefaultArguments(D);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003264 if (!T->isPODType())
3265 cast<CXXRecordDecl>(Record)->setPOD(false);
3266 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003267
Chris Lattner3ff30c82008-06-29 00:02:00 +00003268 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00003269
Steve Naroff5912a352007-08-28 20:14:24 +00003270 if (D.getInvalidType() || InvalidDecl)
3271 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003272
Douglas Gregor72de6672009-01-08 20:45:30 +00003273 if (II) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003274 PushOnScopeChains(NewFD, S);
Douglas Gregor72de6672009-01-08 20:45:30 +00003275 } else
Douglas Gregor482b77d2009-01-12 23:27:07 +00003276 Record->addDecl(NewFD);
Douglas Gregor44b43212008-12-11 16:49:14 +00003277
Steve Naroff5912a352007-08-28 20:14:24 +00003278 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003279}
3280
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003281/// TranslateIvarVisibility - Translate visibility from a token ID to an
3282/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003283static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003284TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00003285 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00003286 default: assert(0 && "Unknown visitibility kind");
3287 case tok::objc_private: return ObjCIvarDecl::Private;
3288 case tok::objc_public: return ObjCIvarDecl::Public;
3289 case tok::objc_protected: return ObjCIvarDecl::Protected;
3290 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00003291 }
3292}
3293
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003294/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3295/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003296Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003297 SourceLocation DeclStart,
3298 Declarator &D, ExprTy *BitfieldWidth,
3299 tok::ObjCKeywordKind Visibility) {
Douglas Gregor72de6672009-01-08 20:45:30 +00003300
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003301 IdentifierInfo *II = D.getIdentifier();
3302 Expr *BitWidth = (Expr*)BitfieldWidth;
3303 SourceLocation Loc = DeclStart;
3304 if (II) Loc = D.getIdentifierLoc();
3305
3306 // FIXME: Unnamed fields can be handled in various different ways, for
3307 // example, unnamed unions inject all members into the struct namespace!
3308
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003309 QualType T = GetTypeForDeclarator(D, S);
3310 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3311 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003312
3313 if (BitWidth) {
3314 // TODO: Validate.
3315 //printf("WARNING: BITFIELDS IGNORED!\n");
3316
3317 // 6.7.2.1p3
3318 // 6.7.2.1p4
3319
3320 } else {
3321 // Not a bitfield.
3322
3323 // validate II.
3324
3325 }
3326
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003327 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3328 // than a variably modified type.
3329 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00003330 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003331 InvalidDecl = true;
3332 }
3333
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003334 // Get the visibility (access control) for this ivar.
3335 ObjCIvarDecl::AccessControl ac =
3336 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3337 : ObjCIvarDecl::None;
3338
3339 // Construct the decl.
3340 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00003341 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003342
Douglas Gregor72de6672009-01-08 20:45:30 +00003343 if (II) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003344 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregor72de6672009-01-08 20:45:30 +00003345 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3346 && !isa<TagDecl>(PrevDecl)) {
3347 Diag(Loc, diag::err_duplicate_member) << II;
3348 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3349 NewID->setInvalidDecl();
3350 }
3351 }
3352
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003353 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00003354 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003355
3356 if (D.getInvalidType() || InvalidDecl)
3357 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003358
Douglas Gregor72de6672009-01-08 20:45:30 +00003359 if (II) {
3360 // FIXME: When interfaces are DeclContexts, we'll need to add
3361 // these to the interface.
3362 S->AddDecl(NewID);
3363 IdResolver.AddDecl(NewID);
3364 }
3365
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003366 return NewID;
3367}
3368
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00003369void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003370 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00003371 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00003372 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00003373 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00003374 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3375 assert(EnclosingDecl && "missing record or interface decl");
3376 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3377
Reid Spencer5f016e22007-07-11 17:01:13 +00003378 // Verify that all the fields are okay.
3379 unsigned NumNamedMembers = 0;
3380 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003381
Reid Spencer5f016e22007-07-11 17:01:13 +00003382 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff74216642007-09-14 22:20:54 +00003383 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3384 assert(FD && "missing field decl");
3385
Reid Spencer5f016e22007-07-11 17:01:13 +00003386 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003387 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003388
Douglas Gregor72de6672009-01-08 20:45:30 +00003389 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003390 // Remember all fields written by the user.
3391 RecFields.push_back(FD);
3392 }
Steve Narofff13271f2007-09-14 23:09:53 +00003393
Reid Spencer5f016e22007-07-11 17:01:13 +00003394 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003395 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003396 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003397 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003398 FD->setInvalidDecl();
3399 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003400 continue;
3401 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003402 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3403 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003404 if (!Record) { // Incomplete ivar type is always an error.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003405 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3406 diag::err_field_incomplete);
Steve Naroff74216642007-09-14 22:20:54 +00003407 FD->setInvalidDecl();
3408 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003409 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003410 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003411 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003412 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003413 !FDTy->isArrayType()) { //... may have incomplete array type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003414 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3415 diag::err_field_incomplete);
Steve Naroff74216642007-09-14 22:20:54 +00003416 FD->setInvalidDecl();
3417 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003418 continue;
3419 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003420 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003421 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003422 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003423 FD->setInvalidDecl();
3424 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003425 continue;
3426 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003427 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003428 if (Record)
3429 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003430 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003431 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3432 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003433 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003434 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3435 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003436 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003437 Record->setHasFlexibleArrayMember(true);
3438 } else {
3439 // If this is a struct/class and this is not the last element, reject
3440 // it. Note that GCC supports variable sized arrays in the middle of
3441 // structures.
3442 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003443 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003444 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003445 FD->setInvalidDecl();
3446 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003447 continue;
3448 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003449 // We support flexible arrays at the end of structs in other structs
3450 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003451 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003452 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003453 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003454 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003455 }
3456 }
3457 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003458 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003459 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003460 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003461 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003462 FD->setInvalidDecl();
3463 EnclosingDecl->setInvalidDecl();
3464 continue;
3465 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003466 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00003467 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00003468 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003469 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003470
Reid Spencer5f016e22007-07-11 17:01:13 +00003471 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003472 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003473 Record->completeDefinition(Context);
Chris Lattnere1e79852008-02-06 00:51:33 +00003474 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003475 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003476 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003477 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003478 // Must enforce the rule that ivars in the base classes may not be
3479 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003480 if (ID->getSuperClass()) {
3481 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3482 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3483 ObjCIvarDecl* Ivar = (*IVI);
3484 IdentifierInfo *II = Ivar->getIdentifier();
3485 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3486 if (prevIvar) {
3487 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregor72de6672009-01-08 20:45:30 +00003488 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003489 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003490 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003491 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003492 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003493 else if (ObjCImplementationDecl *IMPDecl =
3494 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003495 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3496 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003497 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003498 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003499 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003500
3501 if (Attr)
3502 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003503}
3504
Steve Naroff08d92e42007-09-15 18:49:24 +00003505Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003506 DeclTy *lastEnumConst,
3507 SourceLocation IdLoc, IdentifierInfo *Id,
3508 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003509 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003510 EnumConstantDecl *LastEnumConst =
3511 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3512 Expr *Val = static_cast<Expr*>(val);
3513
Chris Lattner31e05722007-08-26 06:24:45 +00003514 // The scope passed in may not be a decl scope. Zip up the scope tree until
3515 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003516 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003517
Reid Spencer5f016e22007-07-11 17:01:13 +00003518 // Verify that there isn't already something declared with this name in this
3519 // scope.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003520 NamedDecl *PrevDecl = LookupName(S, Id, LookupOrdinaryName);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003521 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003522 // Maybe we will complain about the shadowed template parameter.
3523 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3524 // Just pretend that we didn't see the previous declaration.
3525 PrevDecl = 0;
3526 }
3527
3528 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003529 // When in C++, we may get a TagDecl with the same name; in this case the
3530 // enum constant will 'hide' the tag.
3531 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3532 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003533 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003534 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003535 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003536 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003537 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003538 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003539 Val->Destroy(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00003540 return 0;
3541 }
3542 }
3543
3544 llvm::APSInt EnumVal(32);
3545 QualType EltTy;
3546 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003547 // Make sure to promote the operand type to int.
3548 UsualUnaryConversions(Val);
3549
Reid Spencer5f016e22007-07-11 17:01:13 +00003550 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3551 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003552 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00003553 Val->Destroy(Context);
Chris Lattnerb7416f92007-08-27 17:37:24 +00003554 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003555 } else {
3556 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003557 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003558 }
3559
3560 if (!Val) {
3561 if (LastEnumConst) {
3562 // Assign the last value + 1.
3563 EnumVal = LastEnumConst->getInitVal();
3564 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003565
3566 // Check for overflow on increment.
3567 if (EnumVal < LastEnumConst->getInitVal())
3568 Diag(IdLoc, diag::warn_enum_value_overflow);
3569
Chris Lattnerb7416f92007-08-27 17:37:24 +00003570 EltTy = LastEnumConst->getType();
3571 } else {
3572 // First value, set to zero.
3573 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003574 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003575 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003576 }
3577
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003578 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003579 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003580 Val, EnumVal);
Reid Spencer5f016e22007-07-11 17:01:13 +00003581
3582 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003583 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003584
Reid Spencer5f016e22007-07-11 17:01:13 +00003585 return New;
3586}
3587
Steve Naroff02408c62008-08-07 14:08:16 +00003588// FIXME: For consistency with ActOnFields(), we should have the parser
3589// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003590void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003591 DeclTy **Elements, unsigned NumElements) {
3592 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00003593 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003594
Chris Lattnere37f0be2007-08-28 05:10:31 +00003595 // TODO: If the result value doesn't fit in an int, it must be a long or long
3596 // long value. ISO C does not support this, but GCC does as an extension,
3597 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003598 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003599
Chris Lattnerac609682007-08-28 06:15:15 +00003600 // Verify that all the values are okay, compute the size of the values, and
3601 // reverse the list.
3602 unsigned NumNegativeBits = 0;
3603 unsigned NumPositiveBits = 0;
3604
3605 // Keep track of whether all elements have type int.
3606 bool AllElementsInt = true;
3607
Reid Spencer5f016e22007-07-11 17:01:13 +00003608 for (unsigned i = 0; i != NumElements; ++i) {
3609 EnumConstantDecl *ECD =
3610 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3611 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003612
3613 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003614 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003615 assert(InitVal.getBitWidth() >= IntWidth &&
3616 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003617 if (InitVal.getBitWidth() > IntWidth) {
3618 llvm::APSInt V(InitVal);
3619 V.trunc(IntWidth);
3620 V.extend(InitVal.getBitWidth());
3621 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003622 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3623 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003624 }
Chris Lattnerac609682007-08-28 06:15:15 +00003625
3626 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003627 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003628 NumPositiveBits = std::max(NumPositiveBits,
3629 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003630 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003631 NumNegativeBits = std::max(NumNegativeBits,
3632 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003633
Chris Lattnerac609682007-08-28 06:15:15 +00003634 // Keep track of whether every enum element has type int (very commmon).
3635 if (AllElementsInt)
3636 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003637 }
3638
Chris Lattnerac609682007-08-28 06:15:15 +00003639 // Figure out the type that should be used for this enum.
3640 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3641 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003642 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003643
3644 if (NumNegativeBits) {
3645 // If there is a negative value, figure out the smallest integer type (of
3646 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003647 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003648 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003649 BestWidth = IntWidth;
3650 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003651 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003652
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003653 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003654 BestType = Context.LongTy;
3655 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003656 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003657
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003658 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003659 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3660 BestType = Context.LongLongTy;
3661 }
3662 }
3663 } else {
3664 // If there is no negative value, figure out which of uint, ulong, ulonglong
3665 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003666 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003667 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003668 BestWidth = IntWidth;
3669 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003670 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003671 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003672 } else {
3673 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003674 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003675 "How could an initializer get larger than ULL?");
3676 BestType = Context.UnsignedLongLongTy;
3677 }
3678 }
3679
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003680 // Loop over all of the enumerator constants, changing their types to match
3681 // the type of the enum if needed.
3682 for (unsigned i = 0; i != NumElements; ++i) {
3683 EnumConstantDecl *ECD =
3684 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3685 if (!ECD) continue; // Already issued a diagnostic.
3686
3687 // Standard C says the enumerators have int type, but we allow, as an
3688 // extension, the enumerators to be larger than int size. If each
3689 // enumerator value fits in an int, type it as an int, otherwise type it the
3690 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3691 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003692 if (ECD->getType() == Context.IntTy) {
3693 // Make sure the init value is signed.
3694 llvm::APSInt IV = ECD->getInitVal();
3695 IV.setIsSigned(true);
3696 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003697
3698 if (getLangOptions().CPlusPlus)
3699 // C++ [dcl.enum]p4: Following the closing brace of an
3700 // enum-specifier, each enumerator has the type of its
3701 // enumeration.
3702 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003703 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003704 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003705
3706 // Determine whether the value fits into an int.
3707 llvm::APSInt InitVal = ECD->getInitVal();
3708 bool FitsInInt;
3709 if (InitVal.isUnsigned() || !InitVal.isNegative())
3710 FitsInInt = InitVal.getActiveBits() < IntWidth;
3711 else
3712 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3713
3714 // If it fits into an integer type, force it. Otherwise force it to match
3715 // the enum decl type.
3716 QualType NewTy;
3717 unsigned NewWidth;
3718 bool NewSign;
3719 if (FitsInInt) {
3720 NewTy = Context.IntTy;
3721 NewWidth = IntWidth;
3722 NewSign = true;
3723 } else if (ECD->getType() == BestType) {
3724 // Already the right type!
Douglas Gregorc9467cf2008-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);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003730 continue;
3731 } else {
3732 NewTy = BestType;
3733 NewWidth = BestWidth;
3734 NewSign = BestType->isSignedIntegerType();
3735 }
3736
3737 // Adjust the APSInt value.
3738 InitVal.extOrTrunc(NewWidth);
3739 InitVal.setIsSigned(NewSign);
3740 ECD->setInitVal(InitVal);
3741
3742 // Adjust the Expr initializer and type.
Chris Lattner13fd4162009-01-15 19:19:42 +00003743 if (ECD->getInitExpr())
Ted Kremenek8189cde2009-02-07 01:47:29 +00003744 ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3745 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003746 if (getLangOptions().CPlusPlus)
3747 // C++ [dcl.enum]p4: Following the closing brace of an
3748 // enum-specifier, each enumerator has the type of its
3749 // enumeration.
3750 ECD->setType(EnumType);
3751 else
3752 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003753 }
Chris Lattnerac609682007-08-28 06:15:15 +00003754
Douglas Gregor44b43212008-12-11 16:49:14 +00003755 Enum->completeDefinition(Context, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00003756}
3757
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003758Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003759 ExprArg expr) {
3760 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3761
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003762 return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003763}
3764
Douglas Gregorf44515a2008-12-16 22:23:02 +00003765
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003766void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3767 ExprTy *alignment, SourceLocation PragmaLoc,
3768 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3769 Expr *Alignment = static_cast<Expr *>(alignment);
3770
3771 // If specified then alignment must be a "small" power of two.
3772 unsigned AlignmentVal = 0;
3773 if (Alignment) {
3774 llvm::APSInt Val;
3775 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3776 !Val.isPowerOf2() ||
3777 Val.getZExtValue() > 16) {
3778 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003779 Alignment->Destroy(Context);
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003780 return; // Ignore
3781 }
3782
3783 AlignmentVal = (unsigned) Val.getZExtValue();
3784 }
3785
3786 switch (Kind) {
3787 case Action::PPK_Default: // pack([n])
3788 PackContext.setAlignment(AlignmentVal);
3789 break;
3790
3791 case Action::PPK_Show: // pack(show)
3792 // Show the current alignment, making sure to show the right value
3793 // for the default.
3794 AlignmentVal = PackContext.getAlignment();
3795 // FIXME: This should come from the target.
3796 if (AlignmentVal == 0)
3797 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003798 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003799 break;
3800
3801 case Action::PPK_Push: // pack(push [, id] [, [n])
3802 PackContext.push(Name);
3803 // Set the new alignment if specified.
3804 if (Alignment)
3805 PackContext.setAlignment(AlignmentVal);
3806 break;
3807
3808 case Action::PPK_Pop: // pack(pop [, id] [, n])
3809 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3810 // "#pragma pack(pop, identifier, n) is undefined"
3811 if (Alignment && Name)
3812 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3813
3814 // Do the pop.
3815 if (!PackContext.pop(Name)) {
3816 // If a name was specified then failure indicates the name
3817 // wasn't found. Otherwise failure indicates the stack was
3818 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003819 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3820 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003821
3822 // FIXME: Warn about popping named records as MSVC does.
3823 } else {
3824 // Pop succeeded, set the new alignment if specified.
3825 if (Alignment)
3826 PackContext.setAlignment(AlignmentVal);
3827 }
3828 break;
3829
3830 default:
3831 assert(0 && "Invalid #pragma pack kind.");
3832 }
3833}
3834
3835bool PragmaPackStack::pop(IdentifierInfo *Name) {
3836 if (Stack.empty())
3837 return false;
3838
3839 // If name is empty just pop top.
3840 if (!Name) {
3841 Alignment = Stack.back().first;
3842 Stack.pop_back();
3843 return true;
3844 }
3845
3846 // Otherwise, find the named record.
3847 for (unsigned i = Stack.size(); i != 0; ) {
3848 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003849 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003850 // Found it, pop up to and including this record.
3851 Alignment = Stack[i].first;
3852 Stack.erase(Stack.begin() + i, Stack.end());
3853 return true;
3854 }
3855 }
3856
3857 return false;
3858}