blob: 2c5e46afa0e73a352798140c42dd80156ef16de8 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregore267ff32008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
29
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31
Douglas Gregor2def4832008-11-17 20:34:05 +000032Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000033 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000034 DeclContext *DC = 0;
35 if (SS) {
36 if (SS->isInvalid())
37 return 0;
38 DC = static_cast<DeclContext*>(SS->getScopeRep());
39 }
40 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroffb327ce02008-04-02 14:35:35 +000041
Douglas Gregor2ce52f32008-04-13 21:07:44 +000042 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
43 isa<ObjCInterfaceDecl>(IIDecl) ||
Douglas Gregor72c3f312008-12-05 18:15:24 +000044 isa<TagDecl>(IIDecl) ||
45 isa<TemplateTypeParmDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000046 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000047 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000048}
49
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000050DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000051 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000052 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000053 if (MD->isOutOfLineDefinition())
54 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000055
56 // A C++ inline method is parsed *after* the topmost class it was declared in
57 // is fully parsed (it's "complete").
58 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000059 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000060 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
61 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000062 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000063 DC = RD;
64
65 // Return the declaration context of the topmost class the inline method is
66 // declared in.
67 return DC;
68 }
69
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000070 if (isa<ObjCMethodDecl>(DC))
71 return Context.getTranslationUnitDecl();
72
73 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
74 return SD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000075
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000076 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000077}
78
Douglas Gregor44b43212008-12-11 16:49:14 +000079void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000080 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +000081 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000082 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +000083 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +000084}
85
Chris Lattnerb048c982008-04-06 04:47:34 +000086void Sema::PopDeclContext() {
87 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +000088
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000089 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000090}
91
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000092/// Add this decl to the scope shadowed decl chains.
93void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000094 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000095
96 // C++ [basic.scope]p4:
97 // -- exactly one declaration shall declare a class name or
98 // enumeration name that is not a typedef name and the other
99 // declarations shall all refer to the same object or
100 // enumerator, or all refer to functions and function templates;
101 // in this case the class name or enumeration name is hidden.
102 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
103 // We are pushing the name of a tag (enum or class).
Douglas Gregor44b43212008-12-11 16:49:14 +0000104 if (CurContext == TD->getDeclContext()) {
105 // We're pushing the tag into the current context, which might
106 // require some reshuffling in the identifier resolver.
107 IdentifierResolver::iterator
108 I = IdResolver.begin(TD->getIdentifier(), CurContext,
109 false/*LookInParentCtx*/);
110 if (I != IdResolver.end()) {
111 // There is already a declaration with the same name in the same
112 // scope. It must be found before we find the new declaration,
113 // so swap the order on the shadowed declaration chain.
114 IdResolver.AddShadowedDecl(TD, *I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000115
Douglas Gregor44b43212008-12-11 16:49:14 +0000116 // Add this declaration to the current context.
117 CurContext->addDecl(Context, TD);
118
119 return;
120 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000121 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000122 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000123 // We are pushing the name of a function, which might be an
124 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000125 FunctionDecl *FD = cast<FunctionDecl>(D);
126 Decl *Prev = LookupDecl(FD->getDeclName(), Decl::IDNS_Ordinary, S,
127 FD->getDeclContext(), false, false);
128 if (Prev && (isa<OverloadedFunctionDecl>(Prev) || isa<FunctionDecl>(Prev))) {
129 // There is already a declaration with the same name in
130 // the same scope. It must be a function or an overloaded
131 // function.
132 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(Prev);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000133 if (!Ovl) {
134 // We haven't yet overloaded this function. Take the existing
135 // FunctionDecl and put it into an OverloadedFunctionDecl.
136 Ovl = OverloadedFunctionDecl::Create(Context,
137 FD->getDeclContext(),
Douglas Gregor2def4832008-11-17 20:34:05 +0000138 FD->getDeclName());
Douglas Gregore267ff32008-12-11 20:41:00 +0000139 Ovl->addOverload(cast<FunctionDecl>(Prev));
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000140
Douglas Gregore267ff32008-12-11 20:41:00 +0000141 // If there is an ame binding for the existing FunctionDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +0000142 // remove it.
143 for (IdentifierResolver::iterator I
144 = IdResolver.begin(FD->getDeclName(), FD->getDeclContext(),
Douglas Gregore267ff32008-12-11 20:41:00 +0000145 false/*LookInParentCtx*/),
146 E = IdResolver.end(); I != E; ++I) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000147 if (*I == Prev) {
148 IdResolver.RemoveDecl(*I);
149 S->RemoveDecl(*I);
150 break;
151 }
152 }
153
154 // Add the name binding for the OverloadedFunctionDecl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000155 IdResolver.AddDecl(Ovl);
Douglas Gregor44b43212008-12-11 16:49:14 +0000156
157 // Update the context with the newly-created overloaded
158 // function set.
159 FD->getDeclContext()->insert(Context, Ovl);
160
161 S->AddDecl(Ovl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000162 }
163
Douglas Gregor44b43212008-12-11 16:49:14 +0000164 // We added this function declaration to the scope earlier, but
165 // we don't want it there because it is part of the overloaded
166 // function declaration.
167 S->RemoveDecl(FD);
168
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000169 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
170 // to its list of overloads.
171 Ovl->addOverload(FD);
172
Douglas Gregor44b43212008-12-11 16:49:14 +0000173 // Add this new function declaration to the declaration context.
174 CurContext->addDecl(Context, FD, false);
175
176 return;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000177 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000178 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000179
Douglas Gregore267ff32008-12-11 20:41:00 +0000180 // Add scoped declarations into their context, so that they can be
181 // found later. Declarations without a context won't be inserted
182 // into any context.
Douglas Gregor44b43212008-12-11 16:49:14 +0000183 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
184 CurContext->addDecl(Context, SD);
Douglas Gregor44b43212008-12-11 16:49:14 +0000185
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000186 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000187}
188
Steve Naroffb216c882007-10-09 22:01:59 +0000189void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000190 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000191 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
192 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000193
Reid Spencer5f016e22007-07-11 17:01:13 +0000194 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
195 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000196 Decl *TmpD = static_cast<Decl*>(*I);
197 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000198
Douglas Gregor44b43212008-12-11 16:49:14 +0000199 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
200 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000201
Douglas Gregor44b43212008-12-11 16:49:14 +0000202 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000203
Douglas Gregor44b43212008-12-11 16:49:14 +0000204 // Remove this name from our lexical scope.
205 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 }
207}
208
Steve Naroffe8043c32008-04-01 23:04:06 +0000209/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
210/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000211ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000212 // The third "scope" argument is 0 since we aren't enabling lazy built-in
213 // creation from this context.
214 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000215
Steve Naroffb327ce02008-04-02 14:35:35 +0000216 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000217}
218
Steve Naroffe8043c32008-04-01 23:04:06 +0000219/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000220/// namespace.
Douglas Gregor2def4832008-11-17 20:34:05 +0000221Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000222 const DeclContext *LookupCtx,
Douglas Gregor44b43212008-12-11 16:49:14 +0000223 bool enableLazyBuiltinCreation,
224 bool LookInParent) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000225 if (!Name) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000226 unsigned NS = NSI;
227 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
228 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000229
Douglas Gregore267ff32008-12-11 20:41:00 +0000230 if (LookupCtx == 0 &&
231 (!getLangOptions().CPlusPlus || (NS == Decl::IDNS_Label))) {
232 // Unqualified name lookup in C/Objective-C and name lookup for
233 // labels in C++ is purely lexical, so search in the
234 // declarations attached to the name.
235 assert(!LookupCtx && "Can't perform qualified name lookup here");
236 IdentifierResolver::iterator I
237 = IdResolver.begin(Name, CurContext, LookInParent);
238
239 // Scan up the scope chain looking for a decl that matches this
240 // identifier that is in the appropriate namespace. This search
241 // should not take long, as shadowing of names is uncommon, and
242 // deep shadowing is extremely uncommon.
243 for (; I != IdResolver.end(); ++I)
244 if ((*I)->getIdentifierNamespace() & NS)
245 return *I;
246 } else if (LookupCtx) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000247 assert(getLangOptions().CPlusPlus && "No qualified name lookup in C");
248
Douglas Gregor9d350972008-12-12 08:25:50 +0000249 switch (Name.getNameKind()) {
250 case DeclarationName::CXXConstructorName:
251 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(LookupCtx))
252 return const_cast<CXXRecordDecl *>(Record)->getConstructors();
253 else
254 return 0;
255
256 case DeclarationName::CXXDestructorName:
257 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(LookupCtx))
258 return Record->getDestructor();
259 else
260 return 0;
261
262 default:
263 // Normal name lookup.
264 break;
265 }
266
Douglas Gregor44b43212008-12-11 16:49:14 +0000267 // Perform qualified name lookup into the LookupCtx.
268 // FIXME: Will need to look into base classes and such.
Douglas Gregore267ff32008-12-11 20:41:00 +0000269 DeclContext::lookup_const_iterator I, E;
270 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
271 if ((*I)->getIdentifierNamespace() & NS)
272 return *I;
273 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000274 // Name lookup for ordinary names and tag names in C++ requires
275 // looking into scopes that aren't strictly lexical, and
276 // therefore we walk through the context as well as walking
277 // through the scopes.
278 IdentifierResolver::iterator
279 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
280 IEnd = IdResolver.end();
281 for (; S; S = S->getParent()) {
282 // Check whether the IdResolver has anything in this scope.
283 // FIXME: The isDeclScope check could be expensive. Can we do better?
284 for (; I != IEnd && S->isDeclScope(*I); ++I)
285 if ((*I)->getIdentifierNamespace() & NS)
286 return *I;
287
288 // If there is an entity associated with this scope, it's a
289 // DeclContext. We might need to perform qualified lookup into
290 // it.
291 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
292 while (Ctx && Ctx->isFunctionOrMethod())
293 Ctx = Ctx->getParent();
294 while (Ctx && (Ctx->isNamespace() || Ctx->isCXXRecord())) {
295 // Look for declarations of this name in this scope.
Douglas Gregore267ff32008-12-11 20:41:00 +0000296 DeclContext::lookup_const_iterator I, E;
297 for (llvm::tie(I, E) = Ctx->lookup(Context, Name); I != E; ++I) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000298 // FIXME: Cache this result in the IdResolver
Douglas Gregore267ff32008-12-11 20:41:00 +0000299 if ((*I)->getIdentifierNamespace() & NS)
300 return *I;
Douglas Gregor44b43212008-12-11 16:49:14 +0000301 }
302
303 Ctx = Ctx->getParent();
304 }
305
306 if (!LookInParent)
307 return 0;
308 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000309 }
Chris Lattner7f925cc2008-04-11 07:00:53 +0000310
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 // If we didn't find a use of this identifier, and if the identifier
312 // corresponds to a compiler builtin, create the decl object for the builtin
313 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000314 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000315 IdentifierInfo *II = Name.getAsIdentifierInfo();
316 if (enableLazyBuiltinCreation && II &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000317 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000318 // If this is a builtin on this (or all) targets, create the decl.
319 if (unsigned BuiltinID = II->getBuiltinID())
320 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
321 }
Douglas Gregor2def4832008-11-17 20:34:05 +0000322 if (getLangOptions().ObjC1 && II) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000323 // @interface and @compatibility_alias introduce typedef-like names.
324 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000325 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000326 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000327 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
328 if (IDI != ObjCInterfaceDecls.end())
329 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000330 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
331 if (I != ObjCAliasDecls.end())
332 return I->second->getClassInterface();
333 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 }
335 return 0;
336}
337
Chris Lattner95e2c712008-05-05 22:18:14 +0000338void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000339 if (!Context.getBuiltinVaListType().isNull())
340 return;
341
342 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000343 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000344 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000345 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
346}
347
Reid Spencer5f016e22007-07-11 17:01:13 +0000348/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
349/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000350ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
351 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 Builtin::ID BID = (Builtin::ID)bid;
353
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000354 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000355 InitBuiltinVaListType();
356
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000357 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000358 FunctionDecl *New = FunctionDecl::Create(Context,
359 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000360 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000361 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000362
Chris Lattner95e2c712008-05-05 22:18:14 +0000363 // Create Decl objects for each parameter, adding them to the
364 // FunctionDecl.
365 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
366 llvm::SmallVector<ParmVarDecl*, 16> Params;
367 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
368 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
369 FT->getArgType(i), VarDecl::None, 0,
370 0));
371 New->setParams(&Params[0], Params.size());
372 }
373
374
375
Chris Lattner7f925cc2008-04-11 07:00:53 +0000376 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000377 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 return New;
379}
380
Sebastian Redlc42e1182008-11-11 11:37:55 +0000381/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
382/// everything from the standard library is defined.
383NamespaceDecl *Sema::GetStdNamespace() {
384 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000385 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000386 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattner8edea832008-11-20 05:45:14 +0000387 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000388 0, Global, /*enableLazyBuiltinCreation=*/false);
389 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
390 }
391 return StdNamespace;
392}
393
Reid Spencer5f016e22007-07-11 17:01:13 +0000394/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
395/// and scope as a previous declaration 'Old'. Figure out how to resolve this
396/// situation, merging decls or emitting diagnostics as appropriate.
397///
Steve Naroffe8043c32008-04-01 23:04:06 +0000398TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000399 // Allow multiple definitions for ObjC built-in typedefs.
400 // FIXME: Verify the underlying types are equivalent!
401 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000402 const IdentifierInfo *TypeID = New->getIdentifier();
403 switch (TypeID->getLength()) {
404 default: break;
405 case 2:
406 if (!TypeID->isStr("id"))
407 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000408 Context.setObjCIdType(New);
409 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000410 case 5:
411 if (!TypeID->isStr("Class"))
412 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000413 Context.setObjCClassType(New);
414 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000415 case 3:
416 if (!TypeID->isStr("SEL"))
417 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000418 Context.setObjCSelType(New);
419 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000420 case 8:
421 if (!TypeID->isStr("Protocol"))
422 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000423 Context.setObjCProtoType(New->getUnderlyingType());
424 return New;
425 }
426 // Fall through - the typedef name was not a builtin type.
427 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000428 // Verify the old decl was also a typedef.
429 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
430 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000431 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000432 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000433 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000434 return New;
435 }
436
Chris Lattner99cb9972008-07-25 18:44:27 +0000437 // If the typedef types are not identical, reject them in all languages and
438 // with any extensions enabled.
439 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
440 Context.getCanonicalType(Old->getUnderlyingType()) !=
441 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000442 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000443 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000444 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner99cb9972008-07-25 18:44:27 +0000445 return Old;
446 }
447
Eli Friedman54ecfce2008-06-11 06:20:39 +0000448 if (getLangOptions().Microsoft) return New;
449
Douglas Gregorbbe27432008-11-21 16:29:06 +0000450 // C++ [dcl.typedef]p2:
451 // In a given non-class scope, a typedef specifier can be used to
452 // redefine the name of any type declared in that scope to refer
453 // to the type to which it already refers.
454 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
455 return New;
456
457 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000458 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
459 // *either* declaration is in a system header. The code below implements
460 // this adhoc compatibility rule. FIXME: The following code will not
461 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000462 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
463 SourceManager &SrcMgr = Context.getSourceManager();
464 if (SrcMgr.isInSystemHeader(Old->getLocation()))
465 return New;
466 if (SrcMgr.isInSystemHeader(New->getLocation()))
467 return New;
468 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000469
Chris Lattner08631c52008-11-23 21:45:46 +0000470 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000471 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 return New;
473}
474
Chris Lattner6b6b5372008-06-26 18:38:35 +0000475/// DeclhasAttr - returns true if decl Declaration already has the target
476/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000477static bool DeclHasAttr(const Decl *decl, const Attr *target) {
478 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
479 if (attr->getKind() == target->getKind())
480 return true;
481
482 return false;
483}
484
485/// MergeAttributes - append attributes from the Old decl to the New one.
486static void MergeAttributes(Decl *New, Decl *Old) {
487 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
488
Chris Lattnerddee4232008-03-03 03:28:21 +0000489 while (attr) {
490 tmp = attr;
491 attr = attr->getNext();
492
493 if (!DeclHasAttr(New, tmp)) {
494 New->addAttr(tmp);
495 } else {
496 tmp->setNext(0);
497 delete(tmp);
498 }
499 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000500
501 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000502}
503
Chris Lattner04421082008-04-08 04:40:51 +0000504/// MergeFunctionDecl - We just parsed a function 'New' from
505/// declarator D which has the same name and scope as a previous
506/// declaration 'Old'. Figure out how to resolve this situation,
507/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000508/// Redeclaration will be set true if this New is a redeclaration OldD.
509///
510/// In C++, New and Old must be declarations that are not
511/// overloaded. Use IsOverload to determine whether New and Old are
512/// overloaded, and to select the Old declaration that New should be
513/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000514FunctionDecl *
515Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000516 assert(!isa<OverloadedFunctionDecl>(OldD) &&
517 "Cannot merge with an overloaded function declaration");
518
Douglas Gregorf0097952008-04-21 02:02:58 +0000519 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 // Verify the old decl was also a function.
521 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
522 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000523 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000524 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000525 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000526 return New;
527 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000528
529 // Determine whether the previous declaration was a definition,
530 // implicit declaration, or a declaration.
531 diag::kind PrevDiag;
532 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000533 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000534 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000535 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000536 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000537 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000538
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000539 QualType OldQType = Context.getCanonicalType(Old->getType());
540 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000541
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000542 if (getLangOptions().CPlusPlus) {
543 // (C++98 13.1p2):
544 // Certain function declarations cannot be overloaded:
545 // -- Function declarations that differ only in the return type
546 // cannot be overloaded.
547 QualType OldReturnType
548 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
549 QualType NewReturnType
550 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
551 if (OldReturnType != NewReturnType) {
552 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
553 Diag(Old->getLocation(), PrevDiag);
554 return New;
555 }
556
557 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
558 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
559 if (OldMethod && NewMethod) {
560 // -- Member function declarations with the same name and the
561 // same parameter types cannot be overloaded if any of them
562 // is a static member function declaration.
563 if (OldMethod->isStatic() || NewMethod->isStatic()) {
564 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
565 Diag(Old->getLocation(), PrevDiag);
566 return New;
567 }
568 }
569
570 // (C++98 8.3.5p3):
571 // All declarations for a function shall agree exactly in both the
572 // return type and the parameter-type-list.
573 if (OldQType == NewQType) {
574 // We have a redeclaration.
575 MergeAttributes(New, Old);
576 Redeclaration = true;
577 return MergeCXXFunctionDecl(New, Old);
578 }
579
580 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000581 }
Chris Lattner04421082008-04-08 04:40:51 +0000582
583 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000584 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000585 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000586 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000587 MergeAttributes(New, Old);
588 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000589 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000590 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000591
Steve Naroff837618c2008-01-16 15:01:34 +0000592 // A function that has already been declared has been redeclared or defined
593 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000594
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
596 // TODO: This is totally simplistic. It should handle merging functions
597 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000598 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000599 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000600 return New;
601}
602
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000603/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000604static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000605 if (VD->isFileVarDecl())
606 return (!VD->getInit() &&
607 (VD->getStorageClass() == VarDecl::None ||
608 VD->getStorageClass() == VarDecl::Static));
609 return false;
610}
611
612/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
613/// when dealing with C "tentative" external object definitions (C99 6.9.2).
614void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
615 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000616 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000617
618 for (IdentifierResolver::iterator
619 I = IdResolver.begin(VD->getIdentifier(),
620 VD->getDeclContext(), false/*LookInParentCtx*/),
621 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000622 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000623 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
624
Steve Narofff855e6f2008-08-10 15:20:13 +0000625 // Handle the following case:
626 // int a[10];
627 // int a[]; - the code below makes sure we set the correct type.
628 // int a[11]; - this is an error, size isn't 10.
629 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
630 OldDecl->getType()->isConstantArrayType())
631 VD->setType(OldDecl->getType());
632
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000633 // Check for "tentative" definitions. We can't accomplish this in
634 // MergeVarDecl since the initializer hasn't been attached.
635 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
636 continue;
637
638 // Handle __private_extern__ just like extern.
639 if (OldDecl->getStorageClass() != VarDecl::Extern &&
640 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
641 VD->getStorageClass() != VarDecl::Extern &&
642 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000643 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000644 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000645 }
646 }
647 }
648}
649
Reid Spencer5f016e22007-07-11 17:01:13 +0000650/// MergeVarDecl - We just parsed a variable 'New' which has the same name
651/// and scope as a previous declaration 'Old'. Figure out how to resolve this
652/// situation, merging decls or emitting diagnostics as appropriate.
653///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000654/// Tentative definition rules (C99 6.9.2p2) are checked by
655/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
656/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000657///
Steve Naroffe8043c32008-04-01 23:04:06 +0000658VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000659 // Verify the old decl was also a variable.
660 VarDecl *Old = dyn_cast<VarDecl>(OldD);
661 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000662 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000663 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000664 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000665 return New;
666 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000667
668 MergeAttributes(New, Old);
669
Reid Spencer5f016e22007-07-11 17:01:13 +0000670 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000671 QualType OldCType = Context.getCanonicalType(Old->getType());
672 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000673 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner08631c52008-11-23 21:45:46 +0000674 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000675 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000676 return New;
677 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000678 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
679 if (New->getStorageClass() == VarDecl::Static &&
680 (Old->getStorageClass() == VarDecl::None ||
681 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000682 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000683 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000684 return New;
685 }
686 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
687 if (New->getStorageClass() != VarDecl::Static &&
688 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000689 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000690 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000691 return New;
692 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000693 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
694 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000695 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000696 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 }
698 return New;
699}
700
Chris Lattner04421082008-04-08 04:40:51 +0000701/// CheckParmsForFunctionDef - Check that the parameters of the given
702/// function are appropriate for the definition of a function. This
703/// takes care of any checks that cannot be performed on the
704/// declaration itself, e.g., that the types of each of the function
705/// parameters are complete.
706bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
707 bool HasInvalidParm = false;
708 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
709 ParmVarDecl *Param = FD->getParamDecl(p);
710
711 // C99 6.7.5.3p4: the parameters in a parameter type list in a
712 // function declarator that is part of a function definition of
713 // that function shall not have incomplete type.
714 if (Param->getType()->isIncompleteType() &&
715 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000716 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000717 << Param->getType();
Chris Lattner04421082008-04-08 04:40:51 +0000718 Param->setInvalidDecl();
719 HasInvalidParm = true;
720 }
721 }
722
723 return HasInvalidParm;
724}
725
Reid Spencer5f016e22007-07-11 17:01:13 +0000726/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
727/// no declarator (e.g. "struct foo;") is parsed.
728Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
729 // TODO: emit error on 'int;' or 'const enum foo;'.
730 // TODO: emit error on 'typedef int;'
731 // if (!DS.isMissingDeclaratorOk()) Diag(...);
732
Steve Naroff92199282007-11-17 21:37:36 +0000733 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000734}
735
Steve Naroffd0091aa2008-01-10 22:15:12 +0000736bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000737 // Get the type before calling CheckSingleAssignmentConstraints(), since
738 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000739 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000740
Chris Lattner5cf216b2008-01-04 18:04:52 +0000741 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
742 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
743 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000744}
745
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000746bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000747 const ArrayType *AT = Context.getAsArrayType(DeclT);
748
749 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000750 // C99 6.7.8p14. We have an array of character type with unknown size
751 // being initialized to a string literal.
752 llvm::APSInt ConstVal(32);
753 ConstVal = strLiteral->getByteLength() + 1;
754 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000755 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000756 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000757 } else {
758 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000759 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000760 // FIXME: Avoid truncation for 64-bit length strings.
761 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000762 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000763 diag::warn_initializer_string_for_char_array_too_long)
764 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000765 }
766 // Set type from "char *" to "constant array of char".
767 strLiteral->setType(DeclT);
768 // For now, we always return false (meaning success).
769 return false;
770}
771
772StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000773 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000774 if (AT && AT->getElementType()->isCharType()) {
775 return dyn_cast<StringLiteral>(Init);
776 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000777 return 0;
778}
779
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000780bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
781 SourceLocation InitLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000782 DeclarationName InitEntity) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000783 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +0000784 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000785 // (8.3.2), shall be initialized by an object, or function, of
786 // type T or by an object that can be converted into a T.
787 if (DeclType->isReferenceType())
788 return CheckReferenceInit(Init, DeclType);
789
Steve Naroffca107302008-01-21 23:53:58 +0000790 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
791 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000792 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000793 return Diag(InitLoc, diag::err_variable_object_no_init)
794 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +0000795
Steve Naroff2fdc3742007-12-10 22:44:33 +0000796 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
797 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000798 // FIXME: Handle wide strings
799 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
800 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000801
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000802 // C++ [dcl.init]p14:
803 // -- If the destination type is a (possibly cv-qualified) class
804 // type:
805 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
806 QualType DeclTypeC = Context.getCanonicalType(DeclType);
807 QualType InitTypeC = Context.getCanonicalType(Init->getType());
808
809 // -- If the initialization is direct-initialization, or if it is
810 // copy-initialization where the cv-unqualified version of the
811 // source type is the same class as, or a derived class of, the
812 // class of the destination, constructors are considered.
813 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
814 IsDerivedFrom(InitTypeC, DeclTypeC)) {
815 CXXConstructorDecl *Constructor
816 = PerformInitializationByConstructor(DeclType, &Init, 1,
817 InitLoc, Init->getSourceRange(),
818 InitEntity, IK_Copy);
819 return Constructor == 0;
820 }
821
822 // -- Otherwise (i.e., for the remaining copy-initialization
823 // cases), user-defined conversion sequences that can
824 // convert from the source type to the destination type or
825 // (when a conversion function is used) to a derived class
826 // thereof are enumerated as described in 13.3.1.4, and the
827 // best one is chosen through overload resolution
828 // (13.3). If the conversion cannot be done or is
829 // ambiguous, the initialization is ill-formed. The
830 // function selected is called with the initializer
831 // expression as its argument; if the function is a
832 // constructor, the call initializes a temporary of the
833 // destination type.
834 // FIXME: We're pretending to do copy elision here; return to
835 // this when we have ASTs for such things.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000836 if (!PerformImplicitConversion(Init, DeclType))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000837 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000838
839 return Diag(InitLoc, diag::err_typecheck_convert_incompatible)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000840 << DeclType << InitEntity << "initializing"
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000841 << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000842 }
843
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000844 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000845 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000846 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
847 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +0000848
Steve Naroffd0091aa2008-01-10 22:15:12 +0000849 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000850 } else if (getLangOptions().CPlusPlus) {
851 // C++ [dcl.init]p14:
852 // [...] If the class is an aggregate (8.5.1), and the initializer
853 // is a brace-enclosed list, see 8.5.1.
854 //
855 // Note: 8.5.1 is handled below; here, we diagnose the case where
856 // we have an initializer list and a destination type that is not
857 // an aggregate.
858 // FIXME: In C++0x, this is yet another form of initialization.
859 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
860 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
861 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000862 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +0000863 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +0000864 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000865 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000866
Steve Naroff0cca7492008-05-01 22:18:59 +0000867 InitListChecker CheckInitList(this, InitList, DeclType);
868 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000869}
870
Douglas Gregor10bd3682008-11-17 22:58:34 +0000871/// GetNameForDeclarator - Determine the full declaration name for the
872/// given Declarator.
873DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
874 switch (D.getKind()) {
875 case Declarator::DK_Abstract:
876 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
877 return DeclarationName();
878
879 case Declarator::DK_Normal:
880 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
881 return DeclarationName(D.getIdentifier());
882
883 case Declarator::DK_Constructor: {
884 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
885 Ty = Context.getCanonicalType(Ty);
886 return Context.DeclarationNames.getCXXConstructorName(Ty);
887 }
888
889 case Declarator::DK_Destructor: {
890 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
891 Ty = Context.getCanonicalType(Ty);
892 return Context.DeclarationNames.getCXXDestructorName(Ty);
893 }
894
895 case Declarator::DK_Conversion: {
896 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
897 Ty = Context.getCanonicalType(Ty);
898 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
899 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000900
901 case Declarator::DK_Operator:
902 assert(D.getIdentifier() == 0 && "operator names have no identifier");
903 return Context.DeclarationNames.getCXXOperatorName(
904 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000905 }
906
907 assert(false && "Unknown name kind");
908 return DeclarationName();
909}
910
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000911Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000912Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000913 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +0000914 DeclarationName Name = GetNameForDeclarator(D);
915
Chris Lattnere80a59c2007-07-25 00:24:17 +0000916 // All of these full declarators require an identifier. If it doesn't have
917 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +0000918 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +0000919 if (!D.getInvalidType()) // Reject this if we think it is valid.
920 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000921 diag::err_declarator_need_ident)
922 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +0000923 return 0;
924 }
925
Chris Lattner31e05722007-08-26 06:24:45 +0000926 // The scope passed in may not be a decl scope. Zip up the scope tree until
927 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +0000928 while ((S->getFlags() & Scope::DeclScope) == 0 ||
929 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +0000930 S = S->getParent();
931
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000932 DeclContext *DC;
933 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +0000934 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000935 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000936
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000937 // See if this is a redefinition of a variable in the same scope.
938 if (!D.getCXXScopeSpec().isSet()) {
939 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +0000940 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000941 } else { // Something like "int foo::x;"
942 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000943 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000944
945 // C++ 7.3.1.2p2:
946 // Members (including explicit specializations of templates) of a named
947 // namespace can also be defined outside that namespace by explicit
948 // qualification of the name being defined, provided that the entity being
949 // defined was already declared in the namespace and the definition appears
950 // after the point of declaration in a namespace that encloses the
951 // declarations namespace.
952 //
Douglas Gregor9d350972008-12-12 08:25:50 +0000953 // FIXME: We need to perform this check later, once we know that
954 // we've actually found a redeclaration. Otherwise, just the fact
955 // that there is some entity with the same name will suppress this
956 // diagnostic, e.g., we fail to diagnose:
957 // class X {
958 // void f();
959 // };
960 //
961 // void X::f(int) { } // ill-formed, but we don't complain.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000962 if (PrevDecl == 0) {
963 // No previous declaration in the qualifying scope.
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000964 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
Chris Lattner08631c52008-11-23 21:45:46 +0000965 << Name << D.getCXXScopeSpec().getRange();
Douglas Gregor44b43212008-12-11 16:49:14 +0000966 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000967 } else if (!CurContext->Encloses(DC)) {
968 // The qualifying scope doesn't enclose the original declaration.
969 // Emit diagnostic based on current scope.
970 SourceLocation L = D.getIdentifierLoc();
971 SourceRange R = D.getCXXScopeSpec().getRange();
972 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +0000973 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000974 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +0000975 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000976 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000977 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000978 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000979 }
980 }
981
Douglas Gregorf57172b2008-12-08 18:40:42 +0000982 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000983 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +0000984 InvalidDecl = InvalidDecl
985 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000986 // Just pretend that we didn't see the previous declaration.
987 PrevDecl = 0;
988 }
989
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000990 // In C++, the previous declaration we find might be a tag type
991 // (class or enum). In this case, the new declaration will hide the
992 // tag type.
993 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
994 PrevDecl = 0;
995
Chris Lattner41af0932007-11-14 06:34:38 +0000996 QualType R = GetTypeForDeclarator(D, S);
997 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
998
Reid Spencer5f016e22007-07-11 17:01:13 +0000999 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001000 // Check that there are no default arguments (C++ only).
1001 if (getLangOptions().CPlusPlus)
1002 CheckExtraCXXDefaultArguments(D);
1003
Chris Lattner41af0932007-11-14 06:34:38 +00001004 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +00001005 if (!NewTD) return 0;
1006
1007 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001008 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +00001009 // Merge the decl with the existing one if appropriate. If the decl is
1010 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001011 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001012 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1013 if (NewTD == 0) return 0;
1014 }
1015 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001016 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001017 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1018 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +00001019 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001020 if (NewTD->getUnderlyingType()->isVariableArrayType())
1021 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1022 else
1023 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1024
Steve Naroffd7444aa2007-08-31 17:20:07 +00001025 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001026 }
1027 }
Chris Lattner41af0932007-11-14 06:34:38 +00001028 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +00001029 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +00001030 switch (D.getDeclSpec().getStorageClassSpec()) {
1031 default: assert(0 && "Unknown storage class!");
1032 case DeclSpec::SCS_auto:
1033 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +00001034 case DeclSpec::SCS_mutable:
Chris Lattnerd1625842008-11-24 06:25:27 +00001035 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroff5912a352007-08-28 20:14:24 +00001036 InvalidDecl = true;
1037 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001038 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1039 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1040 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +00001041 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001042 }
1043
Chris Lattnera98e58d2008-03-15 21:24:04 +00001044 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001045 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +00001046 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1047
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001048 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001049 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +00001050 // This is a C++ constructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001051 assert(DC->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +00001052 "Constructors can only be declared in a member context");
1053
Douglas Gregor42a552f2008-11-05 20:51:48 +00001054 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001055
1056 // Create the new declaration
1057 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001058 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001059 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +00001060 isExplicit, isInline,
1061 /*isImplicitlyDeclared=*/false);
1062
Douglas Gregor42a552f2008-11-05 20:51:48 +00001063 if (isInvalidDecl)
1064 NewFD->setInvalidDecl();
1065 } else if (D.getKind() == Declarator::DK_Destructor) {
1066 // This is a C++ destructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001067 if (DC->isCXXRecord()) {
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001068 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001069
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001070 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001071 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001072 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001073 isInline,
1074 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001075
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001076 if (isInvalidDecl)
1077 NewFD->setInvalidDecl();
1078 } else {
1079 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1080 // Create a FunctionDecl to satisfy the function definition parsing
1081 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001082 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001083 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001084 // FIXME: Move to DeclGroup...
1085 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001086 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001087 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001088 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001089 if (!DC->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001090 Diag(D.getIdentifierLoc(),
1091 diag::err_conv_function_not_member);
1092 return 0;
1093 } else {
1094 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
1095
1096 NewFD = CXXConversionDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001097 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001098 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001099 isInline, isExplicit);
1100
1101 if (isInvalidDecl)
1102 NewFD->setInvalidDecl();
1103 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001104 } else if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001105 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001106 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001107 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001108 (SC == FunctionDecl::Static), isInline,
1109 LastDeclarator);
1110 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001111 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001112 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001113 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001114 // FIXME: Move to DeclGroup...
1115 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001116 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +00001117 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +00001118 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +00001119
Daniel Dunbara80f8742008-08-05 01:35:17 +00001120 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +00001121 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +00001122 // The parser guarantees this is a string.
1123 StringLiteral *SE = cast<StringLiteral>(E);
1124 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1125 SE->getByteLength())));
1126 }
1127
Chris Lattner04421082008-04-08 04:40:51 +00001128 // Copy the parameter declarations from the declarator D to
1129 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001130 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001131 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1132
1133 // Create Decl objects for each parameter, adding them to the
1134 // FunctionDecl.
1135 llvm::SmallVector<ParmVarDecl*, 16> Params;
1136
1137 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1138 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001139 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001140 // We let through "const void" here because Sema::GetTypeForDeclarator
1141 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001142 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1143 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001144 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1145 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001146 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1147
Chris Lattnerdef026a2008-04-10 02:26:16 +00001148 // In C++, the empty parameter-type-list must be spelled "void"; a
1149 // typedef of void is not permitted.
1150 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001151 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001152 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1153 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001154 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001155 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1156 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1157 }
1158
1159 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001160 } else if (R->getAsTypedefType()) {
1161 // When we're declaring a function with a typedef, as in the
1162 // following example, we'll need to synthesize (unnamed)
1163 // parameters for use in the declaration.
1164 //
1165 // @code
1166 // typedef void fn(int);
1167 // fn f;
1168 // @endcode
1169 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1170 if (!FT) {
1171 // This is a typedef of a function with no prototype, so we
1172 // don't need to do anything.
1173 } else if ((FT->getNumArgs() == 0) ||
1174 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1175 FT->getArgType(0)->isVoidType())) {
1176 // This is a zero-argument function. We don't need to do anything.
1177 } else {
1178 // Synthesize a parameter for each argument type.
1179 llvm::SmallVector<ParmVarDecl*, 16> Params;
1180 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1181 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001182 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001183 SourceLocation(), 0,
1184 *ArgType, VarDecl::None,
1185 0, 0));
1186 }
1187
1188 NewFD->setParams(&Params[0], Params.size());
1189 }
Chris Lattner04421082008-04-08 04:40:51 +00001190 }
1191
Douglas Gregor42a552f2008-11-05 20:51:48 +00001192 // C++ constructors and destructors are handled by separate
1193 // routines, since they don't require any declaration merging (C++
1194 // [class.mfct]p2) and they aren't ever pushed into scope, because
1195 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1196 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1197 return ActOnConstructorDeclarator(Constructor);
1198 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1199 return ActOnDestructorDeclarator(Destructor);
Douglas Gregor2def4832008-11-17 20:34:05 +00001200
1201 // Extra checking for conversion functions, including recording
1202 // the conversion function in its class.
1203 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1204 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001205
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001206 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1207 if (NewFD->isOverloadedOperator() &&
1208 CheckOverloadedOperatorDeclaration(NewFD))
1209 NewFD->setInvalidDecl();
1210
Steve Naroffffce4d52008-01-09 23:34:55 +00001211 // Merge the decl with the existing one if appropriate. Since C functions
1212 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001213 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001214 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001215 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001216
1217 // If C++, determine whether NewFD is an overload of PrevDecl or
1218 // a declaration that requires merging. If it's an overload,
1219 // there's no more work to do here; we'll just add the new
1220 // function to the scope.
1221 OverloadedFunctionDecl::function_iterator MatchedDecl;
1222 if (!getLangOptions().CPlusPlus ||
1223 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1224 Decl *OldDecl = PrevDecl;
1225
1226 // If PrevDecl was an overloaded function, extract the
1227 // FunctionDecl that matched.
1228 if (isa<OverloadedFunctionDecl>(PrevDecl))
1229 OldDecl = *MatchedDecl;
1230
1231 // NewFD and PrevDecl represent declarations that need to be
1232 // merged.
1233 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1234
1235 if (NewFD == 0) return 0;
1236 if (Redeclaration) {
1237 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1238
1239 if (OldDecl == PrevDecl) {
1240 // Remove the name binding for the previous
Douglas Gregor44b43212008-12-11 16:49:14 +00001241 // declaration.
1242 if (S->isDeclScope(PrevDecl)) {
1243 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1244 S->RemoveDecl(PrevDecl);
1245 }
1246
1247 // Introduce the new binding for this declaration.
1248 IdResolver.AddDecl(NewFD);
1249 if (getLangOptions().CPlusPlus && NewFD->getParent())
1250 NewFD->getParent()->insert(Context, NewFD);
1251
1252 // Add the redeclaration to the current scope, since we'll
1253 // be skipping PushOnScopeChains.
1254 S->AddDecl(NewFD);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001255 } else {
1256 // We need to update the OverloadedFunctionDecl with the
1257 // latest declaration of this function, so that name
1258 // lookup will always refer to the latest declaration of
1259 // this function.
1260 *MatchedDecl = NewFD;
Douglas Gregor44b43212008-12-11 16:49:14 +00001261 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001262
Douglas Gregor44b43212008-12-11 16:49:14 +00001263 if (getLangOptions().CPlusPlus) {
1264 // Add this declaration to the current context.
1265 CurContext->addDecl(Context, NewFD, false);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001266
Douglas Gregor44b43212008-12-11 16:49:14 +00001267 // Check default arguments now that we have merged decls.
1268 CheckCXXDefaultArguments(NewFD);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001269 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001270
1271 // Set the lexical context. If the declarator has a C++
1272 // scope specifier, the lexical context will be different
1273 // from the semantic context.
1274 NewFD->setLexicalDeclContext(CurContext);
1275
1276 return NewFD;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001277 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001278 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001279 }
1280 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001281
1282 // In C++, check default arguments now that we have merged decls.
1283 if (getLangOptions().CPlusPlus)
1284 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001286 // Check that there are no default arguments (C++ only).
1287 if (getLangOptions().CPlusPlus)
1288 CheckExtraCXXDefaultArguments(D);
1289
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001290 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001291 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1292 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001293 InvalidDecl = true;
1294 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001295
1296 VarDecl *NewVD;
1297 VarDecl::StorageClass SC;
1298 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001299 default: assert(0 && "Unknown storage class!");
1300 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1301 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1302 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1303 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1304 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1305 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001306 case DeclSpec::SCS_mutable:
1307 // mutable can only appear on non-static class members, so it's always
1308 // an error here
1309 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1310 InvalidDecl = true;
Douglas Gregore89b0282008-12-01 22:46:22 +00001311 SC = VarDecl::None;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001312 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001313 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001314
1315 IdentifierInfo *II = Name.getAsIdentifierInfo();
1316 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001317 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1318 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001319 return 0;
1320 }
1321
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001322 if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001323 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1324 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001325 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001326 D.getIdentifierLoc(), II,
1327 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001328 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001329 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001330 if (S->getFnParent() == 0) {
1331 // C99 6.9p2: The storage-class specifiers auto and register shall not
1332 // appear in the declaration specifiers in an external declaration.
1333 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerd1625842008-11-24 06:25:27 +00001334 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001335 InvalidDecl = true;
1336 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001337 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001338 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1339 II, R, SC, LastDeclarator,
1340 // FIXME: Move to DeclGroup...
1341 D.getDeclSpec().getSourceRange().getBegin());
1342 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001343 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001345 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001346
Daniel Dunbara735ad82008-08-06 00:03:29 +00001347 // Handle GNU asm-label extension (encoded as an attribute).
1348 if (Expr *E = (Expr*) D.getAsmLabel()) {
1349 // The parser guarantees this is a string.
1350 StringLiteral *SE = cast<StringLiteral>(E);
1351 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1352 SE->getByteLength())));
1353 }
1354
Nate Begemanc8e89a82008-03-14 18:07:10 +00001355 // Emit an error if an address space was applied to decl with local storage.
1356 // This includes arrays of objects with address space qualifiers, but not
1357 // automatic variables that point to other address spaces.
1358 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001359 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1360 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1361 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001362 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001363 // Merge the decl with the existing one if appropriate. If the decl is
1364 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001365 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 NewVD = MergeVarDecl(NewVD, PrevDecl);
1367 if (NewVD == 0) return 0;
1368 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 New = NewVD;
1370 }
1371
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001372 // Set the lexical context. If the declarator has a C++ scope specifier, the
1373 // lexical context will be different from the semantic context.
1374 New->setLexicalDeclContext(CurContext);
1375
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001377 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001378 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001379 // If any semantic error occurred, mark the decl as invalid.
1380 if (D.getInvalidType() || InvalidDecl)
1381 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001382
1383 return New;
1384}
1385
Steve Naroff6594a702008-10-27 11:34:16 +00001386void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001387 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1388 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001389}
1390
Eli Friedmanc594b322008-05-20 13:48:25 +00001391bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1392 switch (Init->getStmtClass()) {
1393 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001394 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001395 return true;
1396 case Expr::ParenExprClass: {
1397 const ParenExpr* PE = cast<ParenExpr>(Init);
1398 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1399 }
1400 case Expr::CompoundLiteralExprClass:
1401 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1402 case Expr::DeclRefExprClass: {
1403 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001404 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1405 if (VD->hasGlobalStorage())
1406 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001407 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001408 return true;
1409 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001410 if (isa<FunctionDecl>(D))
1411 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001412 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001413 return true;
1414 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001415 case Expr::MemberExprClass: {
1416 const MemberExpr *M = cast<MemberExpr>(Init);
1417 if (M->isArrow())
1418 return CheckAddressConstantExpression(M->getBase());
1419 return CheckAddressConstantExpressionLValue(M->getBase());
1420 }
1421 case Expr::ArraySubscriptExprClass: {
1422 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1423 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1424 return CheckAddressConstantExpression(ASE->getBase()) ||
1425 CheckArithmeticConstantExpression(ASE->getIdx());
1426 }
1427 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001428 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001429 return false;
1430 case Expr::UnaryOperatorClass: {
1431 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1432
1433 // C99 6.6p9
1434 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001435 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001436
Steve Naroff6594a702008-10-27 11:34:16 +00001437 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001438 return true;
1439 }
1440 }
1441}
1442
1443bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1444 switch (Init->getStmtClass()) {
1445 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001446 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001447 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001448 case Expr::ParenExprClass:
1449 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001450 case Expr::StringLiteralClass:
1451 case Expr::ObjCStringLiteralClass:
1452 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001453 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001454 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001455 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1456 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1457 Builtin::BI__builtin___CFStringMakeConstantString)
1458 return false;
1459
Steve Naroff6594a702008-10-27 11:34:16 +00001460 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001461 return true;
1462
Eli Friedmanc594b322008-05-20 13:48:25 +00001463 case Expr::UnaryOperatorClass: {
1464 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1465
1466 // C99 6.6p9
1467 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1468 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1469
1470 if (Exp->getOpcode() == UnaryOperator::Extension)
1471 return CheckAddressConstantExpression(Exp->getSubExpr());
1472
Steve Naroff6594a702008-10-27 11:34:16 +00001473 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001474 return true;
1475 }
1476 case Expr::BinaryOperatorClass: {
1477 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1478 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1479
1480 Expr *PExp = Exp->getLHS();
1481 Expr *IExp = Exp->getRHS();
1482 if (IExp->getType()->isPointerType())
1483 std::swap(PExp, IExp);
1484
1485 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1486 return CheckAddressConstantExpression(PExp) ||
1487 CheckArithmeticConstantExpression(IExp);
1488 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001489 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001490 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001491 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001492 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1493 // Check for implicit promotion
1494 if (SubExpr->getType()->isFunctionType() ||
1495 SubExpr->getType()->isArrayType())
1496 return CheckAddressConstantExpressionLValue(SubExpr);
1497 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001498
1499 // Check for pointer->pointer cast
1500 if (SubExpr->getType()->isPointerType())
1501 return CheckAddressConstantExpression(SubExpr);
1502
Eli Friedmanc3f07642008-08-25 20:46:57 +00001503 if (SubExpr->getType()->isIntegralType()) {
1504 // Check for the special-case of a pointer->int->pointer cast;
1505 // this isn't standard, but some code requires it. See
1506 // PR2720 for an example.
1507 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1508 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1509 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1510 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1511 if (IntWidth >= PointerWidth) {
1512 return CheckAddressConstantExpression(SubCast->getSubExpr());
1513 }
1514 }
1515 }
1516 }
1517 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001518 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001519 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001520
Steve Naroff6594a702008-10-27 11:34:16 +00001521 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001522 return true;
1523 }
1524 case Expr::ConditionalOperatorClass: {
1525 // FIXME: Should we pedwarn here?
1526 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1527 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001528 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001529 return true;
1530 }
1531 if (CheckArithmeticConstantExpression(Exp->getCond()))
1532 return true;
1533 if (Exp->getLHS() &&
1534 CheckAddressConstantExpression(Exp->getLHS()))
1535 return true;
1536 return CheckAddressConstantExpression(Exp->getRHS());
1537 }
1538 case Expr::AddrLabelExprClass:
1539 return false;
1540 }
1541}
1542
Eli Friedman4caf0552008-06-09 05:05:07 +00001543static const Expr* FindExpressionBaseAddress(const Expr* E);
1544
1545static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1546 switch (E->getStmtClass()) {
1547 default:
1548 return E;
1549 case Expr::ParenExprClass: {
1550 const ParenExpr* PE = cast<ParenExpr>(E);
1551 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1552 }
1553 case Expr::MemberExprClass: {
1554 const MemberExpr *M = cast<MemberExpr>(E);
1555 if (M->isArrow())
1556 return FindExpressionBaseAddress(M->getBase());
1557 return FindExpressionBaseAddressLValue(M->getBase());
1558 }
1559 case Expr::ArraySubscriptExprClass: {
1560 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1561 return FindExpressionBaseAddress(ASE->getBase());
1562 }
1563 case Expr::UnaryOperatorClass: {
1564 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1565
1566 if (Exp->getOpcode() == UnaryOperator::Deref)
1567 return FindExpressionBaseAddress(Exp->getSubExpr());
1568
1569 return E;
1570 }
1571 }
1572}
1573
1574static const Expr* FindExpressionBaseAddress(const Expr* E) {
1575 switch (E->getStmtClass()) {
1576 default:
1577 return E;
1578 case Expr::ParenExprClass: {
1579 const ParenExpr* PE = cast<ParenExpr>(E);
1580 return FindExpressionBaseAddress(PE->getSubExpr());
1581 }
1582 case Expr::UnaryOperatorClass: {
1583 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1584
1585 // C99 6.6p9
1586 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1587 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1588
1589 if (Exp->getOpcode() == UnaryOperator::Extension)
1590 return FindExpressionBaseAddress(Exp->getSubExpr());
1591
1592 return E;
1593 }
1594 case Expr::BinaryOperatorClass: {
1595 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1596
1597 Expr *PExp = Exp->getLHS();
1598 Expr *IExp = Exp->getRHS();
1599 if (IExp->getType()->isPointerType())
1600 std::swap(PExp, IExp);
1601
1602 return FindExpressionBaseAddress(PExp);
1603 }
1604 case Expr::ImplicitCastExprClass: {
1605 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1606
1607 // Check for implicit promotion
1608 if (SubExpr->getType()->isFunctionType() ||
1609 SubExpr->getType()->isArrayType())
1610 return FindExpressionBaseAddressLValue(SubExpr);
1611
1612 // Check for pointer->pointer cast
1613 if (SubExpr->getType()->isPointerType())
1614 return FindExpressionBaseAddress(SubExpr);
1615
1616 // We assume that we have an arithmetic expression here;
1617 // if we don't, we'll figure it out later
1618 return 0;
1619 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001620 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001621 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1622
1623 // Check for pointer->pointer cast
1624 if (SubExpr->getType()->isPointerType())
1625 return FindExpressionBaseAddress(SubExpr);
1626
1627 // We assume that we have an arithmetic expression here;
1628 // if we don't, we'll figure it out later
1629 return 0;
1630 }
1631 }
1632}
1633
Anders Carlsson51fe9962008-11-22 21:04:56 +00001634bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001635 switch (Init->getStmtClass()) {
1636 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001637 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001638 return true;
1639 case Expr::ParenExprClass: {
1640 const ParenExpr* PE = cast<ParenExpr>(Init);
1641 return CheckArithmeticConstantExpression(PE->getSubExpr());
1642 }
1643 case Expr::FloatingLiteralClass:
1644 case Expr::IntegerLiteralClass:
1645 case Expr::CharacterLiteralClass:
1646 case Expr::ImaginaryLiteralClass:
1647 case Expr::TypesCompatibleExprClass:
1648 case Expr::CXXBoolLiteralExprClass:
1649 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001650 case Expr::CallExprClass:
1651 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001652 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001653
1654 // Allow any constant foldable calls to builtins.
1655 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001656 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001657
Steve Naroff6594a702008-10-27 11:34:16 +00001658 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001659 return true;
1660 }
1661 case Expr::DeclRefExprClass: {
1662 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1663 if (isa<EnumConstantDecl>(D))
1664 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001665 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001666 return true;
1667 }
1668 case Expr::CompoundLiteralExprClass:
1669 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1670 // but vectors are allowed to be magic.
1671 if (Init->getType()->isVectorType())
1672 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001673 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001674 return true;
1675 case Expr::UnaryOperatorClass: {
1676 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1677
1678 switch (Exp->getOpcode()) {
1679 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1680 // See C99 6.6p3.
1681 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001682 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001683 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001684 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00001685 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1686 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001687 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001688 return true;
1689 case UnaryOperator::Extension:
1690 case UnaryOperator::LNot:
1691 case UnaryOperator::Plus:
1692 case UnaryOperator::Minus:
1693 case UnaryOperator::Not:
1694 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1695 }
1696 }
Sebastian Redl05189992008-11-11 17:56:53 +00001697 case Expr::SizeOfAlignOfExprClass: {
1698 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001699 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00001700 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00001701 return false;
1702 // alignof always evaluates to a constant.
1703 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00001704 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001705 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001706 return true;
1707 }
1708 return false;
1709 }
1710 case Expr::BinaryOperatorClass: {
1711 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1712
1713 if (Exp->getLHS()->getType()->isArithmeticType() &&
1714 Exp->getRHS()->getType()->isArithmeticType()) {
1715 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1716 CheckArithmeticConstantExpression(Exp->getRHS());
1717 }
1718
Eli Friedman4caf0552008-06-09 05:05:07 +00001719 if (Exp->getLHS()->getType()->isPointerType() &&
1720 Exp->getRHS()->getType()->isPointerType()) {
1721 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1722 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1723
1724 // Only allow a null (constant integer) base; we could
1725 // allow some additional cases if necessary, but this
1726 // is sufficient to cover offsetof-like constructs.
1727 if (!LHSBase && !RHSBase) {
1728 return CheckAddressConstantExpression(Exp->getLHS()) ||
1729 CheckAddressConstantExpression(Exp->getRHS());
1730 }
1731 }
1732
Steve Naroff6594a702008-10-27 11:34:16 +00001733 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001734 return true;
1735 }
1736 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001737 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001738 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001739 if (SubExpr->getType()->isArithmeticType())
1740 return CheckArithmeticConstantExpression(SubExpr);
1741
Eli Friedmanb529d832008-09-02 09:37:00 +00001742 if (SubExpr->getType()->isPointerType()) {
1743 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1744 // If the pointer has a null base, this is an offsetof-like construct
1745 if (!Base)
1746 return CheckAddressConstantExpression(SubExpr);
1747 }
1748
Steve Naroff6594a702008-10-27 11:34:16 +00001749 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001750 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001751 }
1752 case Expr::ConditionalOperatorClass: {
1753 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001754
1755 // If GNU extensions are disabled, we require all operands to be arithmetic
1756 // constant expressions.
1757 if (getLangOptions().NoExtensions) {
1758 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1759 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1760 CheckArithmeticConstantExpression(Exp->getRHS());
1761 }
1762
1763 // Otherwise, we have to emulate some of the behavior of fold here.
1764 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1765 // because it can constant fold things away. To retain compatibility with
1766 // GCC code, we see if we can fold the condition to a constant (which we
1767 // should always be able to do in theory). If so, we only require the
1768 // specified arm of the conditional to be a constant. This is a horrible
1769 // hack, but is require by real world code that uses __builtin_constant_p.
1770 APValue Val;
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001771 if (!Exp->getCond()->Evaluate(Val, Context)) {
1772 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00001773 // won't be able to either. Use it to emit the diagnostic though.
1774 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001775 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00001776 return Res;
1777 }
1778
1779 // Verify that the side following the condition is also a constant.
1780 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1781 if (Val.getInt() == 0)
1782 std::swap(TrueSide, FalseSide);
1783
1784 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001785 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001786
1787 // Okay, the evaluated side evaluates to a constant, so we accept this.
1788 // Check to see if the other side is obviously not a constant. If so,
1789 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001790 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001791 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001792 diag::ext_typecheck_expression_not_constant_but_accepted)
1793 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00001794 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001795 }
1796 }
1797}
1798
1799bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001800 Expr::EvalResult Result;
1801
Nuno Lopes9a979c32008-07-07 16:46:50 +00001802 Init = Init->IgnoreParens();
1803
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001804 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
1805 return false;
1806
Eli Friedmanc594b322008-05-20 13:48:25 +00001807 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1808 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1809 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1810
Nuno Lopes9a979c32008-07-07 16:46:50 +00001811 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1812 return CheckForConstantInitializer(e->getInitializer(), DclT);
1813
Eli Friedmanc594b322008-05-20 13:48:25 +00001814 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1815 unsigned numInits = Exp->getNumInits();
1816 for (unsigned i = 0; i < numInits; i++) {
1817 // FIXME: Need to get the type of the declaration for C++,
1818 // because it could be a reference?
1819 if (CheckForConstantInitializer(Exp->getInit(i),
1820 Exp->getInit(i)->getType()))
1821 return true;
1822 }
1823 return false;
1824 }
1825
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001826 // FIXME: We can probably remove some of this code below, now that
1827 // Expr::Evaluate is doing the heavy lifting for scalars.
1828
Eli Friedmanc594b322008-05-20 13:48:25 +00001829 if (Init->isNullPointerConstant(Context))
1830 return false;
1831 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001832 QualType InitTy = Context.getCanonicalType(Init->getType())
1833 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001834 if (InitTy == Context.BoolTy) {
1835 // Special handling for pointers implicitly cast to bool;
1836 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1837 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1838 Expr* SubE = ICE->getSubExpr();
1839 if (SubE->getType()->isPointerType() ||
1840 SubE->getType()->isArrayType() ||
1841 SubE->getType()->isFunctionType()) {
1842 return CheckAddressConstantExpression(Init);
1843 }
1844 }
1845 } else if (InitTy->isIntegralType()) {
1846 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001847 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001848 SubE = CE->getSubExpr();
1849 // Special check for pointer cast to int; we allow as an extension
1850 // an address constant cast to an integer if the integer
1851 // is of an appropriate width (this sort of code is apparently used
1852 // in some places).
1853 // FIXME: Add pedwarn?
1854 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1855 if (SubE && (SubE->getType()->isPointerType() ||
1856 SubE->getType()->isArrayType() ||
1857 SubE->getType()->isFunctionType())) {
1858 unsigned IntWidth = Context.getTypeSize(Init->getType());
1859 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1860 if (IntWidth >= PointerWidth)
1861 return CheckAddressConstantExpression(Init);
1862 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001863 }
1864
1865 return CheckArithmeticConstantExpression(Init);
1866 }
1867
1868 if (Init->getType()->isPointerType())
1869 return CheckAddressConstantExpression(Init);
1870
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001871 // An array type at the top level that isn't an init-list must
1872 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001873 if (Init->getType()->isArrayType())
1874 return false;
1875
Nuno Lopes73419bf2008-09-01 18:42:41 +00001876 if (Init->getType()->isFunctionType())
1877 return false;
1878
Steve Naroff8af6a452008-10-02 17:12:56 +00001879 // Allow block exprs at top level.
1880 if (Init->getType()->isBlockPointerType())
1881 return false;
1882
Steve Naroff6594a702008-10-27 11:34:16 +00001883 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001884 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001885}
1886
Steve Naroffbb204692007-09-12 14:07:44 +00001887void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001888 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001889 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001890 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001891
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001892 // If there is no declaration, there was an error parsing it. Just ignore
1893 // the initializer.
1894 if (RealDecl == 0) {
1895 delete Init;
1896 return;
1897 }
Steve Naroffbb204692007-09-12 14:07:44 +00001898
Steve Naroff410e3e22007-09-12 20:13:48 +00001899 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1900 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001901 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1902 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001903 RealDecl->setInvalidDecl();
1904 return;
1905 }
Steve Naroffbb204692007-09-12 14:07:44 +00001906 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001907 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001908 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001909 if (VDecl->isBlockVarDecl()) {
1910 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001911 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001912 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001913 VDecl->setInvalidDecl();
1914 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001915 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001916 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001917 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001918
1919 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1920 if (!getLangOptions().CPlusPlus) {
1921 if (SC == VarDecl::Static) // C99 6.7.8p4.
1922 CheckForConstantInitializer(Init, DclT);
1923 }
Steve Naroffbb204692007-09-12 14:07:44 +00001924 }
Steve Naroff248a7532008-04-15 22:42:06 +00001925 } else if (VDecl->isFileVarDecl()) {
1926 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001927 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001928 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001929 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001930 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001931 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001932
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001933 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1934 if (!getLangOptions().CPlusPlus) {
1935 // C99 6.7.8p4. All file scoped initializers need to be constant.
1936 CheckForConstantInitializer(Init, DclT);
1937 }
Steve Naroffbb204692007-09-12 14:07:44 +00001938 }
1939 // If the type changed, it means we had an incomplete type that was
1940 // completed by the initializer. For example:
1941 // int ary[] = { 1, 3, 5 };
1942 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001943 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001944 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001945 Init->setType(DclT);
1946 }
Steve Naroffbb204692007-09-12 14:07:44 +00001947
1948 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001949 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001950 return;
1951}
1952
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001953void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1954 Decl *RealDecl = static_cast<Decl *>(dcl);
1955
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00001956 // If there is no declaration, there was an error parsing it. Just ignore it.
1957 if (RealDecl == 0)
1958 return;
1959
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001960 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1961 QualType Type = Var->getType();
1962 // C++ [dcl.init.ref]p3:
1963 // The initializer can be omitted for a reference only in a
1964 // parameter declaration (8.3.5), in the declaration of a
1965 // function return type, in the declaration of a class member
1966 // within its class declaration (9.2), and where the extern
1967 // specifier is explicitly used.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001968 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001969 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001970 << Var->getDeclName()
1971 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00001972 Var->setInvalidDecl();
1973 return;
1974 }
1975
1976 // C++ [dcl.init]p9:
1977 //
1978 // If no initializer is specified for an object, and the object
1979 // is of (possibly cv-qualified) non-POD class type (or array
1980 // thereof), the object shall be default-initialized; if the
1981 // object is of const-qualified type, the underlying class type
1982 // shall have a user-declared default constructor.
1983 if (getLangOptions().CPlusPlus) {
1984 QualType InitType = Type;
1985 if (const ArrayType *Array = Context.getAsArrayType(Type))
1986 InitType = Array->getElementType();
1987 if (InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001988 const CXXConstructorDecl *Constructor
1989 = PerformInitializationByConstructor(InitType, 0, 0,
1990 Var->getLocation(),
1991 SourceRange(Var->getLocation(),
1992 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001993 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001994 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001995 if (!Constructor)
1996 Var->setInvalidDecl();
1997 }
1998 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001999
Douglas Gregor818ce482008-10-29 13:50:18 +00002000#if 0
2001 // FIXME: Temporarily disabled because we are not properly parsing
2002 // linkage specifications on declarations, e.g.,
2003 //
2004 // extern "C" const CGPoint CGPointerZero;
2005 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002006 // C++ [dcl.init]p9:
2007 //
2008 // If no initializer is specified for an object, and the
2009 // object is of (possibly cv-qualified) non-POD class type (or
2010 // array thereof), the object shall be default-initialized; if
2011 // the object is of const-qualified type, the underlying class
2012 // type shall have a user-declared default
2013 // constructor. Otherwise, if no initializer is specified for
2014 // an object, the object and its subobjects, if any, have an
2015 // indeterminate initial value; if the object or any of its
2016 // subobjects are of const-qualified type, the program is
2017 // ill-formed.
2018 //
2019 // This isn't technically an error in C, so we don't diagnose it.
2020 //
2021 // FIXME: Actually perform the POD/user-defined default
2022 // constructor check.
2023 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002024 Context.getCanonicalType(Type).isConstQualified() &&
2025 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002026 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2027 << Var->getName()
2028 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002029#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002030 }
2031}
2032
Reid Spencer5f016e22007-07-11 17:01:13 +00002033/// The declarators are chained together backwards, reverse the list.
2034Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2035 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002036 Decl *GroupDecl = static_cast<Decl*>(group);
2037 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002038 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002039
2040 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2041 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002042 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002043 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002044 else { // reverse the list.
2045 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00002046 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002047 Group->setNextDeclarator(NewGroup);
2048 NewGroup = Group;
2049 Group = Next;
2050 }
2051 }
2052 // Perform semantic analysis that depends on having fully processed both
2053 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00002054 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002055 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2056 if (!IDecl)
2057 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002058 QualType T = IDecl->getType();
2059
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002060 if (T->isVariableArrayType()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002061 const VariableArrayType *VAT =
2062 cast<VariableArrayType>(T.getUnqualifiedType());
2063
2064 // FIXME: This won't give the correct result for
2065 // int a[10][n];
2066 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002067 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002068 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2069 SizeRange;
2070
Eli Friedmanc5773c42008-02-15 18:16:39 +00002071 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002072 } else {
2073 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2074 // static storage duration, it shall not have a variable length array.
2075 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002076 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2077 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002078 IDecl->setInvalidDecl();
2079 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002080 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2081 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002082 IDecl->setInvalidDecl();
2083 }
2084 }
2085 } else if (T->isVariablyModifiedType()) {
2086 if (IDecl->isFileVarDecl()) {
2087 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2088 IDecl->setInvalidDecl();
2089 } else {
2090 if (IDecl->getStorageClass() == VarDecl::Extern) {
2091 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2092 IDecl->setInvalidDecl();
2093 }
Steve Naroffbb204692007-09-12 14:07:44 +00002094 }
2095 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002096
Steve Naroffbb204692007-09-12 14:07:44 +00002097 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2098 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002099 if (IDecl->isBlockVarDecl() &&
2100 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002101 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002102 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002103 IDecl->setInvalidDecl();
2104 }
2105 }
2106 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2107 // object that has file scope without an initializer, and without a
2108 // storage-class specifier or with the storage-class specifier "static",
2109 // constitutes a tentative definition. Note: A tentative definition with
2110 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002111 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002112 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002113 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2114 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002115 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002116 // C99 6.9.2p3: If the declaration of an identifier for an object is
2117 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2118 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002119 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002120 IDecl->setInvalidDecl();
2121 }
2122 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002123 if (IDecl->isFileVarDecl())
2124 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 }
2126 return NewGroup;
2127}
Steve Naroffe1223f72007-08-28 03:03:08 +00002128
Chris Lattner04421082008-04-08 04:40:51 +00002129/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2130/// to introduce parameters into function prototype scope.
2131Sema::DeclTy *
2132Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002133 // FIXME: disallow CXXScopeSpec for param declarators.
Chris Lattner985abd92008-06-26 06:49:43 +00002134 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00002135
2136 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002137 VarDecl::StorageClass StorageClass = VarDecl::None;
2138 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2139 StorageClass = VarDecl::Register;
2140 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002141 Diag(DS.getStorageClassSpecLoc(),
2142 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002143 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002144 }
2145 if (DS.isThreadSpecified()) {
2146 Diag(DS.getThreadSpecLoc(),
2147 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002148 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002149 }
2150
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002151 // Check that there are no default arguments inside the type of this
2152 // parameter (C++ only).
2153 if (getLangOptions().CPlusPlus)
2154 CheckExtraCXXDefaultArguments(D);
2155
Chris Lattner04421082008-04-08 04:40:51 +00002156 // In this context, we *do not* check D.getInvalidType(). If the declarator
2157 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2158 // though it will not reflect the user specified type.
2159 QualType parmDeclType = GetTypeForDeclarator(D, S);
2160
2161 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2162
Reid Spencer5f016e22007-07-11 17:01:13 +00002163 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2164 // Can this happen for params? We already checked that they don't conflict
2165 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002166 IdentifierInfo *II = D.getIdentifier();
2167 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregorf57172b2008-12-08 18:40:42 +00002168 if (PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002169 // Maybe we will complain about the shadowed template parameter.
2170 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2171 // Just pretend that we didn't see the previous declaration.
2172 PrevDecl = 0;
2173 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002174 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002175
2176 // Recover by removing the name
2177 II = 0;
2178 D.SetIdentifier(0, D.getIdentifierLoc());
2179 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002180 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002181
2182 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2183 // Doing the promotion here has a win and a loss. The win is the type for
2184 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2185 // code generator). The loss is the orginal type isn't preserved. For example:
2186 //
2187 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2188 // int blockvardecl[5];
2189 // sizeof(parmvardecl); // size == 4
2190 // sizeof(blockvardecl); // size == 20
2191 // }
2192 //
2193 // For expressions, all implicit conversions are captured using the
2194 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2195 //
2196 // FIXME: If a source translation tool needs to see the original type, then
2197 // we need to consider storing both types (in ParmVarDecl)...
2198 //
Chris Lattnere6327742008-04-02 05:18:44 +00002199 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002200 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002201 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002202 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002203 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002204
Chris Lattner04421082008-04-08 04:40:51 +00002205 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2206 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002207 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002208 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002209
Chris Lattner04421082008-04-08 04:40:51 +00002210 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002211 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002212
2213 // Add the parameter declaration into this scope.
2214 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002215 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002216 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002217
Chris Lattner3ff30c82008-06-29 00:02:00 +00002218 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002219 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002220
Reid Spencer5f016e22007-07-11 17:01:13 +00002221}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002222
Chris Lattnerb652cea2007-10-09 17:14:05 +00002223Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002224 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002225 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2226 "Not a function declarator!");
2227 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002228
Reid Spencer5f016e22007-07-11 17:01:13 +00002229 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2230 // for a K&R function.
2231 if (!FTI.hasPrototype) {
2232 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002233 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002234 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2235 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002236 // Implicitly declare the argument as type 'int' for lack of a better
2237 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002238 DeclSpec DS;
2239 const char* PrevSpec; // unused
2240 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2241 PrevSpec);
2242 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2243 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2244 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002245 }
2246 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002247 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002248 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002249 }
2250
2251 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002252
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002253 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00002254 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002255}
2256
2257Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2258 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002259 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002260
2261 // See if this is a redefinition.
2262 const FunctionDecl *Definition;
2263 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002264 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002265 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002266 }
2267
Douglas Gregor44b43212008-12-11 16:49:14 +00002268 PushDeclContext(FnBodyScope, FD);
Chris Lattner04421082008-04-08 04:40:51 +00002269
2270 // Check the validity of our function parameters
2271 CheckParmsForFunctionDef(FD);
2272
2273 // Introduce our parameters into the function scope
2274 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2275 ParmVarDecl *Param = FD->getParamDecl(p);
2276 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002277 if (Param->getIdentifier())
2278 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002279 }
Chris Lattner04421082008-04-08 04:40:51 +00002280
Reid Spencer5f016e22007-07-11 17:01:13 +00002281 return FD;
2282}
2283
Steve Naroffd6d054d2007-11-11 23:20:51 +00002284Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
2285 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00002286 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002287 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002288 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002289 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002290 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002291 } else
2292 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002293 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002294 // Verify and clean out per-function state.
2295
2296 // Check goto/label use.
2297 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2298 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2299 // Verify that we have no forward references left. If so, there was a goto
2300 // or address of a label taken, but no definition of it. Label fwd
2301 // definitions are indicated with a null substmt.
2302 if (I->second->getSubStmt() == 0) {
2303 LabelStmt *L = I->second;
2304 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002305 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002306
2307 // At this point, we have gotos that use the bogus label. Stitch it into
2308 // the function body so that they aren't leaked and that the AST is well
2309 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002310 if (Body) {
2311 L->setSubStmt(new NullStmt(L->getIdentLoc()));
2312 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2313 } else {
2314 // The whole function wasn't parsed correctly, just delete this.
2315 delete L;
2316 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002317 }
2318 }
2319 LabelMap.clear();
2320
Steve Naroffd6d054d2007-11-11 23:20:51 +00002321 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002322}
2323
Reid Spencer5f016e22007-07-11 17:01:13 +00002324/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2325/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002326ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2327 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002328 // Extension in C99. Legal in C90, but warn about it.
2329 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002330 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002331 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002332 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002333
2334 // FIXME: handle stuff like:
2335 // void foo() { extern float X(); }
2336 // void bar() { X(); } <-- implicit decl for X in another scope.
2337
2338 // Set a Declarator for the implicit definition: int foo();
2339 const char *Dummy;
2340 DeclSpec DS;
2341 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2342 Error = Error; // Silence warning.
2343 assert(!Error && "Error setting up implicit decl!");
2344 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002345 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002346 D.SetIdentifier(&II, Loc);
2347
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002348 // Insert this function into translation-unit scope.
2349
2350 DeclContext *PrevDC = CurContext;
2351 CurContext = Context.getTranslationUnitDecl();
2352
Steve Naroffe2ef8152008-04-04 14:32:09 +00002353 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002354 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002355 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002356
2357 CurContext = PrevDC;
2358
Steve Naroffe2ef8152008-04-04 14:32:09 +00002359 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002360}
2361
2362
Chris Lattner41af0932007-11-14 06:34:38 +00002363TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002364 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002365 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002366 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002367
2368 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002369 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2370 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002371 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002372 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002373 if (D.getInvalidType())
2374 NewTD->setInvalidDecl();
2375 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002376}
2377
Steve Naroff08d92e42007-09-15 18:49:24 +00002378/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002379/// former case, Name will be non-null. In the later case, Name will be null.
2380/// TagType indicates what kind of tag this is. TK indicates whether this is a
2381/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002382Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002383 SourceLocation KWLoc, const CXXScopeSpec &SS,
2384 IdentifierInfo *Name, SourceLocation NameLoc,
2385 AttributeList *Attr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002386 // If this is a use of an existing tag, it must have a name.
2387 assert((Name != 0 || TK == TK_Definition) &&
2388 "Nameless record must be a definition!");
2389
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002390 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002391 switch (TagType) {
2392 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002393 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2394 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2395 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2396 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002397 }
2398
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002399 // Two code paths: a new one for structs/unions/classes where we create
2400 // separate decls for forward declarations, and an old (eventually to
2401 // be removed) code path for enums.
2402 if (Kind != TagDecl::TK_enum)
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002403 return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002404
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002405 DeclContext *DC = CurContext;
2406 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002407
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002408 if (Name && SS.isNotEmpty()) {
2409 // We have a nested-name tag ('struct foo::bar').
2410
2411 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002412 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002413 Name = 0;
2414 goto CreateNewDecl;
2415 }
2416
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002417 DC = static_cast<DeclContext*>(SS.getScopeRep());
2418 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002419 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2420
2421 // A tag 'foo::bar' must already exist.
2422 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002423 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002424 Name = 0;
2425 goto CreateNewDecl;
2426 }
2427 } else {
2428 // If this is a named struct, check to see if there was a previous forward
2429 // declaration or definition.
2430 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2431 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2432 }
2433
Douglas Gregorf57172b2008-12-08 18:40:42 +00002434 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002435 // Maybe we will complain about the shadowed template parameter.
2436 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2437 // Just pretend that we didn't see the previous declaration.
2438 PrevDecl = 0;
2439 }
2440
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002441 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002442 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2443 "unexpected Decl type");
2444 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002445 // If this is a use of a previous tag, or if the tag is already declared
2446 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002447 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002448 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002449 // Make sure that this wasn't declared as an enum and now used as a
2450 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002451 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002452 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002453 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002454 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002455 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002456 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002457 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00002458 // If this is a use or a forward declaration, we're good.
2459 if (TK != TK_Definition)
2460 return PrevDecl;
2461
2462 // Diagnose attempts to redefine a tag.
2463 if (PrevTagDecl->isDefinition()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002464 Diag(NameLoc, diag::err_redefinition) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002465 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner14943b92008-07-03 03:30:58 +00002466 // If this is a redefinition, recover by making this struct be
2467 // anonymous, which will make any later references get the previous
2468 // definition.
2469 Name = 0;
2470 } else {
2471 // Okay, this is definition of a previously declared or referenced
2472 // tag. Move the location of the decl to be the definition site.
2473 PrevDecl->setLocation(NameLoc);
2474 return PrevDecl;
2475 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002476 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002477 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002478 // If we get here, this is a definition of a new struct type in a nested
2479 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2480 // type.
2481 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002482 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002483 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002484 // The tag name clashes with a namespace name, issue an error and
2485 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002486 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002487 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002488 Name = 0;
2489 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002490 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002491 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002492
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002493 CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002494
2495 // If there is an identifier, use the location of the identifier as the
2496 // location of the decl, otherwise use the location of the struct/union
2497 // keyword.
2498 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2499
2500 // Otherwise, if this is the first time we've seen this tag, create the decl.
2501 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002502 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002503 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2504 // enum X { A, B, C } D; D should chain to X.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002505 New = EnumDecl::Create(Context, DC, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002506 // If this is an undefined enum, warn.
2507 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002508 } else {
2509 // struct/union/class
2510
Reid Spencer5f016e22007-07-11 17:01:13 +00002511 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2512 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002513 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002514 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002515 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002516 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002517 New = RecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002518 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002519
2520 // If this has an identifier, add it to the scope stack.
2521 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002522 // The scope passed in may not be a decl scope. Zip up the scope tree until
2523 // we find one that is.
2524 while ((S->getFlags() & Scope::DeclScope) == 0)
2525 S = S->getParent();
2526
2527 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002528 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002529 }
Chris Lattnere1e79852008-02-06 00:51:33 +00002530
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00002531 if (Attr)
2532 ProcessDeclAttributeList(New, Attr);
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002533
2534 // Set the lexical context. If the tag has a C++ scope specifier, the
2535 // lexical context will be different from the semantic context.
2536 New->setLexicalDeclContext(CurContext);
2537
Reid Spencer5f016e22007-07-11 17:01:13 +00002538 return New;
2539}
2540
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002541/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2542/// the logic for enums, we create separate decls for forward declarations.
2543/// This is called by ActOnTag, but eventually will replace its logic.
2544Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002545 SourceLocation KWLoc, const CXXScopeSpec &SS,
2546 IdentifierInfo *Name, SourceLocation NameLoc,
2547 AttributeList *Attr) {
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002548 DeclContext *DC = CurContext;
2549 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002550
2551 if (Name && SS.isNotEmpty()) {
2552 // We have a nested-name tag ('struct foo::bar').
2553
2554 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002555 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002556 Name = 0;
2557 goto CreateNewDecl;
2558 }
2559
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002560 DC = static_cast<DeclContext*>(SS.getScopeRep());
2561 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002562 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2563
2564 // A tag 'foo::bar' must already exist.
2565 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002566 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002567 Name = 0;
2568 goto CreateNewDecl;
2569 }
2570 } else {
2571 // If this is a named struct, check to see if there was a previous forward
2572 // declaration or definition.
2573 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2574 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2575 }
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002576
Douglas Gregorf57172b2008-12-08 18:40:42 +00002577 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002578 // Maybe we will complain about the shadowed template parameter.
2579 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2580 // Just pretend that we didn't see the previous declaration.
2581 PrevDecl = 0;
2582 }
2583
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002584 if (PrevDecl) {
2585 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2586 "unexpected Decl type");
2587
2588 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2589 // If this is a use of a previous tag, or if the tag is already declared
2590 // in the same scope (so that the definition/declaration completes or
2591 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002592 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002593 // Make sure that this wasn't declared as an enum and now used as a
2594 // struct or something similar.
2595 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002596 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002597 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002598 // Recover by making this an anonymous redefinition.
2599 Name = 0;
2600 PrevDecl = 0;
2601 } else {
2602 // If this is a use, return the original decl.
2603
2604 // FIXME: In the future, return a variant or some other clue
2605 // for the consumer of this Decl to know it doesn't own it.
2606 // For our current ASTs this shouldn't be a problem, but will
2607 // need to be changed with DeclGroups.
2608 if (TK == TK_Reference)
2609 return PrevDecl;
2610
2611 // The new decl is a definition?
2612 if (TK == TK_Definition) {
2613 // Diagnose attempts to redefine a tag.
2614 if (RecordDecl* DefRecord =
2615 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002616 Diag(NameLoc, diag::err_redefinition) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002617 Diag(DefRecord->getLocation(), diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002618 // If this is a redefinition, recover by making this struct be
2619 // anonymous, which will make any later references get the previous
2620 // definition.
2621 Name = 0;
2622 PrevDecl = 0;
2623 }
2624 // Okay, this is definition of a previously declared or referenced
2625 // tag. We're going to create a new Decl.
2626 }
2627 }
2628 // If we get here we have (another) forward declaration. Just create
2629 // a new decl.
2630 }
2631 else {
2632 // If we get here, this is a definition of a new struct type in a nested
2633 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2634 // new decl/type. We set PrevDecl to NULL so that the Records
2635 // have distinct types.
2636 PrevDecl = 0;
2637 }
2638 } else {
2639 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002640 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002641 // The tag name clashes with a namespace name, issue an error and
2642 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002643 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002644 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002645 Name = 0;
2646 }
2647 }
2648 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002649
2650 CreateNewDecl:
2651
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002652 // If there is an identifier, use the location of the identifier as the
2653 // location of the decl, otherwise use the location of the struct/union
2654 // keyword.
2655 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2656
2657 // Otherwise, if this is the first time we've seen this tag, create the decl.
2658 TagDecl *New;
2659
2660 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2661 // struct X { int A; } D; D should chain to X.
2662 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002663 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002664 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002665 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2666 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002667 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002668 dyn_cast_or_null<RecordDecl>(PrevDecl));
2669
2670 // If this has an identifier, add it to the scope stack.
2671 if ((TK == TK_Definition || !PrevDecl) && Name) {
2672 // The scope passed in may not be a decl scope. Zip up the scope tree until
2673 // we find one that is.
2674 while ((S->getFlags() & Scope::DeclScope) == 0)
2675 S = S->getParent();
2676
2677 // Add it to the decl chain.
2678 PushOnScopeChains(New, S);
2679 }
Daniel Dunbar3b0db902008-10-16 02:34:03 +00002680
2681 // Handle #pragma pack: if the #pragma pack stack has non-default
2682 // alignment, make up a packed attribute for this decl. These
2683 // attributes are checked when the ASTContext lays out the
2684 // structure.
2685 //
2686 // It is important for implementing the correct semantics that this
2687 // happen here (in act on tag decl). The #pragma pack stack is
2688 // maintained as a result of parser callbacks which can occur at
2689 // many points during the parsing of a struct declaration (because
2690 // the #pragma tokens are effectively skipped over during the
2691 // parsing of the struct).
2692 if (unsigned Alignment = PackContext.getAlignment())
2693 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002694
2695 if (Attr)
2696 ProcessDeclAttributeList(New, Attr);
2697
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002698 // Set the lexical context. If the tag has a C++ scope specifier, the
2699 // lexical context will be different from the semantic context.
2700 New->setLexicalDeclContext(CurContext);
2701
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002702 return New;
2703}
2704
2705
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002706/// Collect the instance variables declared in an Objective-C object. Used in
2707/// the creation of structures from objects using the @defs directive.
Douglas Gregor44b43212008-12-11 16:49:14 +00002708static void CollectIvars(ObjCInterfaceDecl *Class, RecordDecl *Record,
2709 ASTContext& Ctx,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002710 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002711 if (Class->getSuperClass())
Douglas Gregor44b43212008-12-11 16:49:14 +00002712 CollectIvars(Class->getSuperClass(), Record, Ctx, ivars);
Ted Kremenek01e67792008-08-20 03:26:33 +00002713
2714 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremeneka89d1972008-09-03 18:03:35 +00002715 for (ObjCInterfaceDecl::ivar_iterator
2716 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2717
Ted Kremenek01e67792008-08-20 03:26:33 +00002718 ObjCIvarDecl* ID = *I;
Douglas Gregor44b43212008-12-11 16:49:14 +00002719 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, Record,
2720 ID->getLocation(),
Ted Kremenek01e67792008-08-20 03:26:33 +00002721 ID->getIdentifier(),
2722 ID->getType(),
2723 ID->getBitWidth()));
2724 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002725}
2726
2727/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2728/// instance variables of ClassName into Decls.
Douglas Gregor44b43212008-12-11 16:49:14 +00002729void Sema::ActOnDefs(Scope *S, DeclTy *TagD, SourceLocation DeclStart,
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002730 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002731 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002732 // Check that ClassName is a valid class
2733 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2734 if (!Class) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002735 Diag(DeclStart, diag::err_undef_interface) << ClassName;
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002736 return;
2737 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002738 // Collect the instance variables
Douglas Gregor44b43212008-12-11 16:49:14 +00002739 CollectIvars(Class, dyn_cast<RecordDecl>((Decl*)TagD), Context, Decls);
2740
2741 // Introduce all of these fields into the appropriate scope.
2742 for (llvm::SmallVectorImpl<DeclTy*>::iterator D = Decls.begin();
2743 D != Decls.end(); ++D) {
2744 FieldDecl *FD = cast<FieldDecl>((Decl*)*D);
2745 if (getLangOptions().CPlusPlus)
2746 PushOnScopeChains(cast<FieldDecl>(FD), S);
2747 else if (RecordDecl *Record = dyn_cast<RecordDecl>((Decl*)TagD))
2748 Record->addDecl(Context, FD);
2749 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002750}
2751
Chris Lattner1d353ba2008-11-12 21:17:48 +00002752/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2753/// types into constant array types in certain situations which would otherwise
2754/// be errors (for GCC compatibility).
2755static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2756 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002757 // This method tries to turn a variable array into a constant
2758 // array even when the size isn't an ICE. This is necessary
2759 // for compatibility with code that depends on gcc's buggy
2760 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00002761 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2762 if (!VLATy) return QualType();
2763
2764 APValue Result;
2765 if (!VLATy->getSizeExpr() ||
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002766 !VLATy->getSizeExpr()->Evaluate(Result, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00002767 return QualType();
2768
2769 assert(Result.isInt() && "Size expressions must be integers!");
2770 llvm::APSInt &Res = Result.getInt();
2771 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2772 return Context.getConstantArrayType(VLATy->getElementType(),
2773 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002774 return QualType();
2775}
2776
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002777bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00002778 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002779 // FIXME: 6.7.2.1p4 - verify the field type.
2780
2781 llvm::APSInt Value;
2782 if (VerifyIntegerConstantExpression(BitWidth, &Value))
2783 return true;
2784
Chris Lattnercd087072008-12-12 04:56:04 +00002785 // Zero-width bitfield is ok for anonymous field.
2786 if (Value == 0 && FieldName)
2787 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
2788
2789 if (Value.isNegative())
2790 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002791
2792 uint64_t TypeSize = Context.getTypeSize(FieldTy);
2793 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00002794 if (TypeSize && Value.getZExtValue() > TypeSize)
2795 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
2796 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002797
2798 return false;
2799}
2800
Steve Naroff08d92e42007-09-15 18:49:24 +00002801/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002802/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00002803Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00002804 SourceLocation DeclStart,
2805 Declarator &D, ExprTy *BitfieldWidth) {
2806 IdentifierInfo *II = D.getIdentifier();
2807 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002808 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00002809 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002810 if (II) Loc = D.getIdentifierLoc();
2811
2812 // FIXME: Unnamed fields can be handled in various different ways, for
2813 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00002814
Reid Spencer5f016e22007-07-11 17:01:13 +00002815 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002816 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2817 bool InvalidDecl = false;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002818
Reid Spencer5f016e22007-07-11 17:01:13 +00002819 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2820 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002821 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00002822 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002823 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002824 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002825 T = FixedTy;
2826 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002827 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00002828 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002829 InvalidDecl = true;
2830 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002831 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002832
2833 if (BitWidth) {
2834 if (VerifyBitField(Loc, II, T, BitWidth))
2835 InvalidDecl = true;
2836 } else {
2837 // Not a bitfield.
2838
2839 // validate II.
2840
2841 }
2842
Reid Spencer5f016e22007-07-11 17:01:13 +00002843 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002844 FieldDecl *NewFD;
2845
Douglas Gregor44b43212008-12-11 16:49:14 +00002846 // FIXME: We don't want CurContext for C, do we? No, we'll need some
2847 // other way to determine the current RecordDecl.
2848 NewFD = FieldDecl::Create(Context, Record,
2849 Loc, II, T, BitWidth,
2850 D.getDeclSpec().getStorageClassSpec() ==
2851 DeclSpec::SCS_mutable,
2852 /*PrevDecl=*/0);
2853
Chris Lattner3ff30c82008-06-29 00:02:00 +00002854 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002855
Steve Naroff5912a352007-08-28 20:14:24 +00002856 if (D.getInvalidType() || InvalidDecl)
2857 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002858
2859 if (II && getLangOptions().CPlusPlus)
2860 PushOnScopeChains(NewFD, S);
2861 else
2862 Record->addDecl(Context, NewFD);
2863
Steve Naroff5912a352007-08-28 20:14:24 +00002864 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002865}
2866
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002867/// TranslateIvarVisibility - Translate visibility from a token ID to an
2868/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002869static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002870TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002871 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002872 default: assert(0 && "Unknown visitibility kind");
2873 case tok::objc_private: return ObjCIvarDecl::Private;
2874 case tok::objc_public: return ObjCIvarDecl::Public;
2875 case tok::objc_protected: return ObjCIvarDecl::Protected;
2876 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002877 }
2878}
2879
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002880/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2881/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002882Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002883 SourceLocation DeclStart,
2884 Declarator &D, ExprTy *BitfieldWidth,
2885 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002886 IdentifierInfo *II = D.getIdentifier();
2887 Expr *BitWidth = (Expr*)BitfieldWidth;
2888 SourceLocation Loc = DeclStart;
2889 if (II) Loc = D.getIdentifierLoc();
2890
2891 // FIXME: Unnamed fields can be handled in various different ways, for
2892 // example, unnamed unions inject all members into the struct namespace!
2893
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002894 QualType T = GetTypeForDeclarator(D, S);
2895 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2896 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002897
2898 if (BitWidth) {
2899 // TODO: Validate.
2900 //printf("WARNING: BITFIELDS IGNORED!\n");
2901
2902 // 6.7.2.1p3
2903 // 6.7.2.1p4
2904
2905 } else {
2906 // Not a bitfield.
2907
2908 // validate II.
2909
2910 }
2911
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002912 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2913 // than a variably modified type.
2914 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002915 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002916 InvalidDecl = true;
2917 }
2918
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002919 // Get the visibility (access control) for this ivar.
2920 ObjCIvarDecl::AccessControl ac =
2921 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2922 : ObjCIvarDecl::None;
2923
2924 // Construct the decl.
2925 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002926 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002927
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002928 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002929 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002930
2931 if (D.getInvalidType() || InvalidDecl)
2932 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002933
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002934 return NewID;
2935}
2936
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002937void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002938 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002939 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002940 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002941 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002942 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2943 assert(EnclosingDecl && "missing record or interface decl");
2944 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2945
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002946 if (Record)
2947 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2948 // Diagnose code like:
2949 // struct S { struct S {} X; };
2950 // We discover this when we complete the outer S. Reject and ignore the
2951 // outer S.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002952 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002953 << DefRecord->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002954 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002955 Record->setInvalidDecl();
2956 return;
2957 }
2958
Reid Spencer5f016e22007-07-11 17:01:13 +00002959 // Verify that all the fields are okay.
2960 unsigned NumNamedMembers = 0;
2961 llvm::SmallVector<FieldDecl*, 32> RecFields;
2962 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002963
Reid Spencer5f016e22007-07-11 17:01:13 +00002964 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002965
Steve Naroff74216642007-09-14 22:20:54 +00002966 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2967 assert(FD && "missing field decl");
2968
2969 // Remember all fields.
2970 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002971
2972 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002973 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002974
Reid Spencer5f016e22007-07-11 17:01:13 +00002975 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002976 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002977 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002978 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002979 FD->setInvalidDecl();
2980 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002981 continue;
2982 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002983 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2984 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002985 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002986 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002987 FD->setInvalidDecl();
2988 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002989 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002990 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002991 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002992 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002993 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002994 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002995 FD->setInvalidDecl();
2996 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002997 continue;
2998 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002999 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003000 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003001 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003002 FD->setInvalidDecl();
3003 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003004 continue;
3005 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003006 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003007 if (Record)
3008 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003009 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003010 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3011 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003012 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003013 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3014 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003015 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003016 Record->setHasFlexibleArrayMember(true);
3017 } else {
3018 // If this is a struct/class and this is not the last element, reject
3019 // it. Note that GCC supports variable sized arrays in the middle of
3020 // structures.
3021 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003022 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003023 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003024 FD->setInvalidDecl();
3025 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003026 continue;
3027 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003028 // We support flexible arrays at the end of structs in other structs
3029 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003030 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003031 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003032 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003033 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003034 }
3035 }
3036 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003037 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003038 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003039 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003040 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003041 FD->setInvalidDecl();
3042 EnclosingDecl->setInvalidDecl();
3043 continue;
3044 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003045 // Keep track of the number of named members.
3046 if (IdentifierInfo *II = FD->getIdentifier()) {
3047 // Detect duplicate member names.
3048 if (!FieldIDs.insert(II)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00003049 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Reid Spencer5f016e22007-07-11 17:01:13 +00003050 // Find the previous decl.
3051 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00003052 for (unsigned i = 0; ; ++i) {
3053 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00003054 if (RecFields[i]->getIdentifier() == II) {
3055 PrevLoc = RecFields[i]->getLocation();
3056 break;
3057 }
3058 }
Chris Lattner5f4a6822008-11-23 23:12:31 +00003059 Diag(PrevLoc, diag::note_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00003060 FD->setInvalidDecl();
3061 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003062 continue;
3063 }
3064 ++NumNamedMembers;
3065 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003066 }
3067
Reid Spencer5f016e22007-07-11 17:01:13 +00003068 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003069 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003070 Record->completeDefinition(Context);
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00003071 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
3072 // Sema::ActOnFinishCXXClassDef.
3073 if (!isa<CXXRecordDecl>(Record))
3074 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00003075 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003076 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
3077 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
3078 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
3079 else if (ObjCImplementationDecl *IMPDecl =
3080 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003081 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3082 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003083 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003084 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003085 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003086
3087 if (Attr)
3088 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003089}
3090
Steve Naroff08d92e42007-09-15 18:49:24 +00003091Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003092 DeclTy *lastEnumConst,
3093 SourceLocation IdLoc, IdentifierInfo *Id,
3094 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003095 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003096 EnumConstantDecl *LastEnumConst =
3097 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3098 Expr *Val = static_cast<Expr*>(val);
3099
Chris Lattner31e05722007-08-26 06:24:45 +00003100 // The scope passed in may not be a decl scope. Zip up the scope tree until
3101 // we find one that is.
3102 while ((S->getFlags() & Scope::DeclScope) == 0)
3103 S = S->getParent();
3104
Reid Spencer5f016e22007-07-11 17:01:13 +00003105 // Verify that there isn't already something declared with this name in this
3106 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003107 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003108 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003109 // Maybe we will complain about the shadowed template parameter.
3110 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3111 // Just pretend that we didn't see the previous declaration.
3112 PrevDecl = 0;
3113 }
3114
3115 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003116 // When in C++, we may get a TagDecl with the same name; in this case the
3117 // enum constant will 'hide' the tag.
3118 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3119 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003120 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003121 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003122 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003123 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003124 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003125 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003126 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003127 return 0;
3128 }
3129 }
3130
3131 llvm::APSInt EnumVal(32);
3132 QualType EltTy;
3133 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003134 // Make sure to promote the operand type to int.
3135 UsualUnaryConversions(Val);
3136
Reid Spencer5f016e22007-07-11 17:01:13 +00003137 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3138 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003139 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003140 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003141 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003142 } else {
3143 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003144 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003145 }
3146
3147 if (!Val) {
3148 if (LastEnumConst) {
3149 // Assign the last value + 1.
3150 EnumVal = LastEnumConst->getInitVal();
3151 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003152
3153 // Check for overflow on increment.
3154 if (EnumVal < LastEnumConst->getInitVal())
3155 Diag(IdLoc, diag::warn_enum_value_overflow);
3156
Chris Lattnerb7416f92007-08-27 17:37:24 +00003157 EltTy = LastEnumConst->getType();
3158 } else {
3159 // First value, set to zero.
3160 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003161 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003162 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003163 }
3164
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003165 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003166 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3167 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003168 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003169
3170 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003171 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00003172 return New;
3173}
3174
Steve Naroff02408c62008-08-07 14:08:16 +00003175// FIXME: For consistency with ActOnFields(), we should have the parser
3176// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003177void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003178 DeclTy **Elements, unsigned NumElements) {
3179 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00003180
Steve Naroff02408c62008-08-07 14:08:16 +00003181 if (Enum && Enum->isDefinition()) {
3182 // Diagnose code like:
3183 // enum e0 {
3184 // E0 = sizeof(enum e0 { E1 })
3185 // };
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003186 Diag(Enum->getLocation(), diag::err_nested_redefinition)
3187 << Enum->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003188 Diag(EnumLoc, diag::note_previous_definition);
Steve Naroff02408c62008-08-07 14:08:16 +00003189 Enum->setInvalidDecl();
3190 return;
3191 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00003192 // TODO: If the result value doesn't fit in an int, it must be a long or long
3193 // long value. ISO C does not support this, but GCC does as an extension,
3194 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003195 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003196
Chris Lattnerac609682007-08-28 06:15:15 +00003197 // Verify that all the values are okay, compute the size of the values, and
3198 // reverse the list.
3199 unsigned NumNegativeBits = 0;
3200 unsigned NumPositiveBits = 0;
3201
3202 // Keep track of whether all elements have type int.
3203 bool AllElementsInt = true;
3204
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003205 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003206 EnumConstantDecl *EltList = 0;
3207 for (unsigned i = 0; i != NumElements; ++i) {
3208 EnumConstantDecl *ECD =
3209 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3210 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003211
3212 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003213 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003214 assert(InitVal.getBitWidth() >= IntWidth &&
3215 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003216 if (InitVal.getBitWidth() > IntWidth) {
3217 llvm::APSInt V(InitVal);
3218 V.trunc(IntWidth);
3219 V.extend(InitVal.getBitWidth());
3220 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003221 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3222 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003223 }
Chris Lattnerac609682007-08-28 06:15:15 +00003224
3225 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003226 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003227 NumPositiveBits = std::max(NumPositiveBits,
3228 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003229 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003230 NumNegativeBits = std::max(NumNegativeBits,
3231 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003232
Chris Lattnerac609682007-08-28 06:15:15 +00003233 // Keep track of whether every enum element has type int (very commmon).
3234 if (AllElementsInt)
3235 AllElementsInt = ECD->getType() == Context.IntTy;
3236
Reid Spencer5f016e22007-07-11 17:01:13 +00003237 ECD->setNextDeclarator(EltList);
3238 EltList = ECD;
3239 }
3240
Chris Lattnerac609682007-08-28 06:15:15 +00003241 // Figure out the type that should be used for this enum.
3242 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3243 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003244 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003245
3246 if (NumNegativeBits) {
3247 // If there is a negative value, figure out the smallest integer type (of
3248 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003249 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003250 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003251 BestWidth = IntWidth;
3252 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003253 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003254
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003255 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003256 BestType = Context.LongTy;
3257 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003258 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003259
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003260 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003261 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3262 BestType = Context.LongLongTy;
3263 }
3264 }
3265 } else {
3266 // If there is no negative value, figure out which of uint, ulong, ulonglong
3267 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003268 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003269 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003270 BestWidth = IntWidth;
3271 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003272 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003273 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003274 } else {
3275 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003276 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003277 "How could an initializer get larger than ULL?");
3278 BestType = Context.UnsignedLongLongTy;
3279 }
3280 }
3281
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003282 // Loop over all of the enumerator constants, changing their types to match
3283 // the type of the enum if needed.
3284 for (unsigned i = 0; i != NumElements; ++i) {
3285 EnumConstantDecl *ECD =
3286 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3287 if (!ECD) continue; // Already issued a diagnostic.
3288
3289 // Standard C says the enumerators have int type, but we allow, as an
3290 // extension, the enumerators to be larger than int size. If each
3291 // enumerator value fits in an int, type it as an int, otherwise type it the
3292 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3293 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003294 if (ECD->getType() == Context.IntTy) {
3295 // Make sure the init value is signed.
3296 llvm::APSInt IV = ECD->getInitVal();
3297 IV.setIsSigned(true);
3298 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003299
3300 if (getLangOptions().CPlusPlus)
3301 // C++ [dcl.enum]p4: Following the closing brace of an
3302 // enum-specifier, each enumerator has the type of its
3303 // enumeration.
3304 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003305 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003306 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003307
3308 // Determine whether the value fits into an int.
3309 llvm::APSInt InitVal = ECD->getInitVal();
3310 bool FitsInInt;
3311 if (InitVal.isUnsigned() || !InitVal.isNegative())
3312 FitsInInt = InitVal.getActiveBits() < IntWidth;
3313 else
3314 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3315
3316 // If it fits into an integer type, force it. Otherwise force it to match
3317 // the enum decl type.
3318 QualType NewTy;
3319 unsigned NewWidth;
3320 bool NewSign;
3321 if (FitsInInt) {
3322 NewTy = Context.IntTy;
3323 NewWidth = IntWidth;
3324 NewSign = true;
3325 } else if (ECD->getType() == BestType) {
3326 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003327 if (getLangOptions().CPlusPlus)
3328 // C++ [dcl.enum]p4: Following the closing brace of an
3329 // enum-specifier, each enumerator has the type of its
3330 // enumeration.
3331 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003332 continue;
3333 } else {
3334 NewTy = BestType;
3335 NewWidth = BestWidth;
3336 NewSign = BestType->isSignedIntegerType();
3337 }
3338
3339 // Adjust the APSInt value.
3340 InitVal.extOrTrunc(NewWidth);
3341 InitVal.setIsSigned(NewSign);
3342 ECD->setInitVal(InitVal);
3343
3344 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003345 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3346 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003347 if (getLangOptions().CPlusPlus)
3348 // C++ [dcl.enum]p4: Following the closing brace of an
3349 // enum-specifier, each enumerator has the type of its
3350 // enumeration.
3351 ECD->setType(EnumType);
3352 else
3353 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003354 }
Chris Lattnerac609682007-08-28 06:15:15 +00003355
Douglas Gregor44b43212008-12-11 16:49:14 +00003356 Enum->completeDefinition(Context, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003357 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003358}
3359
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003360Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3361 ExprTy *expr) {
3362 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
3363
Chris Lattner8e25d862008-03-16 00:16:02 +00003364 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003365}
3366
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003367Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00003368 SourceLocation LBrace,
3369 SourceLocation RBrace,
3370 const char *Lang,
3371 unsigned StrSize,
3372 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003373 LinkageSpecDecl::LanguageIDs Language;
3374 Decl *dcl = static_cast<Decl *>(D);
3375 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3376 Language = LinkageSpecDecl::lang_c;
3377 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3378 Language = LinkageSpecDecl::lang_cxx;
3379 else {
3380 Diag(Loc, diag::err_bad_language);
3381 return 0;
3382 }
3383
3384 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00003385 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003386}
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003387
3388void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3389 ExprTy *alignment, SourceLocation PragmaLoc,
3390 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3391 Expr *Alignment = static_cast<Expr *>(alignment);
3392
3393 // If specified then alignment must be a "small" power of two.
3394 unsigned AlignmentVal = 0;
3395 if (Alignment) {
3396 llvm::APSInt Val;
3397 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3398 !Val.isPowerOf2() ||
3399 Val.getZExtValue() > 16) {
3400 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3401 delete Alignment;
3402 return; // Ignore
3403 }
3404
3405 AlignmentVal = (unsigned) Val.getZExtValue();
3406 }
3407
3408 switch (Kind) {
3409 case Action::PPK_Default: // pack([n])
3410 PackContext.setAlignment(AlignmentVal);
3411 break;
3412
3413 case Action::PPK_Show: // pack(show)
3414 // Show the current alignment, making sure to show the right value
3415 // for the default.
3416 AlignmentVal = PackContext.getAlignment();
3417 // FIXME: This should come from the target.
3418 if (AlignmentVal == 0)
3419 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003420 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003421 break;
3422
3423 case Action::PPK_Push: // pack(push [, id] [, [n])
3424 PackContext.push(Name);
3425 // Set the new alignment if specified.
3426 if (Alignment)
3427 PackContext.setAlignment(AlignmentVal);
3428 break;
3429
3430 case Action::PPK_Pop: // pack(pop [, id] [, n])
3431 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3432 // "#pragma pack(pop, identifier, n) is undefined"
3433 if (Alignment && Name)
3434 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3435
3436 // Do the pop.
3437 if (!PackContext.pop(Name)) {
3438 // If a name was specified then failure indicates the name
3439 // wasn't found. Otherwise failure indicates the stack was
3440 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003441 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3442 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003443
3444 // FIXME: Warn about popping named records as MSVC does.
3445 } else {
3446 // Pop succeeded, set the new alignment if specified.
3447 if (Alignment)
3448 PackContext.setAlignment(AlignmentVal);
3449 }
3450 break;
3451
3452 default:
3453 assert(0 && "Invalid #pragma pack kind.");
3454 }
3455}
3456
3457bool PragmaPackStack::pop(IdentifierInfo *Name) {
3458 if (Stack.empty())
3459 return false;
3460
3461 // If name is empty just pop top.
3462 if (!Name) {
3463 Alignment = Stack.back().first;
3464 Stack.pop_back();
3465 return true;
3466 }
3467
3468 // Otherwise, find the named record.
3469 for (unsigned i = Stack.size(); i != 0; ) {
3470 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003471 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003472 // Found it, pop up to and including this record.
3473 Alignment = Stack[i].first;
3474 Stack.erase(Stack.begin() + i, Stack.end());
3475 return true;
3476 }
3477 }
3478
3479 return false;
3480}