blob: 373296fb58e996b6a7fbc5531fc541bdc1f9aed3 [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>
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32
Douglas Gregord6efafa2009-02-04 19:16:12 +000033/// \brief If the identifier refers to a type name within this scope,
34/// return the declaration of that type.
35///
36/// This routine performs ordinary name lookup of the identifier II
37/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000038/// determine whether the name refers to a type. If so, returns an
39/// opaque pointer (actually a QualType) corresponding to that
40/// type. Otherwise, returns NULL.
Douglas Gregord6efafa2009-02-04 19:16:12 +000041///
42/// If name lookup results in an ambiguity, this routine will complain
43/// and then return NULL.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000044Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
Douglas Gregorb696ea32009-02-04 17:00:24 +000045 Scope *S, const CXXScopeSpec *SS) {
Chris Lattner22bd9052009-02-16 22:07:16 +000046 NamedDecl *IIDecl = 0;
Douglas Gregor3e41d602009-02-13 23:20:09 +000047 LookupResult Result = LookupParsedName(S, SS, &II, LookupOrdinaryName,
48 false, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +000049 switch (Result.getKind()) {
Chris Lattner22bd9052009-02-16 22:07:16 +000050 case LookupResult::NotFound:
51 case LookupResult::FoundOverloaded:
52 return 0;
Douglas Gregorb696ea32009-02-04 17:00:24 +000053
Chris Lattner22bd9052009-02-16 22:07:16 +000054 case LookupResult::AmbiguousBaseSubobjectTypes:
55 case LookupResult::AmbiguousBaseSubobjects:
56 case LookupResult::AmbiguousReference:
57 DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc);
58 return 0;
Douglas Gregorb696ea32009-02-04 17:00:24 +000059
Chris Lattner22bd9052009-02-16 22:07:16 +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) {
Chris Lattner22bd9052009-02-16 22:07:16 +000066 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000067 // Check whether we can use this type
68 (void)DiagnoseUseOfDecl(IIDecl, NameLoc);
Chris Lattner22bd9052009-02-16 22:07:16 +000069
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000070 return Context.getTypeDeclType(TD).getAsOpaquePtr();
Chris Lattner22bd9052009-02-16 22:07:16 +000071 }
72
73 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000074 // Check whether we can use this interface.
75 (void)DiagnoseUseOfDecl(IIDecl, NameLoc);
Chris Lattner22bd9052009-02-16 22:07:16 +000076
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000077 return Context.getObjCInterfaceType(IDecl).getAsOpaquePtr();
Chris Lattner22bd9052009-02-16 22:07:16 +000078 }
79
80 // Otherwise, could be a variable, function etc.
Steve Naroffa5189032009-01-29 18:09:31 +000081 }
Steve Naroff3536b442007-09-06 21:24:23 +000082 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000083}
84
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000085DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000086 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000087 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000088 if (MD->isOutOfLineDefinition())
89 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000090
Chris Lattner76a642f2009-02-15 22:43:40 +000091 // A C++ inline method is parsed *after* the topmost class it was declared
92 // in is fully parsed (it's "complete").
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000093 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000094 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000095 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
96 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000097 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000098 DC = RD;
99
100 // Return the declaration context of the topmost class the inline method is
101 // declared in.
102 return DC;
103 }
104
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +0000105 if (isa<ObjCMethodDecl>(DC))
106 return Context.getTranslationUnitDecl();
107
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000108 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000109}
110
Douglas Gregor44b43212008-12-11 16:49:14 +0000111void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000112 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +0000113 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +0000114 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +0000115 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000116}
117
Chris Lattnerb048c982008-04-06 04:47:34 +0000118void Sema::PopDeclContext() {
119 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +0000120
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000121 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000122}
123
Douglas Gregorf9201e02009-02-11 23:02:49 +0000124/// \brief Determine whether we allow overloading of the function
125/// PrevDecl with another declaration.
126///
127/// This routine determines whether overloading is possible, not
128/// whether some new function is actually an overload. It will return
129/// true in C++ (where we can always provide overloads) or, as an
130/// extension, in C when the previous function is already an
131/// overloaded function declaration or has the "overloadable"
132/// attribute.
133static bool AllowOverloadingOfFunction(Decl *PrevDecl, ASTContext &Context) {
134 if (Context.getLangOptions().CPlusPlus)
135 return true;
136
137 if (isa<OverloadedFunctionDecl>(PrevDecl))
138 return true;
139
140 return PrevDecl->getAttr<OverloadableAttr>() != 0;
141}
142
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000143/// Add this decl to the scope shadowed decl chains.
144void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000145 // Move up the scope chain until we find the nearest enclosing
146 // non-transparent context. The declaration will be introduced into this
147 // scope.
148 while (S->getEntity() &&
149 ((DeclContext *)S->getEntity())->isTransparentContext())
150 S = S->getParent();
151
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000152 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000153
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000154 // Add scoped declarations into their context, so that they can be
155 // found later. Declarations without a context won't be inserted
156 // into any context.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000157 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000158
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000159 // C++ [basic.scope]p4:
160 // -- exactly one declaration shall declare a class name or
161 // enumeration name that is not a typedef name and the other
162 // declarations shall all refer to the same object or
163 // enumerator, or all refer to functions and function templates;
164 // in this case the class name or enumeration name is hidden.
165 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
166 // We are pushing the name of a tag (enum or class).
Douglas Gregore21b9942009-01-07 16:34:42 +0000167 if (CurContext->getLookupContext()
168 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000169 // We're pushing the tag into the current context, which might
170 // require some reshuffling in the identifier resolver.
171 IdentifierResolver::iterator
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000172 I = IdResolver.begin(TD->getDeclName()),
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000173 IEnd = IdResolver.end();
174 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
175 NamedDecl *PrevDecl = *I;
176 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
177 PrevDecl = *I, ++I) {
178 if (TD->declarationReplaces(*I)) {
179 // This is a redeclaration. Remove it from the chain and
180 // break out, so that we'll add in the shadowed
181 // declaration.
182 S->RemoveDecl(*I);
183 if (PrevDecl == *I) {
184 IdResolver.RemoveDecl(*I);
185 IdResolver.AddDecl(TD);
186 return;
187 } else {
188 IdResolver.RemoveDecl(*I);
189 break;
190 }
191 }
192 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000193
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000194 // There is already a declaration with the same name in the same
195 // scope, which is not a tag declaration. It must be found
196 // before we find the new declaration, so insert the new
197 // declaration at the end of the chain.
198 IdResolver.AddShadowedDecl(TD, PrevDecl);
199
200 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000201 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000202 }
Douglas Gregorf9201e02009-02-11 23:02:49 +0000203 } else if (isa<FunctionDecl>(D) &&
204 AllowOverloadingOfFunction(D, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000205 // We are pushing the name of a function, which might be an
206 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000207 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000208 IdentifierResolver::iterator Redecl
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000209 = std::find_if(IdResolver.begin(FD->getDeclName()),
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000210 IdResolver.end(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000211 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000212 FD));
Douglas Gregor04495c82009-02-24 01:23:02 +0000213 if (Redecl != IdResolver.end() && S->isDeclScope(*Redecl)) {
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000214 // There is already a declaration of a function on our
215 // IdResolver chain. Replace it with this declaration.
216 S->RemoveDecl(*Redecl);
217 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000218 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000219 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000220
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000221 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000222}
223
Steve Naroffb216c882007-10-09 22:01:59 +0000224void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000225 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000226 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
227 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000228
Reid Spencer5f016e22007-07-11 17:01:13 +0000229 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
230 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000231 Decl *TmpD = static_cast<Decl*>(*I);
232 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000233
Douglas Gregor44b43212008-12-11 16:49:14 +0000234 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
235 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000236
Douglas Gregor44b43212008-12-11 16:49:14 +0000237 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000238
Douglas Gregor44b43212008-12-11 16:49:14 +0000239 // Remove this name from our lexical scope.
240 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000241 }
242}
243
Steve Naroffe8043c32008-04-01 23:04:06 +0000244/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
245/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000246ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000247 // The third "scope" argument is 0 since we aren't enabling lazy built-in
248 // creation from this context.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000249 NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000250
Steve Naroffb327ce02008-04-02 14:35:35 +0000251 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000252}
253
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000254/// getNonFieldDeclScope - Retrieves the innermost scope, starting
255/// from S, where a non-field would be declared. This routine copes
256/// with the difference between C and C++ scoping rules in structs and
257/// unions. For example, the following code is well-formed in C but
258/// ill-formed in C++:
259/// @code
260/// struct S6 {
261/// enum { BAR } e;
262/// };
263///
264/// void test_S6() {
265/// struct S6 a;
266/// a.e = BAR;
267/// }
268/// @endcode
269/// For the declaration of BAR, this routine will return a different
270/// scope. The scope S will be the scope of the unnamed enumeration
271/// within S6. In C++, this routine will return the scope associated
272/// with S6, because the enumeration's scope is a transparent
273/// context but structures can contain non-field names. In C, this
274/// routine will return the translation unit scope, since the
275/// enumeration's scope is a transparent context and structures cannot
276/// contain non-field names.
277Scope *Sema::getNonFieldDeclScope(Scope *S) {
278 while (((S->getFlags() & Scope::DeclScope) == 0) ||
279 (S->getEntity() &&
280 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
281 (S->isClassScope() && !getLangOptions().CPlusPlus))
282 S = S->getParent();
283 return S;
284}
285
Chris Lattner95e2c712008-05-05 22:18:14 +0000286void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000287 if (!Context.getBuiltinVaListType().isNull())
288 return;
289
290 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000291 NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
Steve Naroff733002f2007-10-18 22:17:45 +0000292 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000293 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
294}
295
Douglas Gregor3e41d602009-02-13 23:20:09 +0000296/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
297/// file scope. lazily create a decl for it. ForRedeclaration is true
298/// if we're creating this built-in in anticipation of redeclaring the
299/// built-in.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000300NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000301 Scope *S, bool ForRedeclaration,
302 SourceLocation Loc) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 Builtin::ID BID = (Builtin::ID)bid;
304
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000305 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000306 InitBuiltinVaListType();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000307
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000308 Builtin::Context::GetBuiltinTypeError Error;
309 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context, Error);
310 switch (Error) {
311 case Builtin::Context::GE_None:
312 // Okay
313 break;
314
315 case Builtin::Context::GE_Missing_FILE:
316 if (ForRedeclaration)
317 Diag(Loc, diag::err_implicit_decl_requires_stdio)
318 << Context.BuiltinInfo.GetName(BID);
319 return 0;
320 }
Douglas Gregor3e41d602009-02-13 23:20:09 +0000321
322 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
323 Diag(Loc, diag::ext_implicit_lib_function_decl)
324 << Context.BuiltinInfo.GetName(BID)
325 << R;
Douglas Gregorb1152d82009-02-16 21:58:21 +0000326 if (Context.BuiltinInfo.getHeaderName(BID) &&
Douglas Gregor3e41d602009-02-13 23:20:09 +0000327 Diags.getDiagnosticMapping(diag::ext_implicit_lib_function_decl)
328 != diag::MAP_IGNORE)
329 Diag(Loc, diag::note_please_include_header)
330 << Context.BuiltinInfo.getHeaderName(BID)
331 << Context.BuiltinInfo.GetName(BID);
332 }
333
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000334 FunctionDecl *New = FunctionDecl::Create(Context,
335 Context.getTranslationUnitDecl(),
Douglas Gregor3e41d602009-02-13 23:20:09 +0000336 Loc, II, R,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000337 FunctionDecl::Extern, false);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000338 New->setImplicit();
339
Chris Lattner95e2c712008-05-05 22:18:14 +0000340 // Create Decl objects for each parameter, adding them to the
341 // FunctionDecl.
342 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
343 llvm::SmallVector<ParmVarDecl*, 16> Params;
344 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
345 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000346 FT->getArgType(i), VarDecl::None, 0));
Ted Kremenekfc767612009-01-14 00:42:25 +0000347 New->setParams(Context, &Params[0], Params.size());
Chris Lattner95e2c712008-05-05 22:18:14 +0000348 }
349
Douglas Gregor3c385e52009-02-14 18:57:46 +0000350 AddKnownFunctionAttributes(New);
Chris Lattner95e2c712008-05-05 22:18:14 +0000351
Chris Lattner7f925cc2008-04-11 07:00:53 +0000352 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000353 // FIXME: This is hideous. We need to teach PushOnScopeChains to
354 // relate Scopes to DeclContexts, and probably eliminate CurContext
355 // entirely, but we're not there yet.
356 DeclContext *SavedContext = CurContext;
357 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000358 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000359 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 return New;
361}
362
Sebastian Redlc42e1182008-11-11 11:37:55 +0000363/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
364/// everything from the standard library is defined.
365NamespaceDecl *Sema::GetStdNamespace() {
366 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000367 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000368 DeclContext *Global = Context.getTranslationUnitDecl();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000369 Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000370 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
371 }
372 return StdNamespace;
373}
374
Douglas Gregorcda9c672009-02-16 17:45:42 +0000375/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
376/// same name and scope as a previous declaration 'Old'. Figure out
377/// how to resolve this situation, merging decls or emitting
378/// diagnostics as appropriate. Returns true if there was an error,
379/// false otherwise.
Reid Spencer5f016e22007-07-11 17:01:13 +0000380///
Douglas Gregorcda9c672009-02-16 17:45:42 +0000381bool Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000382 bool objc_types = false;
Steve Naroff2b255c42008-09-09 14:32:20 +0000383 // Allow multiple definitions for ObjC built-in typedefs.
384 // FIXME: Verify the underlying types are equivalent!
385 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000386 const IdentifierInfo *TypeID = New->getIdentifier();
387 switch (TypeID->getLength()) {
388 default: break;
389 case 2:
390 if (!TypeID->isStr("id"))
391 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000392 Context.setObjCIdType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000393 objc_types = true;
394 break;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000395 case 5:
396 if (!TypeID->isStr("Class"))
397 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000398 Context.setObjCClassType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000399 objc_types = true;
Douglas Gregorcda9c672009-02-16 17:45:42 +0000400 return false;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000401 case 3:
402 if (!TypeID->isStr("SEL"))
403 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000404 Context.setObjCSelType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000405 objc_types = true;
Douglas Gregorcda9c672009-02-16 17:45:42 +0000406 return false;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000407 case 8:
408 if (!TypeID->isStr("Protocol"))
409 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000410 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000411 objc_types = true;
Douglas Gregorcda9c672009-02-16 17:45:42 +0000412 return false;
Steve Naroff2b255c42008-09-09 14:32:20 +0000413 }
414 // Fall through - the typedef name was not a builtin type.
415 }
Douglas Gregor66973122009-01-28 17:15:10 +0000416 // Verify the old decl was also a type.
417 TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000418 if (!Old) {
Douglas Gregor66973122009-01-28 17:15:10 +0000419 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000420 << New->getDeclName();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000421 if (!objc_types)
422 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000423 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 }
Douglas Gregor66973122009-01-28 17:15:10 +0000425
426 // Determine the "old" type we'll use for checking and diagnostics.
427 QualType OldType;
428 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
429 OldType = OldTypedef->getUnderlyingType();
430 else
431 OldType = Context.getTypeDeclType(Old);
432
Chris Lattner99cb9972008-07-25 18:44:27 +0000433 // If the typedef types are not identical, reject them in all languages and
434 // with any extensions enabled.
Douglas Gregor66973122009-01-28 17:15:10 +0000435
436 if (OldType != New->getUnderlyingType() &&
437 Context.getCanonicalType(OldType) !=
Chris Lattner99cb9972008-07-25 18:44:27 +0000438 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000439 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregor66973122009-01-28 17:15:10 +0000440 << New->getUnderlyingType() << OldType;
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000441 if (!objc_types)
442 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000443 return true;
Chris Lattner99cb9972008-07-25 18:44:27 +0000444 }
Douglas Gregorcda9c672009-02-16 17:45:42 +0000445 if (objc_types) return false;
446 if (getLangOptions().Microsoft) return false;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000447
Douglas Gregorbbe27432008-11-21 16:29:06 +0000448 // C++ [dcl.typedef]p2:
449 // In a given non-class scope, a typedef specifier can be used to
450 // redefine the name of any type declared in that scope to refer
451 // to the type to which it already refers.
452 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
Douglas Gregorcda9c672009-02-16 17:45:42 +0000453 return false;
Douglas Gregorbbe27432008-11-21 16:29:06 +0000454
455 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000456 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
457 // *either* declaration is in a system header. The code below implements
458 // this adhoc compatibility rule. FIXME: The following code will not
459 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000460 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
461 SourceManager &SrcMgr = Context.getSourceManager();
462 if (SrcMgr.isInSystemHeader(Old->getLocation()))
Douglas Gregorcda9c672009-02-16 17:45:42 +0000463 return false;
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000464 if (SrcMgr.isInSystemHeader(New->getLocation()))
Douglas Gregorcda9c672009-02-16 17:45:42 +0000465 return false;
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000466 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000467
Chris Lattner08631c52008-11-23 21:45:46 +0000468 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000469 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000470 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000471}
472
Chris Lattner6b6b5372008-06-26 18:38:35 +0000473/// DeclhasAttr - returns true if decl Declaration already has the target
474/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000475static bool DeclHasAttr(const Decl *decl, const Attr *target) {
476 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
477 if (attr->getKind() == target->getKind())
478 return true;
479
480 return false;
481}
482
483/// MergeAttributes - append attributes from the Old decl to the New one.
484static void MergeAttributes(Decl *New, Decl *Old) {
485 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
486
Chris Lattnerddee4232008-03-03 03:28:21 +0000487 while (attr) {
Douglas Gregorae170942009-02-13 00:26:38 +0000488 tmp = attr;
489 attr = attr->getNext();
Chris Lattnerddee4232008-03-03 03:28:21 +0000490
Douglas Gregorae170942009-02-13 00:26:38 +0000491 if (!DeclHasAttr(New, tmp) && tmp->isMerged()) {
492 tmp->setInherited(true);
493 New->addAttr(tmp);
Chris Lattnerddee4232008-03-03 03:28:21 +0000494 } else {
Douglas Gregorae170942009-02-13 00:26:38 +0000495 tmp->setNext(0);
496 delete(tmp);
Chris Lattnerddee4232008-03-03 03:28:21 +0000497 }
498 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000499
500 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000501}
502
Chris Lattner04421082008-04-08 04:40:51 +0000503/// MergeFunctionDecl - We just parsed a function 'New' from
504/// declarator D which has the same name and scope as a previous
505/// declaration 'Old'. Figure out how to resolve this situation,
506/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000507///
508/// In C++, New and Old must be declarations that are not
509/// overloaded. Use IsOverload to determine whether New and Old are
510/// overloaded, and to select the Old declaration that New should be
511/// merged with.
Douglas Gregorcda9c672009-02-16 17:45:42 +0000512///
513/// Returns true if there was an error, false otherwise.
514bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000515 assert(!isa<OverloadedFunctionDecl>(OldD) &&
516 "Cannot merge with an overloaded function declaration");
517
Reid Spencer5f016e22007-07-11 17:01:13 +0000518 // Verify the old decl was also a function.
519 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
520 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000521 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000522 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000523 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000524 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000525 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000526
527 // Determine whether the previous declaration was a definition,
528 // implicit declaration, or a declaration.
529 diag::kind PrevDiag;
530 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000531 PrevDiag = diag::note_previous_definition;
Douglas Gregorcda9c672009-02-16 17:45:42 +0000532 else if (Old->isImplicit())
533 PrevDiag = diag::note_previous_implicit_declaration;
534 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000535 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000536
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000537 QualType OldQType = Context.getCanonicalType(Old->getType());
538 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000539
Douglas Gregor04495c82009-02-24 01:23:02 +0000540 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
541 New->getStorageClass() == FunctionDecl::Static &&
542 Old->getStorageClass() != FunctionDecl::Static) {
543 Diag(New->getLocation(), diag::err_static_non_static)
544 << New;
545 Diag(Old->getLocation(), PrevDiag);
546 return true;
547 }
548
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000549 if (getLangOptions().CPlusPlus) {
550 // (C++98 13.1p2):
551 // Certain function declarations cannot be overloaded:
552 // -- Function declarations that differ only in the return type
553 // cannot be overloaded.
554 QualType OldReturnType
555 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
556 QualType NewReturnType
557 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
558 if (OldReturnType != NewReturnType) {
559 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000560 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000561 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000562 }
563
564 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
565 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
566 if (OldMethod && NewMethod) {
567 // -- Member function declarations with the same name and the
568 // same parameter types cannot be overloaded if any of them
569 // is a static member function declaration.
570 if (OldMethod->isStatic() || NewMethod->isStatic()) {
571 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000572 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000573 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000574 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000575
576 // C++ [class.mem]p1:
577 // [...] A member shall not be declared twice in the
578 // member-specification, except that a nested class or member
579 // class template can be declared and then later defined.
580 if (OldMethod->getLexicalDeclContext() ==
581 NewMethod->getLexicalDeclContext()) {
582 unsigned NewDiag;
583 if (isa<CXXConstructorDecl>(OldMethod))
584 NewDiag = diag::err_constructor_redeclared;
585 else if (isa<CXXDestructorDecl>(NewMethod))
586 NewDiag = diag::err_destructor_redeclared;
587 else if (isa<CXXConversionDecl>(NewMethod))
588 NewDiag = diag::err_conv_function_redeclared;
589 else
590 NewDiag = diag::err_member_redeclared;
591
592 Diag(New->getLocation(), NewDiag);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000593 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000594 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000595 }
596
597 // (C++98 8.3.5p3):
598 // All declarations for a function shall agree exactly in both the
599 // return type and the parameter-type-list.
Douglas Gregor04495c82009-02-24 01:23:02 +0000600 if (OldQType == NewQType)
601 return MergeCompatibleFunctionDecls(New, Old);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000602
603 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000604 }
Chris Lattner04421082008-04-08 04:40:51 +0000605
606 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000607 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000608 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000609 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor68719812009-02-16 18:20:44 +0000610 const FunctionType *NewFuncType = NewQType->getAsFunctionType();
611 const FunctionTypeProto *OldProto = 0;
612 if (isa<FunctionTypeNoProto>(NewFuncType) &&
613 (OldProto = OldQType->getAsFunctionTypeProto())) {
614 // The old declaration provided a function prototype, but the
615 // new declaration does not. Merge in the prototype.
616 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
617 OldProto->arg_type_end());
618 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
619 &ParamTypes[0], ParamTypes.size(),
620 OldProto->isVariadic(),
621 OldProto->getTypeQuals());
622 New->setType(NewQType);
623 New->setInheritedPrototype();
Douglas Gregor450da982009-02-16 20:58:07 +0000624
625 // Synthesize a parameter for each argument type.
626 llvm::SmallVector<ParmVarDecl*, 16> Params;
627 for (FunctionTypeProto::arg_type_iterator
628 ParamType = OldProto->arg_type_begin(),
629 ParamEnd = OldProto->arg_type_end();
630 ParamType != ParamEnd; ++ParamType) {
631 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
632 SourceLocation(), 0,
633 *ParamType, VarDecl::None,
634 0);
635 Param->setImplicit();
636 Params.push_back(Param);
637 }
638
639 New->setParams(Context, &Params[0], Params.size());
640
Douglas Gregor68719812009-02-16 18:20:44 +0000641 }
642
Douglas Gregor04495c82009-02-24 01:23:02 +0000643 return MergeCompatibleFunctionDecls(New, Old);
Chris Lattner04421082008-04-08 04:40:51 +0000644 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000645
Steve Naroff837618c2008-01-16 15:01:34 +0000646 // A function that has already been declared has been redeclared or defined
647 // with a different type- show appropriate diagnostic
Douglas Gregorcda9c672009-02-16 17:45:42 +0000648 if (unsigned BuiltinID = Old->getBuiltinID(Context)) {
649 // The user has declared a builtin function with an incompatible
650 // signature.
651 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
652 // The function the user is redeclaring is a library-defined
653 // function like 'malloc' or 'printf'. Warn about the
654 // redeclaration, then ignore it.
655 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
656 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
657 << Old << Old->getType();
Douglas Gregorc2b6a822009-02-18 22:00:45 +0000658 return true;
Douglas Gregorcda9c672009-02-16 17:45:42 +0000659 }
Steve Naroff837618c2008-01-16 15:01:34 +0000660
Douglas Gregorcda9c672009-02-16 17:45:42 +0000661 PrevDiag = diag::note_previous_builtin_declaration;
662 }
663
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000664 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000665 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000666 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000667}
668
Douglas Gregor04495c82009-02-24 01:23:02 +0000669/// \brief Completes the merge of two function declarations that are
670/// known to be compatible.
671///
672/// This routine handles the merging of attributes and other
673/// properties of function declarations form the old declaration to
674/// the new declaration, once we know that New is in fact a
675/// redeclaration of Old.
676///
677/// \returns false
678bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
679 // Merge the attributes
680 MergeAttributes(New, Old);
681
682 // Merge the storage class.
683 New->setStorageClass(Old->getStorageClass());
684
685 // FIXME: need to implement inline semantics
686
687 // Merge "pure" flag.
688 if (Old->isPure())
689 New->setPure();
690
691 // Merge the "deleted" flag.
692 if (Old->isDeleted())
693 New->setDeleted();
694
695 if (getLangOptions().CPlusPlus)
696 return MergeCXXFunctionDecl(New, Old);
697
698 return false;
699}
700
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000701/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000702static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000703 if (VD->isFileVarDecl())
704 return (!VD->getInit() &&
705 (VD->getStorageClass() == VarDecl::None ||
706 VD->getStorageClass() == VarDecl::Static));
707 return false;
708}
709
710/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
711/// when dealing with C "tentative" external object definitions (C99 6.9.2).
712void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
713 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000714 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000715
Douglas Gregore21b9942009-01-07 16:34:42 +0000716 // FIXME: I don't think this will actually see all of the
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000717 // redefinitions. Can't we check this property on-the-fly?
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000718 for (IdentifierResolver::iterator I = IdResolver.begin(VD->getIdentifier()),
719 E = IdResolver.end();
720 I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000721 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000722 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
723
Steve Narofff855e6f2008-08-10 15:20:13 +0000724 // Handle the following case:
725 // int a[10];
726 // int a[]; - the code below makes sure we set the correct type.
727 // int a[11]; - this is an error, size isn't 10.
728 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
729 OldDecl->getType()->isConstantArrayType())
730 VD->setType(OldDecl->getType());
731
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000732 // Check for "tentative" definitions. We can't accomplish this in
733 // MergeVarDecl since the initializer hasn't been attached.
734 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
735 continue;
736
737 // Handle __private_extern__ just like extern.
738 if (OldDecl->getStorageClass() != VarDecl::Extern &&
739 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
740 VD->getStorageClass() != VarDecl::Extern &&
741 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000742 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000743 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Sebastian Redl89ef6e02009-02-08 10:49:44 +0000744 // One redefinition error is enough.
745 break;
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000746 }
747 }
748 }
749}
750
Reid Spencer5f016e22007-07-11 17:01:13 +0000751/// MergeVarDecl - We just parsed a variable 'New' which has the same name
752/// and scope as a previous declaration 'Old'. Figure out how to resolve this
753/// situation, merging decls or emitting diagnostics as appropriate.
754///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000755/// Tentative definition rules (C99 6.9.2p2) are checked by
756/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
757/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000758///
Douglas Gregorcda9c672009-02-16 17:45:42 +0000759bool Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000760 // Verify the old decl was also a variable.
761 VarDecl *Old = dyn_cast<VarDecl>(OldD);
762 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000763 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000764 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000765 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000766 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000767 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000768
769 MergeAttributes(New, Old);
770
Eli Friedman13ca96a2009-01-24 23:49:55 +0000771 // Merge the types
772 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
773 if (MergedT.isNull()) {
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000774 Diag(New->getLocation(), diag::err_redefinition_different_type)
775 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000776 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000777 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000778 }
Eli Friedman13ca96a2009-01-24 23:49:55 +0000779 New->setType(MergedT);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000780 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
781 if (New->getStorageClass() == VarDecl::Static &&
782 (Old->getStorageClass() == VarDecl::None ||
783 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000784 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000785 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000786 return true;
Steve Naroffb7b032e2008-01-30 00:44:01 +0000787 }
788 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
789 if (New->getStorageClass() != VarDecl::Static &&
790 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000791 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000792 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000793 return true;
Steve Naroffb7b032e2008-01-30 00:44:01 +0000794 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000795 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
796 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000797 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000798 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000799 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000800 }
Douglas Gregorcda9c672009-02-16 17:45:42 +0000801 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000802}
803
Chris Lattner04421082008-04-08 04:40:51 +0000804/// CheckParmsForFunctionDef - Check that the parameters of the given
805/// function are appropriate for the definition of a function. This
806/// takes care of any checks that cannot be performed on the
807/// declaration itself, e.g., that the types of each of the function
808/// parameters are complete.
809bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
810 bool HasInvalidParm = false;
811 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
812 ParmVarDecl *Param = FD->getParamDecl(p);
813
814 // C99 6.7.5.3p4: the parameters in a parameter type list in a
815 // function declarator that is part of a function definition of
816 // that function shall not have incomplete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000817 if (!Param->isInvalidDecl() &&
818 DiagnoseIncompleteType(Param->getLocation(), Param->getType(),
819 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattner04421082008-04-08 04:40:51 +0000820 Param->setInvalidDecl();
821 HasInvalidParm = true;
822 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000823
824 // C99 6.9.1p5: If the declarator includes a parameter type list, the
825 // declaration of each parameter shall include an identifier.
Douglas Gregor450da982009-02-16 20:58:07 +0000826 if (Param->getIdentifier() == 0 &&
827 !Param->isImplicit() &&
828 !getLangOptions().CPlusPlus)
Chris Lattner777f07b2008-12-17 07:32:46 +0000829 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000830 }
831
832 return HasInvalidParm;
833}
834
Reid Spencer5f016e22007-07-11 17:01:13 +0000835/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
836/// no declarator (e.g. "struct foo;") is parsed.
837Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000838 TagDecl *Tag = 0;
839 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
840 DS.getTypeSpecType() == DeclSpec::TST_struct ||
841 DS.getTypeSpecType() == DeclSpec::TST_union ||
842 DS.getTypeSpecType() == DeclSpec::TST_enum)
843 Tag = dyn_cast<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
844
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000845 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
846 if (!Record->getDeclName() && Record->isDefinition() &&
847 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
848 return BuildAnonymousStructOrUnion(S, DS, Record);
849
850 // Microsoft allows unnamed struct/union fields. Don't complain
851 // about them.
852 // FIXME: Should we support Microsoft's extensions in this area?
853 if (Record->getDeclName() && getLangOptions().Microsoft)
854 return Tag;
855 }
856
Douglas Gregorddc29e12009-02-06 22:42:48 +0000857 if (!DS.isMissingDeclaratorOk() &&
858 DS.getTypeSpecType() != DeclSpec::TST_error) {
Douglas Gregor21282df2009-01-22 16:23:54 +0000859 // Warn about typedefs of enums without names, since this is an
860 // extension in both Microsoft an GNU.
Douglas Gregor8158f692009-01-17 02:55:50 +0000861 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
862 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor21282df2009-01-22 16:23:54 +0000863 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregoree159c12009-01-13 23:10:51 +0000864 << DS.getSourceRange();
865 return Tag;
866 }
867
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000868 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
869 << DS.getSourceRange();
870 return 0;
871 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000872
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000873 return Tag;
874}
875
876/// InjectAnonymousStructOrUnionMembers - Inject the members of the
877/// anonymous struct or union AnonRecord into the owning context Owner
878/// and scope S. This routine will be invoked just after we realize
879/// that an unnamed union or struct is actually an anonymous union or
880/// struct, e.g.,
881///
882/// @code
883/// union {
884/// int i;
885/// float f;
886/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
887/// // f into the surrounding scope.x
888/// @endcode
889///
890/// This routine is recursive, injecting the names of nested anonymous
891/// structs/unions into the owning context and scope as well.
892bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
893 RecordDecl *AnonRecord) {
894 bool Invalid = false;
895 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
896 FEnd = AnonRecord->field_end();
897 F != FEnd; ++F) {
898 if ((*F)->getDeclName()) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000899 NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
900 LookupOrdinaryName, true);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000901 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
902 // C++ [class.union]p2:
903 // The names of the members of an anonymous union shall be
904 // distinct from the names of any other entity in the
905 // scope in which the anonymous union is declared.
906 unsigned diagKind
907 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
908 : diag::err_anonymous_struct_member_redecl;
909 Diag((*F)->getLocation(), diagKind)
910 << (*F)->getDeclName();
911 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
912 Invalid = true;
913 } else {
914 // C++ [class.union]p2:
915 // For the purpose of name lookup, after the anonymous union
916 // definition, the members of the anonymous union are
917 // considered to have been defined in the scope in which the
918 // anonymous union is declared.
Douglas Gregor40f4e692009-01-20 16:54:50 +0000919 Owner->makeDeclVisibleInContext(*F);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000920 S->AddDecl(*F);
921 IdResolver.AddDecl(*F);
922 }
923 } else if (const RecordType *InnerRecordType
924 = (*F)->getType()->getAsRecordType()) {
925 RecordDecl *InnerRecord = InnerRecordType->getDecl();
926 if (InnerRecord->isAnonymousStructOrUnion())
927 Invalid = Invalid ||
928 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
929 }
930 }
931
932 return Invalid;
933}
934
935/// ActOnAnonymousStructOrUnion - Handle the declaration of an
936/// anonymous structure or union. Anonymous unions are a C++ feature
937/// (C++ [class.union]) and a GNU C extension; anonymous structures
938/// are a GNU C and GNU C++ extension.
939Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
940 RecordDecl *Record) {
941 DeclContext *Owner = Record->getDeclContext();
942
943 // Diagnose whether this anonymous struct/union is an extension.
944 if (Record->isUnion() && !getLangOptions().CPlusPlus)
945 Diag(Record->getLocation(), diag::ext_anonymous_union);
946 else if (!Record->isUnion())
947 Diag(Record->getLocation(), diag::ext_anonymous_struct);
948
949 // C and C++ require different kinds of checks for anonymous
950 // structs/unions.
951 bool Invalid = false;
952 if (getLangOptions().CPlusPlus) {
953 const char* PrevSpec = 0;
954 // C++ [class.union]p3:
955 // Anonymous unions declared in a named namespace or in the
956 // global namespace shall be declared static.
957 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
958 (isa<TranslationUnitDecl>(Owner) ||
959 (isa<NamespaceDecl>(Owner) &&
960 cast<NamespaceDecl>(Owner)->getDeclName()))) {
961 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
962 Invalid = true;
963
964 // Recover by adding 'static'.
965 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
966 }
967 // C++ [class.union]p3:
968 // A storage class is not allowed in a declaration of an
969 // anonymous union in a class scope.
970 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
971 isa<RecordDecl>(Owner)) {
972 Diag(DS.getStorageClassSpecLoc(),
973 diag::err_anonymous_union_with_storage_spec);
974 Invalid = true;
975
976 // Recover by removing the storage specifier.
977 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
978 PrevSpec);
979 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000980
981 // C++ [class.union]p2:
982 // The member-specification of an anonymous union shall only
983 // define non-static data members. [Note: nested types and
984 // functions cannot be declared within an anonymous union. ]
985 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
986 MemEnd = Record->decls_end();
987 Mem != MemEnd; ++Mem) {
988 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
989 // C++ [class.union]p3:
990 // An anonymous union shall not have private or protected
991 // members (clause 11).
992 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
993 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
994 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
995 Invalid = true;
996 }
997 } else if ((*Mem)->isImplicit()) {
998 // Any implicit members are fine.
Douglas Gregor1931b442009-02-03 00:34:39 +0000999 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1000 // This is a type that showed up in an
1001 // elaborated-type-specifier inside the anonymous struct or
1002 // union, but which actually declares a type outside of the
1003 // anonymous struct or union. It's okay.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001004 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1005 if (!MemRecord->isAnonymousStructOrUnion() &&
1006 MemRecord->getDeclName()) {
1007 // This is a nested type declaration.
1008 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1009 << (int)Record->isUnion();
1010 Invalid = true;
1011 }
1012 } else {
1013 // We have something that isn't a non-static data
1014 // member. Complain about it.
1015 unsigned DK = diag::err_anonymous_record_bad_member;
1016 if (isa<TypeDecl>(*Mem))
1017 DK = diag::err_anonymous_record_with_type;
1018 else if (isa<FunctionDecl>(*Mem))
1019 DK = diag::err_anonymous_record_with_function;
1020 else if (isa<VarDecl>(*Mem))
1021 DK = diag::err_anonymous_record_with_static;
1022 Diag((*Mem)->getLocation(), DK)
1023 << (int)Record->isUnion();
1024 Invalid = true;
1025 }
1026 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001027 } else {
1028 // FIXME: Check GNU C semantics
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001029 if (Record->isUnion() && !Owner->isRecord()) {
1030 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
1031 << (int)getLangOptions().CPlusPlus;
1032 Invalid = true;
1033 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001034 }
1035
1036 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001037 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1038 << (int)getLangOptions().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001039 Invalid = true;
1040 }
1041
1042 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001043 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001044 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1045 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1046 /*IdentifierInfo=*/0,
1047 Context.getTypeDeclType(Record),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001048 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001049 Anon->setAccess(AS_public);
1050 if (getLangOptions().CPlusPlus)
1051 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001052 } else {
1053 VarDecl::StorageClass SC;
1054 switch (DS.getStorageClassSpec()) {
1055 default: assert(0 && "Unknown storage class!");
1056 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1057 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1058 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1059 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1060 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1061 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1062 case DeclSpec::SCS_mutable:
1063 // mutable can only appear on non-static class members, so it's always
1064 // an error here
1065 Diag(Record->getLocation(), diag::err_mutable_nonmember);
1066 Invalid = true;
1067 SC = VarDecl::None;
1068 break;
1069 }
1070
1071 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1072 /*IdentifierInfo=*/0,
1073 Context.getTypeDeclType(Record),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001074 SC, DS.getSourceRange().getBegin());
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001075 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001076 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001077
1078 // Add the anonymous struct/union object to the current
1079 // context. We'll be referencing this object when we refer to one of
1080 // its members.
Douglas Gregor482b77d2009-01-12 23:27:07 +00001081 Owner->addDecl(Anon);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001082
1083 // Inject the members of the anonymous struct/union into the owning
1084 // context and into the identifier resolver chain for name lookup
1085 // purposes.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001086 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1087 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001088
1089 // Mark this as an anonymous struct/union type. Note that we do not
1090 // do this until after we have already checked and injected the
1091 // members of this anonymous struct/union type, because otherwise
1092 // the members could be injected twice: once by DeclContext when it
1093 // builds its lookup table, and once by
1094 // InjectAnonymousStructOrUnionMembers.
1095 Record->setAnonymousStructOrUnion(true);
1096
1097 if (Invalid)
1098 Anon->setInvalidDecl();
1099
1100 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +00001101}
1102
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001103bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
1104 bool DirectInit) {
Steve Narofff0090632007-09-02 02:04:30 +00001105 // Get the type before calling CheckSingleAssignmentConstraints(), since
1106 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001107 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +00001108
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001109 if (getLangOptions().CPlusPlus) {
1110 // FIXME: I dislike this error message. A lot.
1111 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
1112 return Diag(Init->getSourceRange().getBegin(),
1113 diag::err_typecheck_convert_incompatible)
1114 << DeclType << Init->getType() << "initializing"
1115 << Init->getSourceRange();
1116
1117 return false;
1118 }
Douglas Gregor45920e82008-12-19 17:40:08 +00001119
Chris Lattner5cf216b2008-01-04 18:04:52 +00001120 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1121 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1122 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +00001123}
1124
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001125bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001126 const ArrayType *AT = Context.getAsArrayType(DeclT);
1127
1128 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001129 // C99 6.7.8p14. We have an array of character type with unknown size
1130 // being initialized to a string literal.
1131 llvm::APSInt ConstVal(32);
1132 ConstVal = strLiteral->getByteLength() + 1;
1133 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +00001134 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001135 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001136 } else {
1137 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001138 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001139 // FIXME: Avoid truncation for 64-bit length strings.
1140 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001141 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001142 diag::warn_initializer_string_for_char_array_too_long)
1143 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001144 }
1145 // Set type from "char *" to "constant array of char".
1146 strLiteral->setType(DeclT);
1147 // For now, we always return false (meaning success).
1148 return false;
1149}
1150
1151StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattner111c2ee2009-02-24 21:54:33 +00001152 if (const ArrayType *AT = Context.getAsArrayType(DeclType))
1153 if (AT->getElementType()->isCharType())
1154 return dyn_cast<StringLiteral>(Init->IgnoreParens());
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001155 return 0;
1156}
1157
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001158bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1159 SourceLocation InitLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001160 DeclarationName InitEntity,
1161 bool DirectInit) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +00001162 if (DeclType->isDependentType() || Init->isTypeDependent())
1163 return false;
1164
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001165 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +00001166 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001167 // (8.3.2), shall be initialized by an object, or function, of
1168 // type T or by an object that can be converted into a T.
1169 if (DeclType->isReferenceType())
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001170 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001171
Steve Naroffca107302008-01-21 23:53:58 +00001172 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1173 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001174 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001175 return Diag(InitLoc, diag::err_variable_object_no_init)
1176 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +00001177
Steve Naroff2fdc3742007-12-10 22:44:33 +00001178 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1179 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001180 // FIXME: Handle wide strings
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001181 if (StringLiteral *StrLiteral = IsStringLiteralInit(Init, DeclType))
1182 return CheckStringLiteralInit(StrLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +00001183
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001184 // C++ [dcl.init]p14:
1185 // -- If the destination type is a (possibly cv-qualified) class
1186 // type:
1187 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1188 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1189 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1190
1191 // -- If the initialization is direct-initialization, or if it is
1192 // copy-initialization where the cv-unqualified version of the
1193 // source type is the same class as, or a derived class of, the
1194 // class of the destination, constructors are considered.
1195 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1196 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1197 CXXConstructorDecl *Constructor
1198 = PerformInitializationByConstructor(DeclType, &Init, 1,
1199 InitLoc, Init->getSourceRange(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001200 InitEntity,
1201 DirectInit? IK_Direct : IK_Copy);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001202 return Constructor == 0;
1203 }
1204
1205 // -- Otherwise (i.e., for the remaining copy-initialization
1206 // cases), user-defined conversion sequences that can
1207 // convert from the source type to the destination type or
1208 // (when a conversion function is used) to a derived class
1209 // thereof are enumerated as described in 13.3.1.4, and the
1210 // best one is chosen through overload resolution
1211 // (13.3). If the conversion cannot be done or is
1212 // ambiguous, the initialization is ill-formed. The
1213 // function selected is called with the initializer
1214 // expression as its argument; if the function is a
1215 // constructor, the call initializes a temporary of the
1216 // destination type.
1217 // FIXME: We're pretending to do copy elision here; return to
1218 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +00001219 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001220 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001221
Douglas Gregor61366e92008-12-24 00:01:03 +00001222 if (InitEntity)
1223 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1224 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1225 << Init->getType() << Init->getSourceRange();
1226 else
1227 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1228 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1229 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001230 }
1231
Steve Naroff1ac6fdd2008-09-29 20:07:05 +00001232 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +00001233 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001234 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1235 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +00001236
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001237 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregor930d8b52009-01-30 22:09:00 +00001238 }
Eli Friedmane6f058f2008-06-06 19:40:52 +00001239
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001240 bool hadError = CheckInitList(InitList, DeclType);
1241 Init = InitList;
1242 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +00001243}
1244
Douglas Gregor10bd3682008-11-17 22:58:34 +00001245/// GetNameForDeclarator - Determine the full declaration name for the
1246/// given Declarator.
1247DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1248 switch (D.getKind()) {
1249 case Declarator::DK_Abstract:
1250 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1251 return DeclarationName();
1252
1253 case Declarator::DK_Normal:
1254 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1255 return DeclarationName(D.getIdentifier());
1256
1257 case Declarator::DK_Constructor: {
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001258 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001259 Ty = Context.getCanonicalType(Ty);
1260 return Context.DeclarationNames.getCXXConstructorName(Ty);
1261 }
1262
1263 case Declarator::DK_Destructor: {
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001264 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001265 Ty = Context.getCanonicalType(Ty);
1266 return Context.DeclarationNames.getCXXDestructorName(Ty);
1267 }
1268
1269 case Declarator::DK_Conversion: {
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001270 // FIXME: We'd like to keep the non-canonical type for diagnostics!
Douglas Gregor10bd3682008-11-17 22:58:34 +00001271 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1272 Ty = Context.getCanonicalType(Ty);
1273 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1274 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001275
1276 case Declarator::DK_Operator:
1277 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1278 return Context.DeclarationNames.getCXXOperatorName(
1279 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001280 }
1281
1282 assert(false && "Unknown name kind");
1283 return DeclarationName();
1284}
1285
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001286/// isNearlyMatchingFunction - Determine whether the C++ functions
1287/// Declaration and Definition are "nearly" matching. This heuristic
1288/// is used to improve diagnostics in the case where an out-of-line
1289/// function definition doesn't match any declaration within
1290/// the class or namespace.
1291static bool isNearlyMatchingFunction(ASTContext &Context,
1292 FunctionDecl *Declaration,
1293 FunctionDecl *Definition) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001294 if (Declaration->param_size() != Definition->param_size())
1295 return false;
1296 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1297 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1298 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1299
1300 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1301 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1302 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1303 return false;
1304 }
1305
1306 return true;
1307}
1308
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001309Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001310Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1311 bool IsFunctionDefinition) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001312 NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001313 DeclarationName Name = GetNameForDeclarator(D);
1314
Chris Lattnere80a59c2007-07-25 00:24:17 +00001315 // All of these full declarators require an identifier. If it doesn't have
1316 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001317 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001318 if (!D.getInvalidType()) // Reject this if we think it is valid.
1319 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001320 diag::err_declarator_need_ident)
1321 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001322 return 0;
1323 }
1324
Chris Lattner31e05722007-08-26 06:24:45 +00001325 // The scope passed in may not be a decl scope. Zip up the scope tree until
1326 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001327 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregoraaba5e32009-02-04 19:02:06 +00001328 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001329 S = S->getParent();
1330
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001331 DeclContext *DC;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001332 NamedDecl *PrevDecl;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001333 NamedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001334 bool InvalidDecl = false;
Douglas Gregorcda9c672009-02-16 17:45:42 +00001335
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001336 QualType R = GetTypeForDeclarator(D, S);
1337 if (R.isNull()) {
1338 InvalidDecl = true;
1339 R = Context.IntTy;
1340 }
1341
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001342 // See if this is a redefinition of a variable in the same scope.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001343 if (!D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid()) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001344 LookupNameKind NameKind = LookupOrdinaryName;
1345
1346 // If the declaration we're planning to build will be a function
1347 // or object with linkage, then look for another declaration with
1348 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1349 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1350 /* Do nothing*/;
1351 else if (R->isFunctionType()) {
1352 if (CurContext->isFunctionOrMethod())
1353 NameKind = LookupRedeclarationWithLinkage;
1354 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
1355 NameKind = LookupRedeclarationWithLinkage;
1356
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001357 DC = CurContext;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001358 PrevDecl = LookupName(S, Name, NameKind, true,
Douglas Gregor9add3172009-02-17 03:23:10 +00001359 D.getDeclSpec().getStorageClassSpec() !=
1360 DeclSpec::SCS_static,
Douglas Gregor3e41d602009-02-13 23:20:09 +00001361 D.getIdentifierLoc());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001362 } else { // Something like "int foo::x;"
1363 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor3e41d602009-02-13 23:20:09 +00001364 PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001365
1366 // C++ 7.3.1.2p2:
1367 // Members (including explicit specializations of templates) of a named
1368 // namespace can also be defined outside that namespace by explicit
1369 // qualification of the name being defined, provided that the entity being
1370 // defined was already declared in the namespace and the definition appears
1371 // after the point of declaration in a namespace that encloses the
1372 // declarations namespace.
1373 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001374 // Note that we only check the context at this point. We don't yet
1375 // have enough information to make sure that PrevDecl is actually
1376 // the declaration we want to match. For example, given:
1377 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001378 // class X {
1379 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001380 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001381 // };
1382 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001383 // void X::f(int) { } // ill-formed
1384 //
1385 // In this case, PrevDecl will point to the overload set
1386 // containing the two f's declared in X, but neither of them
1387 // matches.
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001388
1389 // First check whether we named the global scope.
1390 if (isa<TranslationUnitDecl>(DC)) {
1391 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
1392 << Name << D.getCXXScopeSpec().getRange();
1393 } else if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001394 // The qualifying scope doesn't enclose the original declaration.
1395 // Emit diagnostic based on current scope.
1396 SourceLocation L = D.getIdentifierLoc();
1397 SourceRange R = D.getCXXScopeSpec().getRange();
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001398 if (isa<FunctionDecl>(CurContext))
Chris Lattner011bb4e2008-11-23 20:28:15 +00001399 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001400 else
Chris Lattner011bb4e2008-11-23 20:28:15 +00001401 Diag(L, diag::err_invalid_declarator_scope)
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001402 << Name << cast<NamedDecl>(DC) << R;
Douglas Gregor44b43212008-12-11 16:49:14 +00001403 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001404 }
1405 }
1406
Douglas Gregorf57172b2008-12-08 18:40:42 +00001407 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001408 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001409 InvalidDecl = InvalidDecl
1410 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001411 // Just pretend that we didn't see the previous declaration.
1412 PrevDecl = 0;
1413 }
1414
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001415 // In C++, the previous declaration we find might be a tag type
1416 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00001417 // tag type. Note that this does does not apply if we're declaring a
1418 // typedef (C++ [dcl.typedef]p4).
1419 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1420 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001421 PrevDecl = 0;
1422
Douglas Gregorcda9c672009-02-16 17:45:42 +00001423 bool Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001425 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
Douglas Gregorcda9c672009-02-16 17:45:42 +00001426 InvalidDecl, Redeclaration);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001427 } else if (R->isFunctionType()) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001428 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
Douglas Gregorcda9c672009-02-16 17:45:42 +00001429 IsFunctionDefinition, InvalidDecl,
1430 Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +00001431 } else {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001432 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
Douglas Gregorcda9c672009-02-16 17:45:42 +00001433 InvalidDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +00001434 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001435
1436 if (New == 0)
1437 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001438
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001439 // Set the lexical context. If the declarator has a C++ scope specifier, the
1440 // lexical context will be different from the semantic context.
1441 New->setLexicalDeclContext(CurContext);
1442
Douglas Gregorcda9c672009-02-16 17:45:42 +00001443 // If this has an identifier and is not an invalid redeclaration,
1444 // add it to the scope stack.
1445 if (Name && !(Redeclaration && InvalidDecl))
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001446 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001447 // If any semantic error occurred, mark the decl as invalid.
1448 if (D.getInvalidType() || InvalidDecl)
1449 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001450
1451 return New;
1452}
1453
Eli Friedman1ca48132009-02-21 00:44:51 +00001454/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
1455/// types into constant array types in certain situations which would otherwise
1456/// be errors (for GCC compatibility).
1457static QualType TryToFixInvalidVariablyModifiedType(QualType T,
1458 ASTContext &Context,
1459 bool &SizeIsNegative) {
1460 // This method tries to turn a variable array into a constant
1461 // array even when the size isn't an ICE. This is necessary
1462 // for compatibility with code that depends on gcc's buggy
1463 // constant expression folding, like struct {char x[(int)(char*)2];}
1464 SizeIsNegative = false;
1465
1466 if (const PointerType* PTy = dyn_cast<PointerType>(T)) {
1467 QualType Pointee = PTy->getPointeeType();
1468 QualType FixedType =
1469 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
1470 if (FixedType.isNull()) return FixedType;
Eli Friedman61125c82009-02-21 00:58:02 +00001471 FixedType = Context.getPointerType(FixedType);
1472 FixedType.setCVRQualifiers(T.getCVRQualifiers());
1473 return FixedType;
Eli Friedman1ca48132009-02-21 00:44:51 +00001474 }
1475
1476 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
1477 if (!VLATy) return QualType();
1478
1479 Expr::EvalResult EvalResult;
1480 if (!VLATy->getSizeExpr() ||
1481 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
1482 return QualType();
1483
1484 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
1485 llvm::APSInt &Res = EvalResult.Val.getInt();
1486 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1487 return Context.getConstantArrayType(VLATy->getElementType(),
1488 Res, ArrayType::Normal, 0);
1489
1490 SizeIsNegative = true;
1491 return QualType();
1492}
1493
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001494NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001495Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001496 QualType R, Decl* LastDeclarator,
Douglas Gregorcda9c672009-02-16 17:45:42 +00001497 Decl* PrevDecl, bool& InvalidDecl,
1498 bool &Redeclaration) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001499 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1500 if (D.getCXXScopeSpec().isSet()) {
1501 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1502 << D.getCXXScopeSpec().getRange();
1503 InvalidDecl = true;
1504 // Pretend we didn't see the scope specifier.
1505 DC = 0;
1506 }
1507
1508 // Check that there are no default arguments (C++ only).
1509 if (getLangOptions().CPlusPlus)
1510 CheckExtraCXXDefaultArguments(D);
1511
1512 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1513 if (!NewTD) return 0;
1514
1515 // Handle attributes prior to checking for duplicates in MergeVarDecl
1516 ProcessDeclAttributes(NewTD, D);
1517 // Merge the decl with the existing one if appropriate. If the decl is
1518 // in an outer scope, it isn't the same thing.
1519 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00001520 Redeclaration = true;
1521 if (MergeTypeDefDecl(NewTD, PrevDecl))
1522 InvalidDecl = true;
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001523 }
1524
1525 if (S->getFnParent() == 0) {
Eli Friedman1ca48132009-02-21 00:44:51 +00001526 QualType T = NewTD->getUnderlyingType();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001527 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1528 // then it shall have block scope.
Eli Friedman1ca48132009-02-21 00:44:51 +00001529 if (T->isVariablyModifiedType()) {
1530 bool SizeIsNegative;
1531 QualType FixedTy =
1532 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
1533 if (!FixedTy.isNull()) {
1534 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
1535 NewTD->setUnderlyingType(FixedTy);
1536 } else {
1537 if (SizeIsNegative)
1538 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
1539 else if (T->isVariableArrayType())
1540 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1541 else
1542 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1543 InvalidDecl = true;
1544 }
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001545 }
1546 }
1547 return NewTD;
1548}
1549
Douglas Gregor8f301052009-02-24 19:23:27 +00001550/// \brief Determines whether the given declaration is an out-of-scope
1551/// previous declaration.
1552///
1553/// This routine should be invoked when name lookup has found a
1554/// previous declaration (PrevDecl) that is not in the scope where a
1555/// new declaration by the same name is being introduced. If the new
1556/// declaration occurs in a local scope, previous declarations with
1557/// linkage may still be considered previous declarations (C99
1558/// 6.2.2p4-5, C++ [basic.link]p6).
1559///
1560/// \param PrevDecl the previous declaration found by name
1561/// lookup
1562///
1563/// \param DC the context in which the new declaration is being
1564/// declared.
1565///
1566/// \returns true if PrevDecl is an out-of-scope previous declaration
1567/// for a new delcaration with the same name.
1568static bool
1569isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
1570 ASTContext &Context) {
1571 if (!PrevDecl)
1572 return 0;
1573
1574 // FIXME: PrevDecl could be an OverloadedFunctionDecl, in which
1575 // case we need to check each of the overloaded functions.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001576 if (!PrevDecl->hasLinkage())
1577 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00001578
1579 if (Context.getLangOptions().CPlusPlus) {
1580 // C++ [basic.link]p6:
1581 // If there is a visible declaration of an entity with linkage
1582 // having the same name and type, ignoring entities declared
1583 // outside the innermost enclosing namespace scope, the block
1584 // scope declaration declares that same entity and receives the
1585 // linkage of the previous declaration.
1586 DeclContext *OuterContext = DC->getLookupContext();
1587 if (!OuterContext->isFunctionOrMethod())
1588 // This rule only applies to block-scope declarations.
1589 return false;
1590 else {
1591 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
1592 if (PrevOuterContext->isRecord())
1593 // We found a member function: ignore it.
1594 return false;
1595 else {
1596 // Find the innermost enclosing namespace for the new and
1597 // previous declarations.
1598 while (!OuterContext->isFileContext())
1599 OuterContext = OuterContext->getParent();
1600 while (!PrevOuterContext->isFileContext())
1601 PrevOuterContext = PrevOuterContext->getParent();
1602
1603 // The previous declaration is in a different namespace, so it
1604 // isn't the same function.
1605 if (OuterContext->getPrimaryContext() !=
1606 PrevOuterContext->getPrimaryContext())
1607 return false;
1608 }
1609 }
1610 }
1611
Douglas Gregor8f301052009-02-24 19:23:27 +00001612 return true;
1613}
1614
1615/// \brief Inject a locally-scoped declaration with external linkage
1616/// into the appropriate namespace scope.
1617///
1618/// Given a declaration of an entity with linkage that occurs within a
1619/// local scope, this routine inject that declaration into top-level
1620/// scope so that it will be visible for later uses and declarations
1621/// of the same entity.
1622void Sema::InjectLocallyScopedExternalDeclaration(ValueDecl *VD) {
1623 // FIXME: We don't do this in C++ because, although we would like
1624 // to get the extra checking that this operation implies,
1625 // the declaration itself is not visible according to C++'s rules.
1626 assert(!getLangOptions().CPlusPlus &&
1627 "Can't inject locally-scoped declarations in C++");
1628 IdentifierResolver::iterator I = IdResolver.begin(VD->getDeclName()),
1629 IEnd = IdResolver.end();
1630 NamedDecl *PrevDecl = 0;
1631 while (I != IEnd && !isa<TranslationUnitDecl>((*I)->getDeclContext())) {
1632 PrevDecl = *I;
1633 ++I;
1634 }
1635
1636 if (I == IEnd) {
1637 // No name with this identifier has been declared at translation
1638 // unit scope. Add this name into the appropriate scope.
1639 if (PrevDecl)
1640 IdResolver.AddShadowedDecl(VD, PrevDecl);
1641 else
1642 IdResolver.AddDecl(VD);
1643 TUScope->AddDecl(VD);
1644 return;
1645 }
1646
1647 if (isa<TagDecl>(*I)) {
1648 // The first thing we found was a tag declaration, so insert
1649 // this function so that it will be found before the tag
1650 // declaration.
1651 if (PrevDecl)
1652 IdResolver.AddShadowedDecl(VD, PrevDecl);
1653 else
1654 IdResolver.AddDecl(VD);
1655 TUScope->AddDecl(VD);
1656 return;
1657 }
1658
1659 if (VD->declarationReplaces(*I)) {
1660 // We found a previous declaration of the same entity. Replace
1661 // that declaration with this one.
1662 TUScope->RemoveDecl(*I);
1663 TUScope->AddDecl(VD);
1664 IdResolver.RemoveDecl(*I);
1665 if (PrevDecl)
1666 IdResolver.AddShadowedDecl(VD, PrevDecl);
1667 else
1668 IdResolver.AddDecl(VD);
1669 }
1670}
1671
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001672NamedDecl*
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001673Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001674 QualType R, Decl* LastDeclarator,
Douglas Gregor8f301052009-02-24 19:23:27 +00001675 NamedDecl* PrevDecl, bool& InvalidDecl,
Douglas Gregorcda9c672009-02-16 17:45:42 +00001676 bool &Redeclaration) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001677 DeclarationName Name = GetNameForDeclarator(D);
1678
1679 // Check that there are no default arguments (C++ only).
1680 if (getLangOptions().CPlusPlus)
1681 CheckExtraCXXDefaultArguments(D);
1682
1683 if (R.getTypePtr()->isObjCInterfaceType()) {
Steve Naroffccef3712009-02-20 22:59:16 +00001684 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001685 InvalidDecl = true;
1686 }
1687
1688 VarDecl *NewVD;
1689 VarDecl::StorageClass SC;
1690 switch (D.getDeclSpec().getStorageClassSpec()) {
1691 default: assert(0 && "Unknown storage class!");
1692 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1693 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1694 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1695 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1696 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1697 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1698 case DeclSpec::SCS_mutable:
1699 // mutable can only appear on non-static class members, so it's always
1700 // an error here
1701 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1702 InvalidDecl = true;
1703 SC = VarDecl::None;
1704 break;
1705 }
1706
1707 IdentifierInfo *II = Name.getAsIdentifierInfo();
1708 if (!II) {
1709 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1710 << Name.getAsString();
1711 return 0;
1712 }
1713
1714 if (DC->isRecord()) {
1715 // This is a static data member for a C++ class.
1716 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1717 D.getIdentifierLoc(), II,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001718 R);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001719 } else {
1720 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1721 if (S->getFnParent() == 0) {
1722 // C99 6.9p2: The storage-class specifiers auto and register shall not
1723 // appear in the declaration specifiers in an external declaration.
1724 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1725 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1726 InvalidDecl = true;
1727 }
1728 }
1729 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001730 II, R, SC,
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001731 // FIXME: Move to DeclGroup...
1732 D.getDeclSpec().getSourceRange().getBegin());
1733 NewVD->setThreadSpecified(ThreadSpecified);
1734 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001735 NewVD->setNextDeclarator(LastDeclarator);
1736
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001737 // Handle attributes prior to checking for duplicates in MergeVarDecl
1738 ProcessDeclAttributes(NewVD, D);
1739
1740 // Handle GNU asm-label extension (encoded as an attribute).
1741 if (Expr *E = (Expr*) D.getAsmLabel()) {
1742 // The parser guarantees this is a string.
1743 StringLiteral *SE = cast<StringLiteral>(E);
1744 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1745 SE->getByteLength())));
1746 }
1747
1748 // Emit an error if an address space was applied to decl with local storage.
1749 // This includes arrays of objects with address space qualifiers, but not
1750 // automatic variables that point to other address spaces.
1751 // ISO/IEC TR 18037 S5.1.2
1752 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1753 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1754 InvalidDecl = true;
1755 }
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00001756
1757 if (NewVD->hasLocalStorage() && NewVD->getType().isObjCGCWeak()) {
1758 Diag(D.getIdentifierLoc(), diag::warn_attribute_weak_on_local);
1759 }
1760
Douglas Gregor8f301052009-02-24 19:23:27 +00001761 // If name lookup finds a previous declaration that is not in the
1762 // same scope as the new declaration, this may still be an
1763 // acceptable redeclaration.
1764 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001765 !(NewVD->hasLinkage() &&
Douglas Gregor8f301052009-02-24 19:23:27 +00001766 isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
1767 PrevDecl = 0;
1768
1769 // Merge the decl with the existing one if appropriate.
1770 if (PrevDecl) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001771 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1772 // The user tried to define a non-static data member
1773 // out-of-line (C++ [dcl.meaning]p1).
1774 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1775 << D.getCXXScopeSpec().getRange();
1776 NewVD->Destroy(Context);
1777 return 0;
1778 }
1779
Douglas Gregorcda9c672009-02-16 17:45:42 +00001780 Redeclaration = true;
1781 if (MergeVarDecl(NewVD, PrevDecl))
1782 InvalidDecl = true;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001783
1784 if (D.getCXXScopeSpec().isSet()) {
1785 // No previous declaration in the qualifying scope.
1786 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1787 << Name << D.getCXXScopeSpec().getRange();
1788 InvalidDecl = true;
1789 }
1790 }
Douglas Gregor8f301052009-02-24 19:23:27 +00001791
1792 // If this is a locally-scoped extern variable in C, inject a
1793 // declaration into translation unit scope so that all external
1794 // declarations are visible.
1795 if (!getLangOptions().CPlusPlus && CurContext->isFunctionOrMethod() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001796 NewVD->hasLinkage())
Douglas Gregor8f301052009-02-24 19:23:27 +00001797 InjectLocallyScopedExternalDeclaration(NewVD);
1798
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001799 return NewVD;
1800}
1801
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001802NamedDecl*
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001803Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001804 QualType R, Decl *LastDeclarator,
Douglas Gregor04495c82009-02-24 01:23:02 +00001805 NamedDecl* PrevDecl, bool IsFunctionDefinition,
Douglas Gregorcda9c672009-02-16 17:45:42 +00001806 bool& InvalidDecl, bool &Redeclaration) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001807 assert(R.getTypePtr()->isFunctionType());
1808
1809 DeclarationName Name = GetNameForDeclarator(D);
1810 FunctionDecl::StorageClass SC = FunctionDecl::None;
1811 switch (D.getDeclSpec().getStorageClassSpec()) {
1812 default: assert(0 && "Unknown storage class!");
1813 case DeclSpec::SCS_auto:
1814 case DeclSpec::SCS_register:
1815 case DeclSpec::SCS_mutable:
Douglas Gregor04495c82009-02-24 01:23:02 +00001816 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
1817 diag::err_typecheck_sclass_func);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001818 InvalidDecl = true;
1819 break;
1820 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1821 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
Douglas Gregor04495c82009-02-24 01:23:02 +00001822 case DeclSpec::SCS_static: {
1823 if (DC->getLookupContext()->isFunctionOrMethod()) {
1824 // C99 6.7.1p5:
1825 // The declaration of an identifier for a function that has
1826 // block scope shall have no explicit storage-class specifier
1827 // other than extern
1828 // See also (C++ [dcl.stc]p4).
1829 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
1830 diag::err_static_block_func);
1831 SC = FunctionDecl::None;
1832 } else
1833 SC = FunctionDecl::Static;
1834 break;
1835 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001836 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1837 }
1838
1839 bool isInline = D.getDeclSpec().isInlineSpecified();
1840 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1841 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1842
1843 FunctionDecl *NewFD;
1844 if (D.getKind() == Declarator::DK_Constructor) {
1845 // This is a C++ constructor declaration.
1846 assert(DC->isRecord() &&
1847 "Constructors can only be declared in a member context");
1848
1849 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1850
1851 // Create the new declaration
1852 NewFD = CXXConstructorDecl::Create(Context,
1853 cast<CXXRecordDecl>(DC),
1854 D.getIdentifierLoc(), Name, R,
1855 isExplicit, isInline,
1856 /*isImplicitlyDeclared=*/false);
1857
1858 if (InvalidDecl)
1859 NewFD->setInvalidDecl();
1860 } else if (D.getKind() == Declarator::DK_Destructor) {
1861 // This is a C++ destructor declaration.
1862 if (DC->isRecord()) {
1863 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1864
1865 NewFD = CXXDestructorDecl::Create(Context,
1866 cast<CXXRecordDecl>(DC),
1867 D.getIdentifierLoc(), Name, R,
1868 isInline,
1869 /*isImplicitlyDeclared=*/false);
1870
1871 if (InvalidDecl)
1872 NewFD->setInvalidDecl();
1873 } else {
1874 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1875
1876 // Create a FunctionDecl to satisfy the function definition parsing
1877 // code path.
1878 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001879 Name, R, SC, isInline,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001880 // FIXME: Move to DeclGroup...
1881 D.getDeclSpec().getSourceRange().getBegin());
1882 InvalidDecl = true;
1883 NewFD->setInvalidDecl();
1884 }
1885 } else if (D.getKind() == Declarator::DK_Conversion) {
1886 if (!DC->isRecord()) {
1887 Diag(D.getIdentifierLoc(),
1888 diag::err_conv_function_not_member);
1889 return 0;
1890 } else {
1891 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1892
1893 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1894 D.getIdentifierLoc(), Name, R,
1895 isInline, isExplicit);
1896
1897 if (InvalidDecl)
1898 NewFD->setInvalidDecl();
1899 }
1900 } else if (DC->isRecord()) {
1901 // This is a C++ method declaration.
1902 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1903 D.getIdentifierLoc(), Name, R,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001904 (SC == FunctionDecl::Static), isInline);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001905 } else {
1906 NewFD = FunctionDecl::Create(Context, DC,
1907 D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001908 Name, R, SC, isInline,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001909 // FIXME: Move to DeclGroup...
1910 D.getDeclSpec().getSourceRange().getBegin());
1911 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001912 NewFD->setNextDeclarator(LastDeclarator);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001913
1914 // Set the lexical context. If the declarator has a C++
1915 // scope specifier, the lexical context will be different
1916 // from the semantic context.
1917 NewFD->setLexicalDeclContext(CurContext);
1918
1919 // Handle GNU asm-label extension (encoded as an attribute).
1920 if (Expr *E = (Expr*) D.getAsmLabel()) {
1921 // The parser guarantees this is a string.
1922 StringLiteral *SE = cast<StringLiteral>(E);
1923 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1924 SE->getByteLength())));
1925 }
1926
1927 // Copy the parameter declarations from the declarator D to
1928 // the function declaration NewFD, if they are available.
1929 if (D.getNumTypeObjects() > 0) {
1930 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1931
1932 // Create Decl objects for each parameter, adding them to the
1933 // FunctionDecl.
1934 llvm::SmallVector<ParmVarDecl*, 16> Params;
1935
1936 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1937 // function that takes no arguments, not a function that takes a
1938 // single void argument.
1939 // We let through "const void" here because Sema::GetTypeForDeclarator
1940 // already checks for that case.
1941 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1942 FTI.ArgInfo[0].Param &&
1943 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1944 // empty arg list, don't push any params.
1945 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1946
1947 // In C++, the empty parameter-type-list must be spelled "void"; a
1948 // typedef of void is not permitted.
1949 if (getLangOptions().CPlusPlus &&
1950 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1951 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1952 }
1953 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1954 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1955 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1956 }
1957
1958 NewFD->setParams(Context, &Params[0], Params.size());
1959 } else if (R->getAsTypedefType()) {
1960 // When we're declaring a function with a typedef, as in the
1961 // following example, we'll need to synthesize (unnamed)
1962 // parameters for use in the declaration.
1963 //
1964 // @code
1965 // typedef void fn(int);
1966 // fn f;
1967 // @endcode
1968 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1969 if (!FT) {
1970 // This is a typedef of a function with no prototype, so we
1971 // don't need to do anything.
1972 } else if ((FT->getNumArgs() == 0) ||
1973 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1974 FT->getArgType(0)->isVoidType())) {
1975 // This is a zero-argument function. We don't need to do anything.
1976 } else {
1977 // Synthesize a parameter for each argument type.
1978 llvm::SmallVector<ParmVarDecl*, 16> Params;
1979 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1980 ArgType != FT->arg_type_end(); ++ArgType) {
Douglas Gregor450da982009-02-16 20:58:07 +00001981 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC,
1982 SourceLocation(), 0,
1983 *ArgType, VarDecl::None,
1984 0);
1985 Param->setImplicit();
1986 Params.push_back(Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001987 }
1988
1989 NewFD->setParams(Context, &Params[0], Params.size());
1990 }
1991 }
1992
1993 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1994 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1995 else if (isa<CXXDestructorDecl>(NewFD)) {
1996 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1997 Record->setUserDeclaredDestructor(true);
1998 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1999 // user-defined destructor.
2000 Record->setPOD(false);
2001 } else if (CXXConversionDecl *Conversion =
2002 dyn_cast<CXXConversionDecl>(NewFD))
2003 ActOnConversionDeclarator(Conversion);
2004
2005 // Extra checking for C++ overloaded operators (C++ [over.oper]).
2006 if (NewFD->isOverloadedOperator() &&
2007 CheckOverloadedOperatorDeclaration(NewFD))
2008 NewFD->setInvalidDecl();
2009
Douglas Gregor8f301052009-02-24 19:23:27 +00002010 // If name lookup finds a previous declaration that is not in the
2011 // same scope as the new declaration, this may still be an
2012 // acceptable redeclaration.
2013 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002014 !(NewFD->hasLinkage() &&
2015 isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
Douglas Gregor8f301052009-02-24 19:23:27 +00002016 PrevDecl = 0;
Douglas Gregor04495c82009-02-24 01:23:02 +00002017
2018 // Merge or overload the declaration with an existing declaration of
2019 // the same name, if appropriate.
Douglas Gregorf9201e02009-02-11 23:02:49 +00002020 bool OverloadableAttrRequired = false;
Douglas Gregor04495c82009-02-24 01:23:02 +00002021 if (PrevDecl) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00002022 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002023 // a declaration that requires merging. If it's an overload,
2024 // there's no more work to do here; we'll just add the new
2025 // function to the scope.
2026 OverloadedFunctionDecl::function_iterator MatchedDecl;
Douglas Gregorae170942009-02-13 00:26:38 +00002027
2028 if (!getLangOptions().CPlusPlus &&
Douglas Gregorc6666f82009-02-18 06:34:51 +00002029 AllowOverloadingOfFunction(PrevDecl, Context)) {
Douglas Gregorae170942009-02-13 00:26:38 +00002030 OverloadableAttrRequired = true;
2031
Douglas Gregorc6666f82009-02-18 06:34:51 +00002032 // Functions marked "overloadable" must have a prototype (that
2033 // we can't get through declaration merging).
2034 if (!R->getAsFunctionTypeProto()) {
2035 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_no_prototype)
2036 << NewFD;
2037 InvalidDecl = true;
2038 Redeclaration = true;
2039
2040 // Turn this into a variadic function with no parameters.
2041 R = Context.getFunctionType(R->getAsFunctionType()->getResultType(),
2042 0, 0, true, 0);
2043 NewFD->setType(R);
2044 }
2045 }
2046
2047 if (PrevDecl &&
2048 (!AllowOverloadingOfFunction(PrevDecl, Context) ||
2049 !IsOverload(NewFD, PrevDecl, MatchedDecl))) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00002050 Redeclaration = true;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002051 Decl *OldDecl = PrevDecl;
2052
2053 // If PrevDecl was an overloaded function, extract the
2054 // FunctionDecl that matched.
2055 if (isa<OverloadedFunctionDecl>(PrevDecl))
2056 OldDecl = *MatchedDecl;
2057
2058 // NewFD and PrevDecl represent declarations that need to be
2059 // merged.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002060 if (MergeFunctionDecl(NewFD, OldDecl))
2061 InvalidDecl = true;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002062
Douglas Gregorcda9c672009-02-16 17:45:42 +00002063 if (!InvalidDecl) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002064 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
2065
2066 // An out-of-line member function declaration must also be a
2067 // definition (C++ [dcl.meaning]p1).
2068 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
2069 !InvalidDecl) {
2070 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
2071 << D.getCXXScopeSpec().getRange();
2072 NewFD->setInvalidDecl();
2073 }
2074 }
2075 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002076 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002077
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002078 if (D.getCXXScopeSpec().isSet() &&
2079 (!PrevDecl || !Redeclaration)) {
2080 // The user tried to provide an out-of-line definition for a
2081 // function that is a member of a class or namespace, but there
2082 // was no such member function declared (C++ [class.mfct]p2,
2083 // C++ [namespace.memdef]p2). For example:
2084 //
2085 // class X {
2086 // void f() const;
2087 // };
2088 //
2089 // void X::f() { } // ill-formed
2090 //
2091 // Complain about this problem, and attempt to suggest close
2092 // matches (e.g., those that differ only in cv-qualifiers and
2093 // whether the parameter types are references).
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002094 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
Douglas Gregor4b99bae2009-02-06 22:58:38 +00002095 << cast<NamedDecl>(DC) << D.getCXXScopeSpec().getRange();
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002096 InvalidDecl = true;
2097
2098 LookupResult Prev = LookupQualifiedName(DC, Name, LookupOrdinaryName,
2099 true);
2100 assert(!Prev.isAmbiguous() &&
2101 "Cannot have an ambiguity in previous-declaration lookup");
2102 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
2103 Func != FuncEnd; ++Func) {
2104 if (isa<FunctionDecl>(*Func) &&
2105 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
2106 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002107 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002108
2109 PrevDecl = 0;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002110 }
Douglas Gregord8635172009-02-02 21:35:47 +00002111
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002112 // Handle attributes. We need to have merged decls when handling attributes
2113 // (for example to check for conflicts, etc).
2114 ProcessDeclAttributes(NewFD, D);
Douglas Gregor3c385e52009-02-14 18:57:46 +00002115 AddKnownFunctionAttributes(NewFD);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002116
Douglas Gregorf9201e02009-02-11 23:02:49 +00002117 if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
2118 // If a function name is overloadable in C, then every function
2119 // with that name must be marked "overloadable".
2120 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
Douglas Gregorae170942009-02-13 00:26:38 +00002121 << Redeclaration << NewFD;
Douglas Gregorf9201e02009-02-11 23:02:49 +00002122 if (PrevDecl)
2123 Diag(PrevDecl->getLocation(),
2124 diag::note_attribute_overloadable_prev_overload);
2125 NewFD->addAttr(new OverloadableAttr);
2126 }
2127
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002128 if (getLangOptions().CPlusPlus) {
Sebastian Redl00d50742009-02-08 14:56:26 +00002129 // In C++, check default arguments now that we have merged decls. Unless
2130 // the lexical context is the class, because in this case this is done
2131 // during delayed parsing anyway.
2132 if (!CurContext->isRecord())
2133 CheckCXXDefaultArguments(NewFD);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002134
2135 // An out-of-line member function declaration must also be a
2136 // definition (C++ [dcl.meaning]p1).
2137 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
2138 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
2139 << D.getCXXScopeSpec().getRange();
2140 InvalidDecl = true;
2141 }
2142 }
Douglas Gregor25d944a2009-02-24 04:26:15 +00002143
Douglas Gregor8f301052009-02-24 19:23:27 +00002144 // If this is a locally-scoped function in C, inject a declaration
2145 // into translation unit scope so that all external declarations are
2146 // visible.
2147 if (!getLangOptions().CPlusPlus && CurContext->isFunctionOrMethod())
2148 InjectLocallyScopedExternalDeclaration(NewFD);
Douglas Gregor25d944a2009-02-24 04:26:15 +00002149
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002150 return NewFD;
2151}
2152
Steve Naroff6594a702008-10-27 11:34:16 +00002153void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002154 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
2155 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00002156}
2157
Eli Friedmanc594b322008-05-20 13:48:25 +00002158bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
2159 switch (Init->getStmtClass()) {
2160 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002161 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002162 return true;
2163 case Expr::ParenExprClass: {
2164 const ParenExpr* PE = cast<ParenExpr>(Init);
2165 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
2166 }
2167 case Expr::CompoundLiteralExprClass:
2168 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor1a49af92009-01-06 05:10:23 +00002169 case Expr::DeclRefExprClass:
2170 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002171 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00002172 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2173 if (VD->hasGlobalStorage())
2174 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002175 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00002176 return true;
2177 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002178 if (isa<FunctionDecl>(D))
2179 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002180 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00002181 return true;
2182 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002183 case Expr::MemberExprClass: {
2184 const MemberExpr *M = cast<MemberExpr>(Init);
2185 if (M->isArrow())
2186 return CheckAddressConstantExpression(M->getBase());
2187 return CheckAddressConstantExpressionLValue(M->getBase());
2188 }
2189 case Expr::ArraySubscriptExprClass: {
2190 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
2191 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
2192 return CheckAddressConstantExpression(ASE->getBase()) ||
2193 CheckArithmeticConstantExpression(ASE->getIdx());
2194 }
2195 case Expr::StringLiteralClass:
Chris Lattner111c2ee2009-02-24 21:54:33 +00002196 case Expr::ObjCEncodeExprClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00002197 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00002198 return false;
2199 case Expr::UnaryOperatorClass: {
2200 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2201
2202 // C99 6.6p9
2203 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00002204 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00002205
Steve Naroff6594a702008-10-27 11:34:16 +00002206 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002207 return true;
2208 }
2209 }
2210}
2211
2212bool Sema::CheckAddressConstantExpression(const Expr* Init) {
2213 switch (Init->getStmtClass()) {
2214 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002215 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002216 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00002217 case Expr::ParenExprClass:
2218 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00002219 case Expr::StringLiteralClass:
Chris Lattner111c2ee2009-02-24 21:54:33 +00002220 case Expr::ObjCEncodeExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00002221 case Expr::ObjCStringLiteralClass:
2222 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00002223 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00002224 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00002225 // __builtin___CFStringMakeConstantString is a valid constant l-value.
Douglas Gregor3c385e52009-02-14 18:57:46 +00002226 if (cast<CallExpr>(Init)->isBuiltinCall(Context) ==
Chris Lattner506ff882008-10-06 07:26:43 +00002227 Builtin::BI__builtin___CFStringMakeConstantString)
2228 return false;
2229
Steve Naroff6594a702008-10-27 11:34:16 +00002230 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00002231 return true;
2232
Eli Friedmanc594b322008-05-20 13:48:25 +00002233 case Expr::UnaryOperatorClass: {
2234 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2235
2236 // C99 6.6p9
2237 if (Exp->getOpcode() == UnaryOperator::AddrOf)
2238 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
2239
2240 if (Exp->getOpcode() == UnaryOperator::Extension)
2241 return CheckAddressConstantExpression(Exp->getSubExpr());
2242
Steve Naroff6594a702008-10-27 11:34:16 +00002243 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002244 return true;
2245 }
2246 case Expr::BinaryOperatorClass: {
2247 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
2248 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2249
2250 Expr *PExp = Exp->getLHS();
2251 Expr *IExp = Exp->getRHS();
2252 if (IExp->getType()->isPointerType())
2253 std::swap(PExp, IExp);
2254
2255 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
2256 return CheckAddressConstantExpression(PExp) ||
2257 CheckArithmeticConstantExpression(IExp);
2258 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00002259 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002260 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002261 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00002262 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
2263 // Check for implicit promotion
2264 if (SubExpr->getType()->isFunctionType() ||
2265 SubExpr->getType()->isArrayType())
2266 return CheckAddressConstantExpressionLValue(SubExpr);
2267 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002268
2269 // Check for pointer->pointer cast
2270 if (SubExpr->getType()->isPointerType())
2271 return CheckAddressConstantExpression(SubExpr);
2272
Eli Friedmanc3f07642008-08-25 20:46:57 +00002273 if (SubExpr->getType()->isIntegralType()) {
2274 // Check for the special-case of a pointer->int->pointer cast;
2275 // this isn't standard, but some code requires it. See
2276 // PR2720 for an example.
2277 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
2278 if (SubCast->getSubExpr()->getType()->isPointerType()) {
2279 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
2280 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2281 if (IntWidth >= PointerWidth) {
2282 return CheckAddressConstantExpression(SubCast->getSubExpr());
2283 }
2284 }
2285 }
2286 }
2287 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00002288 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00002289 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002290
Steve Naroff6594a702008-10-27 11:34:16 +00002291 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002292 return true;
2293 }
2294 case Expr::ConditionalOperatorClass: {
2295 // FIXME: Should we pedwarn here?
2296 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
2297 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00002298 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002299 return true;
2300 }
2301 if (CheckArithmeticConstantExpression(Exp->getCond()))
2302 return true;
2303 if (Exp->getLHS() &&
2304 CheckAddressConstantExpression(Exp->getLHS()))
2305 return true;
2306 return CheckAddressConstantExpression(Exp->getRHS());
2307 }
2308 case Expr::AddrLabelExprClass:
2309 return false;
2310 }
2311}
2312
Eli Friedman4caf0552008-06-09 05:05:07 +00002313static const Expr* FindExpressionBaseAddress(const Expr* E);
2314
2315static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
2316 switch (E->getStmtClass()) {
2317 default:
2318 return E;
2319 case Expr::ParenExprClass: {
2320 const ParenExpr* PE = cast<ParenExpr>(E);
2321 return FindExpressionBaseAddressLValue(PE->getSubExpr());
2322 }
2323 case Expr::MemberExprClass: {
2324 const MemberExpr *M = cast<MemberExpr>(E);
2325 if (M->isArrow())
2326 return FindExpressionBaseAddress(M->getBase());
2327 return FindExpressionBaseAddressLValue(M->getBase());
2328 }
2329 case Expr::ArraySubscriptExprClass: {
2330 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
2331 return FindExpressionBaseAddress(ASE->getBase());
2332 }
2333 case Expr::UnaryOperatorClass: {
2334 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2335
2336 if (Exp->getOpcode() == UnaryOperator::Deref)
2337 return FindExpressionBaseAddress(Exp->getSubExpr());
2338
2339 return E;
2340 }
2341 }
2342}
2343
2344static const Expr* FindExpressionBaseAddress(const Expr* E) {
2345 switch (E->getStmtClass()) {
2346 default:
2347 return E;
2348 case Expr::ParenExprClass: {
2349 const ParenExpr* PE = cast<ParenExpr>(E);
2350 return FindExpressionBaseAddress(PE->getSubExpr());
2351 }
2352 case Expr::UnaryOperatorClass: {
2353 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2354
2355 // C99 6.6p9
2356 if (Exp->getOpcode() == UnaryOperator::AddrOf)
2357 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
2358
2359 if (Exp->getOpcode() == UnaryOperator::Extension)
2360 return FindExpressionBaseAddress(Exp->getSubExpr());
2361
2362 return E;
2363 }
2364 case Expr::BinaryOperatorClass: {
2365 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2366
2367 Expr *PExp = Exp->getLHS();
2368 Expr *IExp = Exp->getRHS();
2369 if (IExp->getType()->isPointerType())
2370 std::swap(PExp, IExp);
2371
2372 return FindExpressionBaseAddress(PExp);
2373 }
2374 case Expr::ImplicitCastExprClass: {
2375 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
2376
2377 // Check for implicit promotion
2378 if (SubExpr->getType()->isFunctionType() ||
2379 SubExpr->getType()->isArrayType())
2380 return FindExpressionBaseAddressLValue(SubExpr);
2381
2382 // Check for pointer->pointer cast
2383 if (SubExpr->getType()->isPointerType())
2384 return FindExpressionBaseAddress(SubExpr);
2385
2386 // We assume that we have an arithmetic expression here;
2387 // if we don't, we'll figure it out later
2388 return 0;
2389 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002390 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00002391 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2392
2393 // Check for pointer->pointer cast
2394 if (SubExpr->getType()->isPointerType())
2395 return FindExpressionBaseAddress(SubExpr);
2396
2397 // We assume that we have an arithmetic expression here;
2398 // if we don't, we'll figure it out later
2399 return 0;
2400 }
2401 }
2402}
2403
Anders Carlsson51fe9962008-11-22 21:04:56 +00002404bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00002405 switch (Init->getStmtClass()) {
2406 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002407 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002408 return true;
2409 case Expr::ParenExprClass: {
2410 const ParenExpr* PE = cast<ParenExpr>(Init);
2411 return CheckArithmeticConstantExpression(PE->getSubExpr());
2412 }
2413 case Expr::FloatingLiteralClass:
2414 case Expr::IntegerLiteralClass:
2415 case Expr::CharacterLiteralClass:
2416 case Expr::ImaginaryLiteralClass:
2417 case Expr::TypesCompatibleExprClass:
2418 case Expr::CXXBoolLiteralExprClass:
2419 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00002420 case Expr::CallExprClass:
2421 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002422 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002423
2424 // Allow any constant foldable calls to builtins.
Douglas Gregor3c385e52009-02-14 18:57:46 +00002425 if (CE->isBuiltinCall(Context) && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00002426 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002427
Steve Naroff6594a702008-10-27 11:34:16 +00002428 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002429 return true;
2430 }
Douglas Gregor1a49af92009-01-06 05:10:23 +00002431 case Expr::DeclRefExprClass:
2432 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002433 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2434 if (isa<EnumConstantDecl>(D))
2435 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002436 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002437 return true;
2438 }
2439 case Expr::CompoundLiteralExprClass:
2440 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2441 // but vectors are allowed to be magic.
2442 if (Init->getType()->isVectorType())
2443 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002444 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002445 return true;
2446 case Expr::UnaryOperatorClass: {
2447 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2448
2449 switch (Exp->getOpcode()) {
2450 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2451 // See C99 6.6p3.
2452 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002453 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002454 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002455 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00002456 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2457 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002458 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002459 return true;
2460 case UnaryOperator::Extension:
2461 case UnaryOperator::LNot:
2462 case UnaryOperator::Plus:
2463 case UnaryOperator::Minus:
2464 case UnaryOperator::Not:
2465 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2466 }
2467 }
Sebastian Redl05189992008-11-11 17:56:53 +00002468 case Expr::SizeOfAlignOfExprClass: {
2469 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002470 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00002471 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00002472 return false;
2473 // alignof always evaluates to a constant.
2474 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00002475 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00002476 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002477 return true;
2478 }
2479 return false;
2480 }
2481 case Expr::BinaryOperatorClass: {
2482 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2483
2484 if (Exp->getLHS()->getType()->isArithmeticType() &&
2485 Exp->getRHS()->getType()->isArithmeticType()) {
2486 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2487 CheckArithmeticConstantExpression(Exp->getRHS());
2488 }
2489
Eli Friedman4caf0552008-06-09 05:05:07 +00002490 if (Exp->getLHS()->getType()->isPointerType() &&
2491 Exp->getRHS()->getType()->isPointerType()) {
2492 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2493 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2494
2495 // Only allow a null (constant integer) base; we could
2496 // allow some additional cases if necessary, but this
2497 // is sufficient to cover offsetof-like constructs.
2498 if (!LHSBase && !RHSBase) {
2499 return CheckAddressConstantExpression(Exp->getLHS()) ||
2500 CheckAddressConstantExpression(Exp->getRHS());
2501 }
2502 }
2503
Steve Naroff6594a702008-10-27 11:34:16 +00002504 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002505 return true;
2506 }
2507 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002508 case Expr::CStyleCastExprClass: {
Nuno Lopesff776452009-02-02 22:57:15 +00002509 const CastExpr *CE = cast<CastExpr>(Init);
2510 const Expr *SubExpr = CE->getSubExpr();
2511
Eli Friedman6d4abe12008-09-01 22:08:17 +00002512 if (SubExpr->getType()->isArithmeticType())
2513 return CheckArithmeticConstantExpression(SubExpr);
2514
Eli Friedmanb529d832008-09-02 09:37:00 +00002515 if (SubExpr->getType()->isPointerType()) {
2516 const Expr* Base = FindExpressionBaseAddress(SubExpr);
Nuno Lopesff776452009-02-02 22:57:15 +00002517 if (Base) {
2518 // the cast is only valid if done to a wide enough type
2519 if (Context.getTypeSize(CE->getType()) >=
2520 Context.getTypeSize(SubExpr->getType()))
2521 return false;
2522 } else {
2523 // If the pointer has a null base, this is an offsetof-like construct
2524 return CheckAddressConstantExpression(SubExpr);
2525 }
Eli Friedmanb529d832008-09-02 09:37:00 +00002526 }
2527
Steve Naroff6594a702008-10-27 11:34:16 +00002528 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00002529 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002530 }
2531 case Expr::ConditionalOperatorClass: {
2532 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00002533
2534 // If GNU extensions are disabled, we require all operands to be arithmetic
2535 // constant expressions.
2536 if (getLangOptions().NoExtensions) {
2537 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2538 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2539 CheckArithmeticConstantExpression(Exp->getRHS());
2540 }
2541
2542 // Otherwise, we have to emulate some of the behavior of fold here.
2543 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2544 // because it can constant fold things away. To retain compatibility with
2545 // GCC code, we see if we can fold the condition to a constant (which we
2546 // should always be able to do in theory). If so, we only require the
2547 // specified arm of the conditional to be a constant. This is a horrible
2548 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002549 Expr::EvalResult EvalResult;
2550 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2551 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002552 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00002553 // won't be able to either. Use it to emit the diagnostic though.
2554 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002555 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00002556 return Res;
2557 }
2558
2559 // Verify that the side following the condition is also a constant.
2560 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002561 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00002562 std::swap(TrueSide, FalseSide);
2563
2564 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00002565 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00002566
2567 // Okay, the evaluated side evaluates to a constant, so we accept this.
2568 // Check to see if the other side is obviously not a constant. If so,
2569 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002570 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00002571 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002572 diag::ext_typecheck_expression_not_constant_but_accepted)
2573 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00002574 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00002575 }
2576 }
2577}
2578
2579bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Chris Lattner111c2ee2009-02-24 21:54:33 +00002580 if (Init->isConstantInitializer(Context))
Eli Friedman578a9722009-02-22 06:45:27 +00002581 return false;
Eli Friedman578a9722009-02-22 06:45:27 +00002582 InitializerElementNotConstant(Init);
2583 return true;
2584
Douglas Gregor05c13a32009-01-22 00:58:24 +00002585 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init))
2586 Init = DIE->getInit();
2587
Nuno Lopes9a979c32008-07-07 16:46:50 +00002588 Init = Init->IgnoreParens();
2589
Nate Begeman59b5da62009-01-18 03:20:47 +00002590 if (Init->isEvaluatable(Context))
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002591 return false;
2592
Eli Friedmanc594b322008-05-20 13:48:25 +00002593 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2594 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2595 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2596
Nuno Lopes9a979c32008-07-07 16:46:50 +00002597 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2598 return CheckForConstantInitializer(e->getInitializer(), DclT);
2599
Douglas Gregor3498bdb2009-01-29 17:44:32 +00002600 if (isa<ImplicitValueInitExpr>(Init)) {
2601 // FIXME: In C++, check for non-POD types.
2602 return false;
2603 }
2604
Eli Friedmanc594b322008-05-20 13:48:25 +00002605 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2606 unsigned numInits = Exp->getNumInits();
2607 for (unsigned i = 0; i < numInits; i++) {
2608 // FIXME: Need to get the type of the declaration for C++,
2609 // because it could be a reference?
Douglas Gregor4c678342009-01-28 21:54:33 +00002610
Eli Friedmanc594b322008-05-20 13:48:25 +00002611 if (CheckForConstantInitializer(Exp->getInit(i),
2612 Exp->getInit(i)->getType()))
2613 return true;
2614 }
2615 return false;
2616 }
2617
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002618 // FIXME: We can probably remove some of this code below, now that
2619 // Expr::Evaluate is doing the heavy lifting for scalars.
2620
Eli Friedmanc594b322008-05-20 13:48:25 +00002621 if (Init->isNullPointerConstant(Context))
2622 return false;
2623 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002624 QualType InitTy = Context.getCanonicalType(Init->getType())
2625 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002626 if (InitTy == Context.BoolTy) {
2627 // Special handling for pointers implicitly cast to bool;
2628 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2629 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2630 Expr* SubE = ICE->getSubExpr();
2631 if (SubE->getType()->isPointerType() ||
2632 SubE->getType()->isArrayType() ||
2633 SubE->getType()->isFunctionType()) {
2634 return CheckAddressConstantExpression(Init);
2635 }
2636 }
2637 } else if (InitTy->isIntegralType()) {
2638 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002639 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002640 SubE = CE->getSubExpr();
2641 // Special check for pointer cast to int; we allow as an extension
2642 // an address constant cast to an integer if the integer
2643 // is of an appropriate width (this sort of code is apparently used
2644 // in some places).
2645 // FIXME: Add pedwarn?
2646 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2647 if (SubE && (SubE->getType()->isPointerType() ||
2648 SubE->getType()->isArrayType() ||
2649 SubE->getType()->isFunctionType())) {
2650 unsigned IntWidth = Context.getTypeSize(Init->getType());
2651 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2652 if (IntWidth >= PointerWidth)
2653 return CheckAddressConstantExpression(Init);
2654 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002655 }
2656
2657 return CheckArithmeticConstantExpression(Init);
2658 }
2659
2660 if (Init->getType()->isPointerType())
2661 return CheckAddressConstantExpression(Init);
2662
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002663 // An array type at the top level that isn't an init-list must
2664 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002665 if (Init->getType()->isArrayType())
2666 return false;
2667
Nuno Lopes73419bf2008-09-01 18:42:41 +00002668 if (Init->getType()->isFunctionType())
2669 return false;
2670
Steve Naroff8af6a452008-10-02 17:12:56 +00002671 // Allow block exprs at top level.
2672 if (Init->getType()->isBlockPointerType())
2673 return false;
Nuno Lopes6ed2ef82009-01-15 16:44:45 +00002674
2675 // GCC cast to union extension
2676 // note: the validity of the cast expr is checked by CheckCastTypes()
2677 if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2678 QualType T = C->getType();
2679 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2680 }
2681
Steve Naroff6594a702008-10-27 11:34:16 +00002682 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002683 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002684}
2685
Sebastian Redl798d1192008-12-13 16:23:55 +00002686void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002687 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2688}
2689
2690/// AddInitializerToDecl - Adds the initializer Init to the
2691/// declaration dcl. If DirectInit is true, this is C++ direct
2692/// initialization rather than copy initialization.
2693void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002694 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002695 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002696 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002697
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002698 // If there is no declaration, there was an error parsing it. Just ignore
2699 // the initializer.
2700 if (RealDecl == 0) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00002701 Init->Destroy(Context);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002702 return;
2703 }
Steve Naroffbb204692007-09-12 14:07:44 +00002704
Steve Naroff410e3e22007-09-12 20:13:48 +00002705 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2706 if (!VDecl) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002707 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002708 RealDecl->setInvalidDecl();
2709 return;
2710 }
Steve Naroffbb204692007-09-12 14:07:44 +00002711 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002712 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002713 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002714 if (VDecl->isBlockVarDecl()) {
2715 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002716 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002717 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002718 VDecl->setInvalidDecl();
2719 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002720 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002721 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002722 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002723
2724 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmanda153232009-02-20 01:34:21 +00002725 // Don't check invalid declarations to avoid emitting useless diagnostics.
2726 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002727 if (SC == VarDecl::Static) // C99 6.7.8p4.
2728 CheckForConstantInitializer(Init, DclT);
2729 }
Steve Naroffbb204692007-09-12 14:07:44 +00002730 }
Steve Naroff248a7532008-04-15 22:42:06 +00002731 } else if (VDecl->isFileVarDecl()) {
2732 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002733 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002734 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002735 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002736 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002737 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002738
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002739 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmanda153232009-02-20 01:34:21 +00002740 // Don't check invalid declarations to avoid emitting useless diagnostics.
2741 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002742 // C99 6.7.8p4. All file scoped initializers need to be constant.
2743 CheckForConstantInitializer(Init, DclT);
2744 }
Steve Naroffbb204692007-09-12 14:07:44 +00002745 }
2746 // If the type changed, it means we had an incomplete type that was
2747 // completed by the initializer. For example:
2748 // int ary[] = { 1, 3, 5 };
2749 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002750 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002751 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002752 Init->setType(DclT);
2753 }
Steve Naroffbb204692007-09-12 14:07:44 +00002754
2755 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002756 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002757 return;
2758}
2759
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002760void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2761 Decl *RealDecl = static_cast<Decl *>(dcl);
2762
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002763 // If there is no declaration, there was an error parsing it. Just ignore it.
2764 if (RealDecl == 0)
2765 return;
2766
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002767 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2768 QualType Type = Var->getType();
2769 // C++ [dcl.init.ref]p3:
2770 // The initializer can be omitted for a reference only in a
2771 // parameter declaration (8.3.5), in the declaration of a
2772 // function return type, in the declaration of a class member
2773 // within its class declaration (9.2), and where the extern
2774 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002775 if (Type->isReferenceType() &&
2776 Var->getStorageClass() != VarDecl::Extern &&
2777 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002778 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002779 << Var->getDeclName()
2780 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002781 Var->setInvalidDecl();
2782 return;
2783 }
2784
2785 // C++ [dcl.init]p9:
2786 //
2787 // If no initializer is specified for an object, and the object
2788 // is of (possibly cv-qualified) non-POD class type (or array
2789 // thereof), the object shall be default-initialized; if the
2790 // object is of const-qualified type, the underlying class type
2791 // shall have a user-declared default constructor.
2792 if (getLangOptions().CPlusPlus) {
2793 QualType InitType = Type;
2794 if (const ArrayType *Array = Context.getAsArrayType(Type))
2795 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002796 if (Var->getStorageClass() != VarDecl::Extern &&
2797 Var->getStorageClass() != VarDecl::PrivateExtern &&
2798 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002799 const CXXConstructorDecl *Constructor
2800 = PerformInitializationByConstructor(InitType, 0, 0,
2801 Var->getLocation(),
2802 SourceRange(Var->getLocation(),
2803 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002804 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002805 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002806 if (!Constructor)
2807 Var->setInvalidDecl();
2808 }
2809 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002810
Douglas Gregor818ce482008-10-29 13:50:18 +00002811#if 0
2812 // FIXME: Temporarily disabled because we are not properly parsing
2813 // linkage specifications on declarations, e.g.,
2814 //
2815 // extern "C" const CGPoint CGPointerZero;
2816 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002817 // C++ [dcl.init]p9:
2818 //
2819 // If no initializer is specified for an object, and the
2820 // object is of (possibly cv-qualified) non-POD class type (or
2821 // array thereof), the object shall be default-initialized; if
2822 // the object is of const-qualified type, the underlying class
2823 // type shall have a user-declared default
2824 // constructor. Otherwise, if no initializer is specified for
2825 // an object, the object and its subobjects, if any, have an
2826 // indeterminate initial value; if the object or any of its
2827 // subobjects are of const-qualified type, the program is
2828 // ill-formed.
2829 //
2830 // This isn't technically an error in C, so we don't diagnose it.
2831 //
2832 // FIXME: Actually perform the POD/user-defined default
2833 // constructor check.
2834 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002835 Context.getCanonicalType(Type).isConstQualified() &&
2836 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002837 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2838 << Var->getName()
2839 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002840#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002841 }
2842}
2843
Reid Spencer5f016e22007-07-11 17:01:13 +00002844/// The declarators are chained together backwards, reverse the list.
2845Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2846 // Often we have single declarators, handle them quickly.
Argyrios Kyrtzidisd311f372009-02-17 20:23:54 +00002847 Decl *Group = static_cast<Decl*>(group);
2848 if (Group == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002849 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002850
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002851 Decl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002852 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002853 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002854 else { // reverse the list.
2855 while (Group) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002856 Decl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002857 Group->setNextDeclarator(NewGroup);
2858 NewGroup = Group;
2859 Group = Next;
2860 }
2861 }
2862 // Perform semantic analysis that depends on having fully processed both
2863 // the declarator and initializer.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002864 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002865 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2866 if (!IDecl)
2867 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002868 QualType T = IDecl->getType();
2869
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002870 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002871 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002872
2873 // FIXME: This won't give the correct result for
2874 // int a[10][n];
2875 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002876 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002877 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2878 SizeRange;
2879
Eli Friedmanc5773c42008-02-15 18:16:39 +00002880 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002881 } else {
2882 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2883 // static storage duration, it shall not have a variable length array.
2884 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002885 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2886 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002887 IDecl->setInvalidDecl();
2888 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002889 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2890 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002891 IDecl->setInvalidDecl();
2892 }
2893 }
2894 } else if (T->isVariablyModifiedType()) {
2895 if (IDecl->isFileVarDecl()) {
2896 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2897 IDecl->setInvalidDecl();
2898 } else {
2899 if (IDecl->getStorageClass() == VarDecl::Extern) {
2900 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2901 IDecl->setInvalidDecl();
2902 }
Steve Naroffbb204692007-09-12 14:07:44 +00002903 }
2904 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002905
Steve Naroffbb204692007-09-12 14:07:44 +00002906 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2907 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002908 if (IDecl->isBlockVarDecl() &&
2909 IDecl->getStorageClass() != VarDecl::Extern) {
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002910 if (!IDecl->isInvalidDecl() &&
2911 DiagnoseIncompleteType(IDecl->getLocation(), T,
2912 diag::err_typecheck_decl_incomplete_type))
Steve Naroffbb204692007-09-12 14:07:44 +00002913 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00002914 }
2915 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2916 // object that has file scope without an initializer, and without a
2917 // storage-class specifier or with the storage-class specifier "static",
2918 // constitutes a tentative definition. Note: A tentative definition with
2919 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002920 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002921 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002922 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2923 // array to be completed. Don't issue a diagnostic.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002924 } else if (!IDecl->isInvalidDecl() &&
2925 DiagnoseIncompleteType(IDecl->getLocation(), T,
2926 diag::err_typecheck_decl_incomplete_type))
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002927 // C99 6.9.2p3: If the declaration of an identifier for an object is
2928 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2929 // declared type shall not be an incomplete type.
Steve Naroffbb204692007-09-12 14:07:44 +00002930 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00002931 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002932 if (IDecl->isFileVarDecl())
2933 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002934 }
2935 return NewGroup;
2936}
Steve Naroffe1223f72007-08-28 03:03:08 +00002937
Chris Lattner04421082008-04-08 04:40:51 +00002938/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2939/// to introduce parameters into function prototype scope.
2940Sema::DeclTy *
2941Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002942 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002943
Chris Lattner04421082008-04-08 04:40:51 +00002944 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002945 VarDecl::StorageClass StorageClass = VarDecl::None;
2946 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2947 StorageClass = VarDecl::Register;
2948 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002949 Diag(DS.getStorageClassSpecLoc(),
2950 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002951 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002952 }
2953 if (DS.isThreadSpecified()) {
2954 Diag(DS.getThreadSpecLoc(),
2955 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002956 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002957 }
2958
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002959 // Check that there are no default arguments inside the type of this
2960 // parameter (C++ only).
2961 if (getLangOptions().CPlusPlus)
2962 CheckExtraCXXDefaultArguments(D);
2963
Chris Lattner04421082008-04-08 04:40:51 +00002964 // In this context, we *do not* check D.getInvalidType(). If the declarator
2965 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2966 // though it will not reflect the user specified type.
2967 QualType parmDeclType = GetTypeForDeclarator(D, S);
2968
2969 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2970
Reid Spencer5f016e22007-07-11 17:01:13 +00002971 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2972 // Can this happen for params? We already checked that they don't conflict
2973 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002974 IdentifierInfo *II = D.getIdentifier();
Chris Lattnercf79b012009-01-21 02:38:50 +00002975 if (II) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002976 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00002977 if (PrevDecl->isTemplateParameter()) {
2978 // Maybe we will complain about the shadowed template parameter.
2979 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2980 // Just pretend that we didn't see the previous declaration.
2981 PrevDecl = 0;
2982 } else if (S->isDeclScope(PrevDecl)) {
2983 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002984
Chris Lattnercf79b012009-01-21 02:38:50 +00002985 // Recover by removing the name
2986 II = 0;
2987 D.SetIdentifier(0, D.getIdentifierLoc());
2988 }
Chris Lattner04421082008-04-08 04:40:51 +00002989 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002990 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002991
2992 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2993 // Doing the promotion here has a win and a loss. The win is the type for
2994 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2995 // code generator). The loss is the orginal type isn't preserved. For example:
2996 //
2997 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2998 // int blockvardecl[5];
2999 // sizeof(parmvardecl); // size == 4
3000 // sizeof(blockvardecl); // size == 20
3001 // }
3002 //
3003 // For expressions, all implicit conversions are captured using the
3004 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
3005 //
3006 // FIXME: If a source translation tool needs to see the original type, then
3007 // we need to consider storing both types (in ParmVarDecl)...
3008 //
Chris Lattnere6327742008-04-02 05:18:44 +00003009 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00003010 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00003011 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00003012 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00003013 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00003014
Chris Lattner04421082008-04-08 04:40:51 +00003015 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
3016 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00003017 parmDeclType, StorageClass,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003018 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00003019
Chris Lattner04421082008-04-08 04:40:51 +00003020 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00003021 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003022
Douglas Gregor584049d2008-12-15 23:53:10 +00003023 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3024 if (D.getCXXScopeSpec().isSet()) {
3025 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
3026 << D.getCXXScopeSpec().getRange();
3027 New->setInvalidDecl();
3028 }
Steve Naroffccef3712009-02-20 22:59:16 +00003029 // Parameter declarators cannot be interface types. All ObjC objects are
3030 // passed by reference.
3031 if (parmDeclType->isObjCInterfaceType()) {
3032 Diag(D.getIdentifierLoc(), diag::err_object_cannot_be_by_value)
3033 << "passed";
3034 New->setInvalidDecl();
3035 }
Douglas Gregor584049d2008-12-15 23:53:10 +00003036
Douglas Gregor44b43212008-12-11 16:49:14 +00003037 // Add the parameter declaration into this scope.
3038 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003039 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00003040 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00003041
Chris Lattner3ff30c82008-06-29 00:02:00 +00003042 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00003043 return New;
Chris Lattner04421082008-04-08 04:40:51 +00003044
Reid Spencer5f016e22007-07-11 17:01:13 +00003045}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00003046
Douglas Gregorbe109b32009-01-23 16:23:13 +00003047void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003048 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3049 "Not a function declarator!");
3050 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00003051
Reid Spencer5f016e22007-07-11 17:01:13 +00003052 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
3053 // for a K&R function.
3054 if (!FTI.hasPrototype) {
3055 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00003056 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00003057 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
3058 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00003059 // Implicitly declare the argument as type 'int' for lack of a better
3060 // type.
Chris Lattner04421082008-04-08 04:40:51 +00003061 DeclSpec DS;
3062 const char* PrevSpec; // unused
3063 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
3064 PrevSpec);
3065 Declarator ParamD(DS, Declarator::KNRTypeListContext);
3066 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00003067 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00003068 }
3069 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00003070 }
3071}
3072
3073Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
3074 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3075 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3076 "Not a function declarator!");
3077 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3078
3079 if (FTI.hasPrototype) {
Chris Lattner04421082008-04-08 04:40:51 +00003080 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00003081 }
3082
Douglas Gregor584049d2008-12-15 23:53:10 +00003083 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00003084
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003085 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00003086 ActOnDeclarator(ParentScope, D, 0,
3087 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003088}
3089
3090Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
3091 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00003092 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00003093
3094 // See if this is a redefinition.
3095 const FunctionDecl *Definition;
3096 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00003097 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003098 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00003099 }
3100
Douglas Gregorcda9c672009-02-16 17:45:42 +00003101 // Builtin functions cannot be defined.
3102 if (unsigned BuiltinID = FD->getBuiltinID(Context)) {
Douglas Gregor655753a2009-02-17 16:03:01 +00003103 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00003104 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor655753a2009-02-17 16:03:01 +00003105 FD->setInvalidDecl();
3106 }
Douglas Gregorcda9c672009-02-16 17:45:42 +00003107 }
3108
Douglas Gregor44b43212008-12-11 16:49:14 +00003109 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00003110
Chris Lattner04421082008-04-08 04:40:51 +00003111 // Check the validity of our function parameters
3112 CheckParmsForFunctionDef(FD);
3113
3114 // Introduce our parameters into the function scope
3115 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
3116 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00003117 Param->setOwningFunction(FD);
3118
Chris Lattner04421082008-04-08 04:40:51 +00003119 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003120 if (Param->getIdentifier())
3121 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00003122 }
Chris Lattner04421082008-04-08 04:40:51 +00003123
Anton Korobeynikov2f402702008-12-26 00:52:02 +00003124 // Checking attributes of current function definition
3125 // dllimport attribute.
3126 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
3127 // dllimport attribute cannot be applied to definition.
3128 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
3129 Diag(FD->getLocation(),
3130 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
3131 << "dllimport";
3132 FD->setInvalidDecl();
3133 return FD;
3134 } else {
3135 // If a symbol previously declared dllimport is later defined, the
3136 // attribute is ignored in subsequent references, and a warning is
3137 // emitted.
3138 Diag(FD->getLocation(),
3139 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
3140 << FD->getNameAsCString() << "dllimport";
3141 }
3142 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003143 return FD;
3144}
3145
Sebastian Redl798d1192008-12-13 16:23:55 +00003146Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00003147 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00003148 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00003149 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00003150 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00003151 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00003152 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattnerffed1632009-02-16 19:27:54 +00003153 assert(MD == getCurMethodDecl() && "Method parsing confused");
Steve Naroffd6d054d2007-11-11 23:20:51 +00003154 MD->setBody((Stmt*)Body);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003155 } else {
3156 Body->Destroy(Context);
Steve Naroff394f3f42008-07-25 17:57:26 +00003157 return 0;
Ted Kremenek8189cde2009-02-07 01:47:29 +00003158 }
Chris Lattnerb048c982008-04-06 04:47:34 +00003159 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00003160 // Verify and clean out per-function state.
3161
3162 // Check goto/label use.
3163 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
3164 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
3165 // Verify that we have no forward references left. If so, there was a goto
3166 // or address of a label taken, but no definition of it. Label fwd
3167 // definitions are indicated with a null substmt.
3168 if (I->second->getSubStmt() == 0) {
3169 LabelStmt *L = I->second;
3170 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003171 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00003172
3173 // At this point, we have gotos that use the bogus label. Stitch it into
3174 // the function body so that they aren't leaked and that the AST is well
3175 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00003176 if (Body) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00003177#if 0
3178 // FIXME: Why do this? Having a 'push_back' in CompoundStmt is ugly,
3179 // and the AST is malformed anyway. We should just blow away 'L'.
3180 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
3181 cast<CompoundStmt>(Body)->push_back(L);
3182#else
3183 L->Destroy(Context);
3184#endif
Chris Lattner0cbc2152008-01-25 00:01:10 +00003185 } else {
3186 // The whole function wasn't parsed correctly, just delete this.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003187 L->Destroy(Context);
Chris Lattner0cbc2152008-01-25 00:01:10 +00003188 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003189 }
3190 }
3191 LabelMap.clear();
3192
Steve Naroffd6d054d2007-11-11 23:20:51 +00003193 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00003194}
3195
Reid Spencer5f016e22007-07-11 17:01:13 +00003196/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
3197/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003198NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
3199 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00003200 // Extension in C99. Legal in C90, but warn about it.
3201 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00003202 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00003203 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003204 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00003205
3206 // FIXME: handle stuff like:
3207 // void foo() { extern float X(); }
3208 // void bar() { X(); } <-- implicit decl for X in another scope.
3209
3210 // Set a Declarator for the implicit definition: int foo();
3211 const char *Dummy;
3212 DeclSpec DS;
3213 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
3214 Error = Error; // Silence warning.
3215 assert(!Error && "Error setting up implicit decl!");
3216 Declarator D(DS, Declarator::BlockContext);
Douglas Gregor965acbb2009-02-18 07:07:28 +00003217 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(),
3218 0, 0, 0, Loc, D),
Sebastian Redlab197ba2009-02-09 18:23:29 +00003219 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00003220 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00003221
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00003222 // Insert this function into translation-unit scope.
3223
3224 DeclContext *PrevDC = CurContext;
3225 CurContext = Context.getTranslationUnitDecl();
3226
Steve Naroffe2ef8152008-04-04 14:32:09 +00003227 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00003228 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00003229 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00003230
3231 CurContext = PrevDC;
3232
Douglas Gregor3c385e52009-02-14 18:57:46 +00003233 AddKnownFunctionAttributes(FD);
3234
Steve Naroffe2ef8152008-04-04 14:32:09 +00003235 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003236}
3237
Douglas Gregor3c385e52009-02-14 18:57:46 +00003238/// \brief Adds any function attributes that we know a priori based on
3239/// the declaration of this function.
3240///
3241/// These attributes can apply both to implicitly-declared builtins
3242/// (like __builtin___printf_chk) or to library-declared functions
3243/// like NSLog or printf.
3244void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
3245 if (FD->isInvalidDecl())
3246 return;
3247
3248 // If this is a built-in function, map its builtin attributes to
3249 // actual attributes.
3250 if (unsigned BuiltinID = FD->getBuiltinID(Context)) {
3251 // Handle printf-formatting attributes.
3252 unsigned FormatIdx;
3253 bool HasVAListArg;
3254 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
3255 if (!FD->getAttr<FormatAttr>())
3256 FD->addAttr(new FormatAttr("printf", FormatIdx + 1, FormatIdx + 2));
3257 }
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00003258
3259 // Mark const if we don't care about errno and that is the only
3260 // thing preventing the function from being const. This allows
3261 // IRgen to use LLVM intrinsics for such functions.
3262 if (!getLangOptions().MathErrno &&
3263 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
3264 if (!FD->getAttr<ConstAttr>())
3265 FD->addAttr(new ConstAttr());
3266 }
Douglas Gregor3c385e52009-02-14 18:57:46 +00003267 }
3268
3269 IdentifierInfo *Name = FD->getIdentifier();
3270 if (!Name)
3271 return;
3272 if ((!getLangOptions().CPlusPlus &&
3273 FD->getDeclContext()->isTranslationUnit()) ||
3274 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
3275 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
3276 LinkageSpecDecl::lang_c)) {
3277 // Okay: this could be a libc/libm/Objective-C function we know
3278 // about.
3279 } else
3280 return;
3281
3282 unsigned KnownID;
3283 for (KnownID = 0; KnownID != id_num_known_functions; ++KnownID)
3284 if (KnownFunctionIDs[KnownID] == Name)
3285 break;
3286
3287 switch (KnownID) {
3288 case id_NSLog:
3289 case id_NSLogv:
3290 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
3291 // FIXME: We known better than our headers.
3292 const_cast<FormatAttr *>(Format)->setType("printf");
3293 } else
3294 FD->addAttr(new FormatAttr("printf", 1, 2));
3295 break;
3296
3297 case id_asprintf:
3298 case id_vasprintf:
3299 if (!FD->getAttr<FormatAttr>())
3300 FD->addAttr(new FormatAttr("printf", 2, 3));
3301 break;
3302
3303 default:
3304 // Unknown function or known function without any attributes to
3305 // add. Do nothing.
3306 break;
3307 }
3308}
Reid Spencer5f016e22007-07-11 17:01:13 +00003309
Chris Lattner41af0932007-11-14 06:34:38 +00003310TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003311 Decl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003312 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00003313 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003314
3315 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00003316 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
3317 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003318 D.getIdentifier(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003319 T);
3320 NewTD->setNextDeclarator(LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00003321 if (D.getInvalidType())
3322 NewTD->setInvalidDecl();
3323 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003324}
3325
Steve Naroff08d92e42007-09-15 18:49:24 +00003326/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00003327/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003328/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +00003329/// reference/declaration/definition of a tag.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003330Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00003331 SourceLocation KWLoc, const CXXScopeSpec &SS,
3332 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorddc29e12009-02-06 22:42:48 +00003333 AttributeList *Attr) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003334 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00003335 assert((Name != 0 || TK == TK_Definition) &&
3336 "Nameless record must be a definition!");
Douglas Gregoraaba5e32009-02-04 19:02:06 +00003337
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003338 TagDecl::TagKind Kind;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003339 switch (TagSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003340 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003341 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3342 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3343 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3344 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003345 }
3346
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003347 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00003348 DeclContext *DC = CurContext;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003349 NamedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00003350
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003351 bool Invalid = false;
3352
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00003353 if (Name && SS.isNotEmpty()) {
3354 // We have a nested-name tag ('struct foo::bar').
3355
3356 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00003357 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00003358 Name = 0;
3359 goto CreateNewDecl;
3360 }
3361
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00003362 DC = static_cast<DeclContext*>(SS.getScopeRep());
Douglas Gregor1931b442009-02-03 00:34:39 +00003363 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00003364 // Look-up name inside 'foo::'.
Steve Naroff3e8ffd22009-01-29 00:07:50 +00003365 PrevDecl = dyn_cast_or_null<TagDecl>(
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003366 LookupQualifiedName(DC, Name, LookupTagName, true).getAsDecl());
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00003367
3368 // A tag 'foo::bar' must already exist.
3369 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00003370 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00003371 Name = 0;
3372 goto CreateNewDecl;
3373 }
Chris Lattnercf79b012009-01-21 02:38:50 +00003374 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00003375 // If this is a named struct, check to see if there was a previous forward
3376 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003377 // FIXME: We're looking into outer scopes here, even when we
3378 // shouldn't be. Doing so can result in ambiguities that we
3379 // shouldn't be diagnosing.
Douglas Gregore2c565d2009-02-03 19:26:08 +00003380 LookupResult R = LookupName(S, Name, LookupTagName,
3381 /*RedeclarationOnly=*/(TK != TK_Reference));
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003382 if (R.isAmbiguous()) {
3383 DiagnoseAmbiguousLookup(R, Name, NameLoc);
3384 // FIXME: This is not best way to recover from case like:
3385 //
3386 // struct S s;
3387 //
3388 // causes needless err_ovl_no_viable_function_in_init latter.
3389 Name = 0;
3390 PrevDecl = 0;
3391 Invalid = true;
3392 }
3393 else
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003394 PrevDecl = R;
Douglas Gregor72de6672009-01-08 20:45:30 +00003395
3396 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
3397 // FIXME: This makes sure that we ignore the contexts associated
3398 // with C structs, unions, and enums when looking for a matching
3399 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +00003400 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003401 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
3402 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +00003403 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00003404 }
3405
Douglas Gregorf57172b2008-12-08 18:40:42 +00003406 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003407 // Maybe we will complain about the shadowed template parameter.
3408 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
3409 // Just pretend that we didn't see the previous declaration.
3410 PrevDecl = 0;
3411 }
3412
Chris Lattner22bd9052009-02-16 22:07:16 +00003413 if (PrevDecl) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003414 // Check whether the previous declaration is usable.
3415 (void)DiagnoseUseOfDecl(PrevDecl, NameLoc);
Chris Lattner22bd9052009-02-16 22:07:16 +00003416
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003417 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00003418 // If this is a use of a previous tag, or if the tag is already declared
3419 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003420 // rementions the tag), reuse the decl.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003421 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00003422 // Make sure that this wasn't declared as an enum and now used as a
3423 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003424 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00003425 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003426 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00003427 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003428 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00003429 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003430 Invalid = true;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003431 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003432 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00003433
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003434 // FIXME: In the future, return a variant or some other clue
3435 // for the consumer of this Decl to know it doesn't own it.
3436 // For our current ASTs this shouldn't be a problem, but will
3437 // need to be changed with DeclGroups.
3438 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00003439 return PrevDecl;
Douglas Gregoraaba5e32009-02-04 19:02:06 +00003440
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003441 // Diagnose attempts to redefine a tag.
3442 if (TK == TK_Definition) {
3443 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
3444 Diag(NameLoc, diag::err_redefinition) << Name;
3445 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003446 // If this is a redefinition, recover by making this
3447 // struct be anonymous, which will make any later
3448 // references get the previous definition.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003449 Name = 0;
3450 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003451 Invalid = true;
3452 } else {
3453 // If the type is currently being defined, complain
3454 // about a nested redefinition.
3455 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
3456 if (Tag->isBeingDefined()) {
3457 Diag(NameLoc, diag::err_nested_redefinition) << Name;
3458 Diag(PrevTagDecl->getLocation(),
3459 diag::note_previous_definition);
3460 Name = 0;
3461 PrevDecl = 0;
3462 Invalid = true;
3463 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003464 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003465
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003466 // Okay, this is definition of a previously declared or referenced
3467 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003468 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003469 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003470 // If we get here we have (another) forward declaration or we
3471 // have a definition. Just create a new decl.
3472 } else {
3473 // If we get here, this is a definition of a new tag type in a nested
3474 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
3475 // new decl/type. We set PrevDecl to NULL so that the entities
3476 // have distinct types.
3477 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00003478 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003479 // If we get here, we're going to create a new Decl. If PrevDecl
3480 // is non-NULL, it's a definition of the tag declared by
3481 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003482 } else {
Douglas Gregor66973122009-01-28 17:15:10 +00003483 // PrevDecl is a namespace, template, or anything else
3484 // that lives in the IDNS_Tag identifier namespace.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003485 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00003486 // The tag name clashes with a namespace name, issue an error and
3487 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00003488 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003489 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00003490 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003491 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003492 Invalid = true;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003493 } else {
3494 // The existing declaration isn't relevant to us; we're in a
3495 // new scope, so clear out the previous declaration.
3496 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00003497 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003498 }
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003499 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
3500 (Kind != TagDecl::TK_enum)) {
3501 // C++ [basic.scope.pdecl]p5:
3502 // -- for an elaborated-type-specifier of the form
3503 //
3504 // class-key identifier
3505 //
3506 // if the elaborated-type-specifier is used in the
3507 // decl-specifier-seq or parameter-declaration-clause of a
3508 // function defined in namespace scope, the identifier is
3509 // declared as a class-name in the namespace that contains
3510 // the declaration; otherwise, except as a friend
3511 // declaration, the identifier is declared in the smallest
3512 // non-class, non-function-prototype scope that contains the
3513 // declaration.
3514 //
3515 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
3516 // C structs and unions.
3517
3518 // Find the context where we'll be declaring the tag.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003519 // FIXME: We would like to maintain the current DeclContext as the
3520 // lexical context,
Douglas Gregor1931b442009-02-03 00:34:39 +00003521 while (SearchDC->isRecord())
3522 SearchDC = SearchDC->getParent();
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003523
3524 // Find the scope where we'll be declaring the tag.
3525 while (S->isClassScope() ||
3526 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003527 ((S->getFlags() & Scope::DeclScope) == 0) ||
3528 (S->getEntity() &&
3529 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003530 S = S->getParent();
Reid Spencer5f016e22007-07-11 17:01:13 +00003531 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00003532
Chris Lattnercc98eac2008-12-17 07:13:27 +00003533CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00003534
3535 // If there is an identifier, use the location of the identifier as the
3536 // location of the decl, otherwise use the location of the struct/union
3537 // keyword.
3538 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3539
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003540 // Otherwise, create a new declaration. If there is a previous
3541 // declaration of the same entity, the two will be linked via
3542 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00003543 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003544
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003545 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003546 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3547 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor1931b442009-02-03 00:34:39 +00003548 New = EnumDecl::Create(Context, SearchDC, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003549 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003550 // If this is an undefined enum, warn.
3551 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003552 } else {
3553 // struct/union/class
3554
Reid Spencer5f016e22007-07-11 17:01:13 +00003555 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3556 // struct X { int A; } D; D should chain to X.
Douglas Gregorddc29e12009-02-06 22:42:48 +00003557 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00003558 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor1931b442009-02-03 00:34:39 +00003559 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003560 cast_or_null<CXXRecordDecl>(PrevDecl));
Douglas Gregorddc29e12009-02-06 22:42:48 +00003561 else
Douglas Gregor1931b442009-02-03 00:34:39 +00003562 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003563 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003564 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003565
3566 if (Kind != TagDecl::TK_enum) {
3567 // Handle #pragma pack: if the #pragma pack stack has non-default
3568 // alignment, make up a packed attribute for this decl. These
3569 // attributes are checked when the ASTContext lays out the
3570 // structure.
3571 //
3572 // It is important for implementing the correct semantics that this
3573 // happen here (in act on tag decl). The #pragma pack stack is
3574 // maintained as a result of parser callbacks which can occur at
3575 // many points during the parsing of a struct declaration (because
3576 // the #pragma tokens are effectively skipped over during the
3577 // parsing of the struct).
Chris Lattner574aa402009-02-17 01:09:29 +00003578 if (unsigned Alignment = getPragmaPackAlignment())
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003579 New->addAttr(new PackedAttr(Alignment * 8));
3580 }
3581
Douglas Gregor66973122009-01-28 17:15:10 +00003582 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
3583 // C++ [dcl.typedef]p3:
3584 // [...] Similarly, in a given scope, a class or enumeration
3585 // shall not be declared with the same name as a typedef-name
3586 // that is declared in that scope and refers to a type other
3587 // than the class or enumeration itself.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00003588 LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true);
Douglas Gregor66973122009-01-28 17:15:10 +00003589 TypedefDecl *PrevTypedef = 0;
3590 if (Lookup.getKind() == LookupResult::Found)
3591 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
3592
3593 if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
3594 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
3595 Context.getCanonicalType(Context.getTypeDeclType(New))) {
3596 Diag(Loc, diag::err_tag_definition_of_typedef)
3597 << Context.getTypeDeclType(New)
3598 << PrevTypedef->getUnderlyingType();
3599 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
3600 Invalid = true;
3601 }
3602 }
3603
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003604 if (Invalid)
3605 New->setInvalidDecl();
3606
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003607 if (Attr)
3608 ProcessDeclAttributeList(New, Attr);
3609
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003610 // If we're declaring or defining a tag in function prototype scope
3611 // in C, note that this type can only be used within the function.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003612 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3613 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3614
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003615 // Set the lexical context. If the tag has a C++ scope specifier, the
3616 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +00003617 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003618
3619 if (TK == TK_Definition)
3620 New->startDefinition();
Reid Spencer5f016e22007-07-11 17:01:13 +00003621
3622 // If this has an identifier, add it to the scope stack.
3623 if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003624 S = getNonFieldDeclScope(S);
Douglas Gregor1931b442009-02-03 00:34:39 +00003625 PushOnScopeChains(New, S);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003626 } else {
Douglas Gregor1931b442009-02-03 00:34:39 +00003627 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00003628 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00003629
Reid Spencer5f016e22007-07-11 17:01:13 +00003630 return New;
3631}
3632
Douglas Gregor72de6672009-01-08 20:45:30 +00003633void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +00003634 AdjustDeclIfTemplate(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +00003635 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3636
3637 // Enter the tag context.
3638 PushDeclContext(S, Tag);
3639
3640 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3641 FieldCollector->StartClass();
3642
3643 if (Record->getIdentifier()) {
3644 // C++ [class]p2:
3645 // [...] The class-name is also inserted into the scope of the
3646 // class itself; this is known as the injected-class-name. For
3647 // purposes of access checking, the injected-class-name is treated
3648 // as if it were a public member name.
3649 RecordDecl *InjectedClassName
3650 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3651 CurContext, Record->getLocation(),
3652 Record->getIdentifier(), Record);
3653 InjectedClassName->setImplicit();
3654 PushOnScopeChains(InjectedClassName, S);
3655 }
3656 }
3657}
3658
3659void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +00003660 AdjustDeclIfTemplate(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +00003661 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3662
3663 if (isa<CXXRecordDecl>(Tag))
3664 FieldCollector->FinishClass();
3665
3666 // Exit this scope of this tag's definition.
3667 PopDeclContext();
3668
3669 // Notify the consumer that we've defined a tag.
3670 Consumer.HandleTagDeclDefinition(Tag);
3671}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00003672
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003673bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00003674 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003675 // FIXME: 6.7.2.1p4 - verify the field type.
3676
3677 llvm::APSInt Value;
3678 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3679 return true;
3680
Chris Lattnercd087072008-12-12 04:56:04 +00003681 // Zero-width bitfield is ok for anonymous field.
3682 if (Value == 0 && FieldName)
3683 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3684
3685 if (Value.isNegative())
3686 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003687
3688 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3689 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00003690 if (TypeSize && Value.getZExtValue() > TypeSize)
3691 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3692 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003693
3694 return false;
3695}
3696
Steve Naroff08d92e42007-09-15 18:49:24 +00003697/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00003698/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00003699Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00003700 SourceLocation DeclStart,
3701 Declarator &D, ExprTy *BitfieldWidth) {
3702 IdentifierInfo *II = D.getIdentifier();
3703 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00003704 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00003705 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003706 if (II) Loc = D.getIdentifierLoc();
3707
3708 // FIXME: Unnamed fields can be handled in various different ways, for
3709 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00003710
Reid Spencer5f016e22007-07-11 17:01:13 +00003711 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00003712 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3713 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00003714
Reid Spencer5f016e22007-07-11 17:01:13 +00003715 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3716 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00003717 if (T->isVariablyModifiedType()) {
Eli Friedman1ca48132009-02-21 00:44:51 +00003718 bool SizeIsNegative;
3719 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
3720 SizeIsNegative);
3721 if (!FixedTy.isNull()) {
3722 Diag(Loc, diag::warn_illegal_constant_array_size);
3723 T = FixedTy;
3724 } else {
3725 if (SizeIsNegative)
3726 Diag(Loc, diag::err_typecheck_negative_array_size);
3727 else
3728 Diag(Loc, diag::err_typecheck_field_variable_size);
3729 T = Context.IntTy;
3730 InvalidDecl = true;
3731 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003732 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003733
3734 if (BitWidth) {
3735 if (VerifyBitField(Loc, II, T, BitWidth))
3736 InvalidDecl = true;
3737 } else {
3738 // Not a bitfield.
3739
3740 // validate II.
3741
3742 }
3743
Chris Lattner7a21bd02009-02-20 20:41:34 +00003744 FieldDecl *NewFD = FieldDecl::Create(Context, Record,
3745 Loc, II, T, BitWidth,
3746 D.getDeclSpec().getStorageClassSpec() ==
3747 DeclSpec::SCS_mutable);
Douglas Gregor44b43212008-12-11 16:49:14 +00003748
Douglas Gregor72de6672009-01-08 20:45:30 +00003749 if (II) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003750 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregor72de6672009-01-08 20:45:30 +00003751 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3752 && !isa<TagDecl>(PrevDecl)) {
3753 Diag(Loc, diag::err_duplicate_member) << II;
3754 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3755 NewFD->setInvalidDecl();
3756 Record->setInvalidDecl();
3757 }
3758 }
3759
Sebastian Redl64b45f72009-01-05 20:52:13 +00003760 if (getLangOptions().CPlusPlus) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003761 CheckExtraCXXDefaultArguments(D);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003762 if (!T->isPODType())
3763 cast<CXXRecordDecl>(Record)->setPOD(false);
3764 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003765
Chris Lattner3ff30c82008-06-29 00:02:00 +00003766 ProcessDeclAttributes(NewFD, D);
Fariborz Jahanianf6123ca2009-02-19 00:22:47 +00003767 if (T.isObjCGCWeak())
Fariborz Jahanianed7e9ef2009-02-18 18:14:41 +00003768 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlssonad148062008-02-16 00:29:18 +00003769
Steve Naroff5912a352007-08-28 20:14:24 +00003770 if (D.getInvalidType() || InvalidDecl)
3771 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003772
Douglas Gregor72de6672009-01-08 20:45:30 +00003773 if (II) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003774 PushOnScopeChains(NewFD, S);
Douglas Gregor72de6672009-01-08 20:45:30 +00003775 } else
Douglas Gregor482b77d2009-01-12 23:27:07 +00003776 Record->addDecl(NewFD);
Douglas Gregor44b43212008-12-11 16:49:14 +00003777
Steve Naroff5912a352007-08-28 20:14:24 +00003778 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003779}
3780
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003781/// TranslateIvarVisibility - Translate visibility from a token ID to an
3782/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003783static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003784TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00003785 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00003786 default: assert(0 && "Unknown visitibility kind");
3787 case tok::objc_private: return ObjCIvarDecl::Private;
3788 case tok::objc_public: return ObjCIvarDecl::Public;
3789 case tok::objc_protected: return ObjCIvarDecl::Protected;
3790 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00003791 }
3792}
3793
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003794/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3795/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003796Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003797 SourceLocation DeclStart,
3798 Declarator &D, ExprTy *BitfieldWidth,
3799 tok::ObjCKeywordKind Visibility) {
Douglas Gregor72de6672009-01-08 20:45:30 +00003800
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003801 IdentifierInfo *II = D.getIdentifier();
3802 Expr *BitWidth = (Expr*)BitfieldWidth;
3803 SourceLocation Loc = DeclStart;
3804 if (II) Loc = D.getIdentifierLoc();
3805
3806 // FIXME: Unnamed fields can be handled in various different ways, for
3807 // example, unnamed unions inject all members into the struct namespace!
3808
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003809 QualType T = GetTypeForDeclarator(D, S);
3810 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3811 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003812
3813 if (BitWidth) {
Steve Naroff63359c82009-02-20 17:57:11 +00003814 // 6.7.2.1p3, 6.7.2.1p4
3815 if (VerifyBitField(Loc, II, T, BitWidth))
3816 InvalidDecl = true;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003817 } else {
3818 // Not a bitfield.
3819
3820 // validate II.
3821
3822 }
3823
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003824 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3825 // than a variably modified type.
3826 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00003827 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003828 InvalidDecl = true;
3829 }
3830
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003831 // Get the visibility (access control) for this ivar.
3832 ObjCIvarDecl::AccessControl ac =
3833 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3834 : ObjCIvarDecl::None;
3835
3836 // Construct the decl.
Argyrios Kyrtzidis0c00aac2009-02-17 20:20:37 +00003837 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, CurContext, Loc, II, T,ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00003838 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003839
Douglas Gregor72de6672009-01-08 20:45:30 +00003840 if (II) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003841 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregor72de6672009-01-08 20:45:30 +00003842 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3843 && !isa<TagDecl>(PrevDecl)) {
3844 Diag(Loc, diag::err_duplicate_member) << II;
3845 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3846 NewID->setInvalidDecl();
3847 }
3848 }
3849
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003850 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00003851 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003852
3853 if (D.getInvalidType() || InvalidDecl)
3854 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003855
Douglas Gregor72de6672009-01-08 20:45:30 +00003856 if (II) {
3857 // FIXME: When interfaces are DeclContexts, we'll need to add
3858 // these to the interface.
3859 S->AddDecl(NewID);
3860 IdResolver.AddDecl(NewID);
3861 }
3862
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003863 return NewID;
3864}
3865
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00003866void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003867 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00003868 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00003869 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00003870 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00003871 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3872 assert(EnclosingDecl && "missing record or interface decl");
Chris Lattner1829a6d2009-02-23 22:00:08 +00003873
3874 // If the decl this is being inserted into is invalid, then it may be a
3875 // redeclaration or some other bogus case. Don't try to add fields to it.
3876 if (EnclosingDecl->isInvalidDecl()) {
3877 // FIXME: Deallocate fields?
3878 return;
3879 }
3880
Steve Naroff74216642007-09-14 22:20:54 +00003881
Reid Spencer5f016e22007-07-11 17:01:13 +00003882 // Verify that all the fields are okay.
3883 unsigned NumNamedMembers = 0;
3884 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003885
Chris Lattner1829a6d2009-02-23 22:00:08 +00003886 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00003887 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff74216642007-09-14 22:20:54 +00003888 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3889 assert(FD && "missing field decl");
3890
Reid Spencer5f016e22007-07-11 17:01:13 +00003891 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003892 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003893
Douglas Gregor72de6672009-01-08 20:45:30 +00003894 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003895 // Remember all fields written by the user.
3896 RecFields.push_back(FD);
3897 }
Steve Narofff13271f2007-09-14 23:09:53 +00003898
Reid Spencer5f016e22007-07-11 17:01:13 +00003899 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003900 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003901 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003902 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003903 FD->setInvalidDecl();
3904 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003905 continue;
3906 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003907 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3908 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003909 if (!Record) { // Incomplete ivar type is always an error.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003910 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3911 diag::err_field_incomplete);
Steve Naroff74216642007-09-14 22:20:54 +00003912 FD->setInvalidDecl();
3913 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003914 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003915 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003916 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003917 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003918 !FDTy->isArrayType()) { //... may have incomplete array type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003919 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3920 diag::err_field_incomplete);
Steve Naroff74216642007-09-14 22:20:54 +00003921 FD->setInvalidDecl();
3922 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003923 continue;
3924 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003925 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003926 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003927 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003928 FD->setInvalidDecl();
3929 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003930 continue;
3931 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003932 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003933 if (Record)
3934 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003935 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003936 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3937 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003938 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003939 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3940 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003941 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003942 Record->setHasFlexibleArrayMember(true);
3943 } else {
3944 // If this is a struct/class and this is not the last element, reject
3945 // it. Note that GCC supports variable sized arrays in the middle of
3946 // structures.
3947 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003948 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003949 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003950 FD->setInvalidDecl();
3951 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003952 continue;
3953 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003954 // We support flexible arrays at the end of structs in other structs
3955 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003956 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003957 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003958 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003959 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003960 }
3961 }
3962 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003963 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003964 if (FDTy->isObjCInterfaceType()) {
Steve Naroffccef3712009-02-20 22:59:16 +00003965 Diag(FD->getLocation(), diag::err_statically_allocated_object);
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003966 FD->setInvalidDecl();
3967 EnclosingDecl->setInvalidDecl();
3968 continue;
3969 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003970 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00003971 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00003972 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003973 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003974
Reid Spencer5f016e22007-07-11 17:01:13 +00003975 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003976 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003977 Record->completeDefinition(Context);
Chris Lattnere1e79852008-02-06 00:51:33 +00003978 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003979 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003980 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner38af2de2009-02-20 21:35:13 +00003981 ID->setIVarList(ClsFields, RecFields.size(), Context);
3982 ID->setLocEnd(RBrac);
3983
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003984 // Must enforce the rule that ivars in the base classes may not be
3985 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003986 if (ID->getSuperClass()) {
3987 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3988 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3989 ObjCIvarDecl* Ivar = (*IVI);
3990 IdentifierInfo *II = Ivar->getIdentifier();
Fariborz Jahaniana5afdd02009-02-16 19:35:27 +00003991 ObjCIvarDecl* prevIvar = ID->getSuperClass()->lookupInstanceVariable(II);
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003992 if (prevIvar) {
3993 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregor72de6672009-01-08 20:45:30 +00003994 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003995 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003996 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003997 }
Chris Lattner1829a6d2009-02-23 22:00:08 +00003998 } else if (ObjCImplementationDecl *IMPDecl =
3999 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004000 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Chris Lattner38af2de2009-02-20 21:35:13 +00004001 IMPDecl->setIVarList(ClsFields, RecFields.size(), Context);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00004002 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00004003 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00004004 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00004005
4006 if (Attr)
4007 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00004008}
4009
Steve Naroff08d92e42007-09-15 18:49:24 +00004010Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00004011 DeclTy *lastEnumConst,
4012 SourceLocation IdLoc, IdentifierInfo *Id,
4013 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00004014 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00004015 EnumConstantDecl *LastEnumConst =
4016 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
4017 Expr *Val = static_cast<Expr*>(val);
4018
Chris Lattner31e05722007-08-26 06:24:45 +00004019 // The scope passed in may not be a decl scope. Zip up the scope tree until
4020 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00004021 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00004022
Reid Spencer5f016e22007-07-11 17:01:13 +00004023 // Verify that there isn't already something declared with this name in this
4024 // scope.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00004025 NamedDecl *PrevDecl = LookupName(S, Id, LookupOrdinaryName);
Douglas Gregorf57172b2008-12-08 18:40:42 +00004026 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00004027 // Maybe we will complain about the shadowed template parameter.
4028 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
4029 // Just pretend that we didn't see the previous declaration.
4030 PrevDecl = 0;
4031 }
4032
4033 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00004034 // When in C++, we may get a TagDecl with the same name; in this case the
4035 // enum constant will 'hide' the tag.
4036 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
4037 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00004038 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004039 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00004040 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00004041 else
Chris Lattner3c73c412008-11-19 08:23:25 +00004042 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00004043 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004044 Val->Destroy(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00004045 return 0;
4046 }
4047 }
4048
4049 llvm::APSInt EnumVal(32);
4050 QualType EltTy;
4051 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00004052 // Make sure to promote the operand type to int.
4053 UsualUnaryConversions(Val);
4054
Reid Spencer5f016e22007-07-11 17:01:13 +00004055 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
4056 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00004057 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004058 Val->Destroy(Context);
Chris Lattnerb7416f92007-08-27 17:37:24 +00004059 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00004060 } else {
4061 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004062 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00004063 }
4064
4065 if (!Val) {
4066 if (LastEnumConst) {
4067 // Assign the last value + 1.
4068 EnumVal = LastEnumConst->getInitVal();
4069 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00004070
4071 // Check for overflow on increment.
4072 if (EnumVal < LastEnumConst->getInitVal())
4073 Diag(IdLoc, diag::warn_enum_value_overflow);
4074
Chris Lattnerb7416f92007-08-27 17:37:24 +00004075 EltTy = LastEnumConst->getType();
4076 } else {
4077 // First value, set to zero.
4078 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00004079 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00004080 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004081 }
4082
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00004083 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00004084 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004085 Val, EnumVal);
Reid Spencer5f016e22007-07-11 17:01:13 +00004086
4087 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00004088 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00004089
Reid Spencer5f016e22007-07-11 17:01:13 +00004090 return New;
4091}
4092
Steve Naroff02408c62008-08-07 14:08:16 +00004093// FIXME: For consistency with ActOnFields(), we should have the parser
4094// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00004095void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00004096 DeclTy **Elements, unsigned NumElements) {
4097 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00004098 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00004099
Chris Lattnere37f0be2007-08-28 05:10:31 +00004100 // TODO: If the result value doesn't fit in an int, it must be a long or long
4101 // long value. ISO C does not support this, but GCC does as an extension,
4102 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00004103 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00004104
Chris Lattnerac609682007-08-28 06:15:15 +00004105 // Verify that all the values are okay, compute the size of the values, and
4106 // reverse the list.
4107 unsigned NumNegativeBits = 0;
4108 unsigned NumPositiveBits = 0;
4109
4110 // Keep track of whether all elements have type int.
4111 bool AllElementsInt = true;
4112
Reid Spencer5f016e22007-07-11 17:01:13 +00004113 for (unsigned i = 0; i != NumElements; ++i) {
4114 EnumConstantDecl *ECD =
4115 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
4116 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00004117
4118 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00004119 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00004120 assert(InitVal.getBitWidth() >= IntWidth &&
4121 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00004122 if (InitVal.getBitWidth() > IntWidth) {
4123 llvm::APSInt V(InitVal);
4124 V.trunc(IntWidth);
4125 V.extend(InitVal.getBitWidth());
4126 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004127 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
4128 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00004129 }
Chris Lattnerac609682007-08-28 06:15:15 +00004130
4131 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00004132 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00004133 NumPositiveBits = std::max(NumPositiveBits,
4134 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00004135 else
Chris Lattner21dd8212008-01-14 21:47:29 +00004136 NumNegativeBits = std::max(NumNegativeBits,
4137 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00004138
Chris Lattnerac609682007-08-28 06:15:15 +00004139 // Keep track of whether every enum element has type int (very commmon).
4140 if (AllElementsInt)
4141 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004142 }
4143
Chris Lattnerac609682007-08-28 06:15:15 +00004144 // Figure out the type that should be used for this enum.
4145 // FIXME: Support attribute(packed) on enums and -fshort-enums.
4146 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00004147 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00004148
4149 if (NumNegativeBits) {
4150 // If there is a negative value, figure out the smallest integer type (of
4151 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00004152 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00004153 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00004154 BestWidth = IntWidth;
4155 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00004156 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00004157
Chris Lattnerb7f6e082007-08-29 17:31:48 +00004158 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00004159 BestType = Context.LongTy;
4160 else {
Chris Lattner98be4942008-03-05 18:54:05 +00004161 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00004162
Chris Lattnerb7f6e082007-08-29 17:31:48 +00004163 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00004164 Diag(Enum->getLocation(), diag::warn_enum_too_large);
4165 BestType = Context.LongLongTy;
4166 }
4167 }
4168 } else {
4169 // If there is no negative value, figure out which of uint, ulong, ulonglong
4170 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00004171 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00004172 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00004173 BestWidth = IntWidth;
4174 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00004175 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00004176 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00004177 } else {
4178 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00004179 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00004180 "How could an initializer get larger than ULL?");
4181 BestType = Context.UnsignedLongLongTy;
4182 }
4183 }
4184
Chris Lattnerb7f6e082007-08-29 17:31:48 +00004185 // Loop over all of the enumerator constants, changing their types to match
4186 // the type of the enum if needed.
4187 for (unsigned i = 0; i != NumElements; ++i) {
4188 EnumConstantDecl *ECD =
4189 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
4190 if (!ECD) continue; // Already issued a diagnostic.
4191
4192 // Standard C says the enumerators have int type, but we allow, as an
4193 // extension, the enumerators to be larger than int size. If each
4194 // enumerator value fits in an int, type it as an int, otherwise type it the
4195 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
4196 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00004197 if (ECD->getType() == Context.IntTy) {
4198 // Make sure the init value is signed.
4199 llvm::APSInt IV = ECD->getInitVal();
4200 IV.setIsSigned(true);
4201 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004202
4203 if (getLangOptions().CPlusPlus)
4204 // C++ [dcl.enum]p4: Following the closing brace of an
4205 // enum-specifier, each enumerator has the type of its
4206 // enumeration.
4207 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00004208 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00004209 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00004210
4211 // Determine whether the value fits into an int.
4212 llvm::APSInt InitVal = ECD->getInitVal();
4213 bool FitsInInt;
4214 if (InitVal.isUnsigned() || !InitVal.isNegative())
4215 FitsInInt = InitVal.getActiveBits() < IntWidth;
4216 else
4217 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
4218
4219 // If it fits into an integer type, force it. Otherwise force it to match
4220 // the enum decl type.
4221 QualType NewTy;
4222 unsigned NewWidth;
4223 bool NewSign;
4224 if (FitsInInt) {
4225 NewTy = Context.IntTy;
4226 NewWidth = IntWidth;
4227 NewSign = true;
4228 } else if (ECD->getType() == BestType) {
4229 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004230 if (getLangOptions().CPlusPlus)
4231 // C++ [dcl.enum]p4: Following the closing brace of an
4232 // enum-specifier, each enumerator has the type of its
4233 // enumeration.
4234 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00004235 continue;
4236 } else {
4237 NewTy = BestType;
4238 NewWidth = BestWidth;
4239 NewSign = BestType->isSignedIntegerType();
4240 }
4241
4242 // Adjust the APSInt value.
4243 InitVal.extOrTrunc(NewWidth);
4244 InitVal.setIsSigned(NewSign);
4245 ECD->setInitVal(InitVal);
4246
4247 // Adjust the Expr initializer and type.
Chris Lattner13fd4162009-01-15 19:19:42 +00004248 if (ECD->getInitExpr())
Ted Kremenek8189cde2009-02-07 01:47:29 +00004249 ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy, ECD->getInitExpr(),
4250 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004251 if (getLangOptions().CPlusPlus)
4252 // C++ [dcl.enum]p4: Following the closing brace of an
4253 // enum-specifier, each enumerator has the type of its
4254 // enumeration.
4255 ECD->setType(EnumType);
4256 else
4257 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00004258 }
Chris Lattnerac609682007-08-28 06:15:15 +00004259
Douglas Gregor44b43212008-12-11 16:49:14 +00004260 Enum->completeDefinition(Context, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00004261}
4262
Anders Carlssondfab6cb2008-02-08 00:33:21 +00004263Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00004264 ExprArg expr) {
4265 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
4266
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004267 return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00004268}
4269