blob: b541f59a22318a399e318912cc66fe960dd6d6ae [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6953a072008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallSet.h"
28using namespace clang;
29
Douglas Gregorb0212bd2008-11-17 20:34:05 +000030Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000031 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000032 DeclContext *DC = 0;
33 if (SS) {
34 if (SS->isInvalid())
35 return 0;
36 DC = static_cast<DeclContext*>(SS->getScopeRep());
37 }
38 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroff6384a012008-04-02 14:35:35 +000039
Douglas Gregor1d661552008-04-13 21:07:44 +000040 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
41 isa<ObjCInterfaceDecl>(IIDecl) ||
Douglas Gregordd861062008-12-05 18:15:24 +000042 isa<TagDecl>(IIDecl) ||
43 isa<TemplateTypeParmDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000044 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000045 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000046}
47
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000048DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000049 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000050 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000051 if (MD->isOutOfLineDefinition())
52 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000053
54 // A C++ inline method is parsed *after* the topmost class it was declared in
55 // is fully parsed (it's "complete").
56 // The parsing of a C++ inline method happens at the declaration context of
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000057 // the topmost (non-nested) class it is lexically declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000058 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
59 DC = MD->getParent();
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000060 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000061 DC = RD;
62
63 // Return the declaration context of the topmost class the inline method is
64 // declared in.
65 return DC;
66 }
67
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000068 if (isa<ObjCMethodDecl>(DC))
69 return Context.getTranslationUnitDecl();
70
71 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
72 return SD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000073
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000074 return DC->getLexicalParent();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000075}
76
Douglas Gregor8acb7272008-12-11 16:49:14 +000077void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000078 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu2c9b8102008-12-08 07:14:51 +000079 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000080 CurContext = DC;
Douglas Gregor8acb7272008-12-11 16:49:14 +000081 S->setEntity(DC);
Chris Lattnereee57c02008-04-04 06:12:32 +000082}
83
Chris Lattnerf3874bc2008-04-06 04:47:34 +000084void Sema::PopDeclContext() {
85 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor8acb7272008-12-11 16:49:14 +000086
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000087 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +000088}
89
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000090/// Add this decl to the scope shadowed decl chains.
91void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000092 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000093
94 // C++ [basic.scope]p4:
95 // -- exactly one declaration shall declare a class name or
96 // enumeration name that is not a typedef name and the other
97 // declarations shall all refer to the same object or
98 // enumerator, or all refer to functions and function templates;
99 // in this case the class name or enumeration name is hidden.
100 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
101 // We are pushing the name of a tag (enum or class).
Douglas Gregor8acb7272008-12-11 16:49:14 +0000102 if (CurContext == TD->getDeclContext()) {
103 // We're pushing the tag into the current context, which might
104 // require some reshuffling in the identifier resolver.
105 IdentifierResolver::iterator
106 I = IdResolver.begin(TD->getIdentifier(), CurContext,
107 false/*LookInParentCtx*/);
108 if (I != IdResolver.end()) {
109 // There is already a declaration with the same name in the same
110 // scope. It must be found before we find the new declaration,
111 // so swap the order on the shadowed declaration chain.
112 IdResolver.AddShadowedDecl(TD, *I);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000113
Douglas Gregor8acb7272008-12-11 16:49:14 +0000114 // Add this declaration to the current context.
115 CurContext->addDecl(Context, TD);
116
117 return;
118 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000119 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000120 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000121 // We are pushing the name of a function, which might be an
122 // overloaded name.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000123 FunctionDecl *FD = cast<FunctionDecl>(D);
124 Decl *Prev = LookupDecl(FD->getDeclName(), Decl::IDNS_Ordinary, S,
125 FD->getDeclContext(), false, false);
126 if (Prev && (isa<OverloadedFunctionDecl>(Prev) || isa<FunctionDecl>(Prev))) {
127 // There is already a declaration with the same name in
128 // the same scope. It must be a function or an overloaded
129 // function.
130 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(Prev);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000131 if (!Ovl) {
132 // We haven't yet overloaded this function. Take the existing
133 // FunctionDecl and put it into an OverloadedFunctionDecl.
134 Ovl = OverloadedFunctionDecl::Create(Context,
135 FD->getDeclContext(),
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000136 FD->getDeclName());
Douglas Gregor8acb7272008-12-11 16:49:14 +0000137 Ovl->addOverload(dyn_cast<FunctionDecl>(Prev));
Douglas Gregord2baafd2008-10-21 16:13:35 +0000138
Douglas Gregor8acb7272008-12-11 16:49:14 +0000139 // If there is an name binding for the existing FunctionDecl,
140 // remove it.
141 for (IdentifierResolver::iterator I
142 = IdResolver.begin(FD->getDeclName(), FD->getDeclContext(),
143 false/*LookInParentCtx*/);
144 I != IdResolver.end(); ++I) {
145 if (*I == Prev) {
146 IdResolver.RemoveDecl(*I);
147 S->RemoveDecl(*I);
148 break;
149 }
150 }
151
152 // Add the name binding for the OverloadedFunctionDecl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000153 IdResolver.AddDecl(Ovl);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000154
155 // Update the context with the newly-created overloaded
156 // function set.
157 FD->getDeclContext()->insert(Context, Ovl);
158
159 S->AddDecl(Ovl);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000160 }
161
Douglas Gregor8acb7272008-12-11 16:49:14 +0000162 // We added this function declaration to the scope earlier, but
163 // we don't want it there because it is part of the overloaded
164 // function declaration.
165 S->RemoveDecl(FD);
166
Douglas Gregord2baafd2008-10-21 16:13:35 +0000167 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
168 // to its list of overloads.
169 Ovl->addOverload(FD);
170
Douglas Gregor8acb7272008-12-11 16:49:14 +0000171 // Add this new function declaration to the declaration context.
172 CurContext->addDecl(Context, FD, false);
173
174 return;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000175 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000176 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000177
Douglas Gregor8acb7272008-12-11 16:49:14 +0000178 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
179 CurContext->addDecl(Context, SD);
180 else {
181 // Other kinds of declarations don't currently have a context
182 // where they need to be inserted.
183 }
184
185
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000186 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000187}
188
Steve Naroff9637a9b2007-10-09 22:01:59 +0000189void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000190 if (S->decl_empty()) return;
Douglas Gregordd861062008-12-05 18:15:24 +0000191 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
192 "Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000193
Chris Lattner4b009652007-07-25 00:24:17 +0000194 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
195 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000196 Decl *TmpD = static_cast<Decl*>(*I);
197 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000198
Douglas Gregor8acb7272008-12-11 16:49:14 +0000199 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
200 NamedDecl *D = cast<NamedDecl>(TmpD);
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000201
Douglas Gregor8acb7272008-12-11 16:49:14 +0000202 if (!D->getDeclName()) continue;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000203
Douglas Gregor8acb7272008-12-11 16:49:14 +0000204 // Remove this name from our lexical scope.
205 IdResolver.RemoveDecl(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000206 }
207}
208
Steve Naroffe57c21a2008-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 Naroffe57c21a2008-04-01 23:04:06 +0000211ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-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 Jahaniandc36dc12007-10-12 19:38:20 +0000215
Steve Naroff6384a012008-04-02 14:35:35 +0000216 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000217}
218
Steve Naroffe57c21a2008-04-01 23:04:06 +0000219/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000220/// namespace.
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000221Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000222 const DeclContext *LookupCtx,
Douglas Gregor8acb7272008-12-11 16:49:14 +0000223 bool enableLazyBuiltinCreation,
224 bool LookInParent) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000225 if (!Name) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000226 unsigned NS = NSI;
227 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
228 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000229
Douglas Gregor8acb7272008-12-11 16:49:14 +0000230 if (LookupCtx) {
231 assert(getLangOptions().CPlusPlus && "No qualified name lookup in C");
232
233 // Perform qualified name lookup into the LookupCtx.
234 // FIXME: Will need to look into base classes and such.
235 for (DeclContext::lookup_const_result I = LookupCtx->lookup(Context, Name);
236 I.first != I.second; ++I.first)
237 if ((*I.first)->getIdentifierNamespace() & NS)
238 return *I.first;
239 } else if (getLangOptions().CPlusPlus &&
240 (NS & (Decl::IDNS_Ordinary | Decl::IDNS_Tag))) {
241 // Name lookup for ordinary names and tag names in C++ requires
242 // looking into scopes that aren't strictly lexical, and
243 // therefore we walk through the context as well as walking
244 // through the scopes.
245 IdentifierResolver::iterator
246 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
247 IEnd = IdResolver.end();
248 for (; S; S = S->getParent()) {
249 // Check whether the IdResolver has anything in this scope.
250 // FIXME: The isDeclScope check could be expensive. Can we do better?
251 for (; I != IEnd && S->isDeclScope(*I); ++I)
252 if ((*I)->getIdentifierNamespace() & NS)
253 return *I;
254
255 // If there is an entity associated with this scope, it's a
256 // DeclContext. We might need to perform qualified lookup into
257 // it.
258 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
259 while (Ctx && Ctx->isFunctionOrMethod())
260 Ctx = Ctx->getParent();
261 while (Ctx && (Ctx->isNamespace() || Ctx->isCXXRecord())) {
262 // Look for declarations of this name in this scope.
263 for (DeclContext::lookup_const_result I = Ctx->lookup(Context, Name);
264 I.first != I.second; ++I.first) {
265 // FIXME: Cache this result in the IdResolver
266 if ((*I.first)->getIdentifierNamespace() & NS)
267 return *I.first;
268 }
269
270 Ctx = Ctx->getParent();
271 }
272
273 if (!LookInParent)
274 return 0;
275 }
276 } else {
277 // Unqualified name lookup for names in our lexical scope. This
278 // name lookup suffices when all of the potential names are known
279 // to have been pushed onto the IdResolver, as happens in C
280 // (always) and in C++ for names in the "label" namespace.
281 assert(!LookupCtx && "Can't perform qualified name lookup here");
282 IdentifierResolver::iterator I
283 = IdResolver.begin(Name, CurContext, LookInParent);
284
285 // Scan up the scope chain looking for a decl that matches this
286 // identifier that is in the appropriate namespace. This search
287 // should not take long, as shadowing of names is uncommon, and
288 // deep shadowing is extremely uncommon.
289 for (; I != IdResolver.end(); ++I)
290 if ((*I)->getIdentifierNamespace() & NS)
291 return *I;
292 }
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000293
Chris Lattner4b009652007-07-25 00:24:17 +0000294 // If we didn't find a use of this identifier, and if the identifier
295 // corresponds to a compiler builtin, create the decl object for the builtin
296 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000297 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000298 IdentifierInfo *II = Name.getAsIdentifierInfo();
299 if (enableLazyBuiltinCreation && II &&
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000300 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroff6384a012008-04-02 14:35:35 +0000301 // If this is a builtin on this (or all) targets, create the decl.
302 if (unsigned BuiltinID = II->getBuiltinID())
303 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
304 }
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000305 if (getLangOptions().ObjC1 && II) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000306 // @interface and @compatibility_alias introduce typedef-like names.
307 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000308 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000309 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000310 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
311 if (IDI != ObjCInterfaceDecls.end())
312 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000313 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
314 if (I != ObjCAliasDecls.end())
315 return I->second->getClassInterface();
316 }
Chris Lattner4b009652007-07-25 00:24:17 +0000317 }
318 return 0;
319}
320
Chris Lattnera9c87f22008-05-05 22:18:14 +0000321void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000322 if (!Context.getBuiltinVaListType().isNull())
323 return;
324
325 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000326 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000327 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000328 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
329}
330
Chris Lattner4b009652007-07-25 00:24:17 +0000331/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
332/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000333ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
334 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000335 Builtin::ID BID = (Builtin::ID)bid;
336
Chris Lattnerb23469f2008-09-28 05:54:29 +0000337 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000338 InitBuiltinVaListType();
339
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000340 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000341 FunctionDecl *New = FunctionDecl::Create(Context,
342 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000343 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000344 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000345
Chris Lattnera9c87f22008-05-05 22:18:14 +0000346 // Create Decl objects for each parameter, adding them to the
347 // FunctionDecl.
348 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
349 llvm::SmallVector<ParmVarDecl*, 16> Params;
350 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
351 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
352 FT->getArgType(i), VarDecl::None, 0,
353 0));
354 New->setParams(&Params[0], Params.size());
355 }
356
357
358
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000359 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000360 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000361 return New;
362}
363
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000364/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
365/// everything from the standard library is defined.
366NamespaceDecl *Sema::GetStdNamespace() {
367 if (!StdNamespace) {
Chris Lattnerf0939602008-11-20 05:45:14 +0000368 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000369 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattnerf0939602008-11-20 05:45:14 +0000370 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000371 0, Global, /*enableLazyBuiltinCreation=*/false);
372 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
373 }
374 return StdNamespace;
375}
376
Chris Lattner4b009652007-07-25 00:24:17 +0000377/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
378/// and scope as a previous declaration 'Old'. Figure out how to resolve this
379/// situation, merging decls or emitting diagnostics as appropriate.
380///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000381TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff453a8782008-09-09 14:32:20 +0000382 // Allow multiple definitions for ObjC built-in typedefs.
383 // FIXME: Verify the underlying types are equivalent!
384 if (getLangOptions().ObjC1) {
Chris Lattner6d16b052008-11-20 05:41:43 +0000385 const IdentifierInfo *TypeID = New->getIdentifier();
386 switch (TypeID->getLength()) {
387 default: break;
388 case 2:
389 if (!TypeID->isStr("id"))
390 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000391 Context.setObjCIdType(New);
392 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000393 case 5:
394 if (!TypeID->isStr("Class"))
395 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000396 Context.setObjCClassType(New);
397 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000398 case 3:
399 if (!TypeID->isStr("SEL"))
400 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000401 Context.setObjCSelType(New);
402 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000403 case 8:
404 if (!TypeID->isStr("Protocol"))
405 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000406 Context.setObjCProtoType(New->getUnderlyingType());
407 return New;
408 }
409 // Fall through - the typedef name was not a builtin type.
410 }
Chris Lattner4b009652007-07-25 00:24:17 +0000411 // Verify the old decl was also a typedef.
412 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
413 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000414 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000415 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000416 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000417 return New;
418 }
419
Chris Lattnerbef8d622008-07-25 18:44:27 +0000420 // If the typedef types are not identical, reject them in all languages and
421 // with any extensions enabled.
422 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
423 Context.getCanonicalType(Old->getUnderlyingType()) !=
424 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner8d756812008-11-20 06:13:02 +0000425 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000426 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner1336cab2008-11-23 23:12:31 +0000427 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerbef8d622008-07-25 18:44:27 +0000428 return Old;
429 }
430
Eli Friedman324d5032008-06-11 06:20:39 +0000431 if (getLangOptions().Microsoft) return New;
432
Douglas Gregor49ba1b72008-11-21 16:29:06 +0000433 // C++ [dcl.typedef]p2:
434 // In a given non-class scope, a typedef specifier can be used to
435 // redefine the name of any type declared in that scope to refer
436 // to the type to which it already refers.
437 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
438 return New;
439
440 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroffa9eae582008-01-30 23:46:05 +0000441 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
442 // *either* declaration is in a system header. The code below implements
443 // this adhoc compatibility rule. FIXME: The following code will not
444 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000445 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
446 SourceManager &SrcMgr = Context.getSourceManager();
447 if (SrcMgr.isInSystemHeader(Old->getLocation()))
448 return New;
449 if (SrcMgr.isInSystemHeader(New->getLocation()))
450 return New;
451 }
Eli Friedman324d5032008-06-11 06:20:39 +0000452
Chris Lattnerb1753422008-11-23 21:45:46 +0000453 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000454 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000455 return New;
456}
457
Chris Lattner6953a072008-06-26 18:38:35 +0000458/// DeclhasAttr - returns true if decl Declaration already has the target
459/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000460static bool DeclHasAttr(const Decl *decl, const Attr *target) {
461 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
462 if (attr->getKind() == target->getKind())
463 return true;
464
465 return false;
466}
467
468/// MergeAttributes - append attributes from the Old decl to the New one.
469static void MergeAttributes(Decl *New, Decl *Old) {
470 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
471
Chris Lattner402b3372008-03-03 03:28:21 +0000472 while (attr) {
473 tmp = attr;
474 attr = attr->getNext();
475
476 if (!DeclHasAttr(New, tmp)) {
477 New->addAttr(tmp);
478 } else {
479 tmp->setNext(0);
480 delete(tmp);
481 }
482 }
Nuno Lopes77654342008-06-01 22:53:53 +0000483
484 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000485}
486
Chris Lattner3e254fb2008-04-08 04:40:51 +0000487/// MergeFunctionDecl - We just parsed a function 'New' from
488/// declarator D which has the same name and scope as a previous
489/// declaration 'Old'. Figure out how to resolve this situation,
490/// merging decls or emitting diagnostics as appropriate.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000491/// Redeclaration will be set true if this New is a redeclaration OldD.
492///
493/// In C++, New and Old must be declarations that are not
494/// overloaded. Use IsOverload to determine whether New and Old are
495/// overloaded, and to select the Old declaration that New should be
496/// merged with.
Douglas Gregor42214c52008-04-21 02:02:58 +0000497FunctionDecl *
498Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000499 assert(!isa<OverloadedFunctionDecl>(OldD) &&
500 "Cannot merge with an overloaded function declaration");
501
Douglas Gregor42214c52008-04-21 02:02:58 +0000502 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000503 // Verify the old decl was also a function.
504 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
505 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000506 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000507 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000508 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000509 return New;
510 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000511
512 // Determine whether the previous declaration was a definition,
513 // implicit declaration, or a declaration.
514 diag::kind PrevDiag;
515 if (Old->isThisDeclarationADefinition())
Chris Lattner1336cab2008-11-23 23:12:31 +0000516 PrevDiag = diag::note_previous_definition;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000517 else if (Old->isImplicit())
Chris Lattner1336cab2008-11-23 23:12:31 +0000518 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000519 else
Chris Lattner1336cab2008-11-23 23:12:31 +0000520 PrevDiag = diag::note_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000521
Chris Lattner42a21742008-04-06 23:10:54 +0000522 QualType OldQType = Context.getCanonicalType(Old->getType());
523 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000524
Douglas Gregord2baafd2008-10-21 16:13:35 +0000525 if (getLangOptions().CPlusPlus) {
526 // (C++98 13.1p2):
527 // Certain function declarations cannot be overloaded:
528 // -- Function declarations that differ only in the return type
529 // cannot be overloaded.
530 QualType OldReturnType
531 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
532 QualType NewReturnType
533 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
534 if (OldReturnType != NewReturnType) {
535 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
536 Diag(Old->getLocation(), PrevDiag);
537 return New;
538 }
539
540 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
541 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
542 if (OldMethod && NewMethod) {
543 // -- Member function declarations with the same name and the
544 // same parameter types cannot be overloaded if any of them
545 // is a static member function declaration.
546 if (OldMethod->isStatic() || NewMethod->isStatic()) {
547 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
548 Diag(Old->getLocation(), PrevDiag);
549 return New;
550 }
551 }
552
553 // (C++98 8.3.5p3):
554 // All declarations for a function shall agree exactly in both the
555 // return type and the parameter-type-list.
556 if (OldQType == NewQType) {
557 // We have a redeclaration.
558 MergeAttributes(New, Old);
559 Redeclaration = true;
560 return MergeCXXFunctionDecl(New, Old);
561 }
562
563 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000564 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000565
566 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000567 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000568 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000569 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000570 MergeAttributes(New, Old);
571 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000572 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000573 }
Chris Lattner1470b072007-11-06 06:07:26 +0000574
Steve Naroff6c9e7922008-01-16 15:01:34 +0000575 // A function that has already been declared has been redeclared or defined
576 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000577
Chris Lattner4b009652007-07-25 00:24:17 +0000578 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
579 // TODO: This is totally simplistic. It should handle merging functions
580 // together etc, merging extern int X; int X; ...
Chris Lattner271d4c22008-11-24 05:29:24 +0000581 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff6c9e7922008-01-16 15:01:34 +0000582 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000583 return New;
584}
585
Steve Naroffb5e78152008-08-08 17:50:35 +0000586/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000587static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000588 if (VD->isFileVarDecl())
589 return (!VD->getInit() &&
590 (VD->getStorageClass() == VarDecl::None ||
591 VD->getStorageClass() == VarDecl::Static));
592 return false;
593}
594
595/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
596/// when dealing with C "tentative" external object definitions (C99 6.9.2).
597void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
598 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000599 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000600
601 for (IdentifierResolver::iterator
602 I = IdResolver.begin(VD->getIdentifier(),
603 VD->getDeclContext(), false/*LookInParentCtx*/),
604 E = IdResolver.end(); I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000605 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000606 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
607
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000608 // Handle the following case:
609 // int a[10];
610 // int a[]; - the code below makes sure we set the correct type.
611 // int a[11]; - this is an error, size isn't 10.
612 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
613 OldDecl->getType()->isConstantArrayType())
614 VD->setType(OldDecl->getType());
615
Steve Naroffb5e78152008-08-08 17:50:35 +0000616 // Check for "tentative" definitions. We can't accomplish this in
617 // MergeVarDecl since the initializer hasn't been attached.
618 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
619 continue;
620
621 // Handle __private_extern__ just like extern.
622 if (OldDecl->getStorageClass() != VarDecl::Extern &&
623 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
624 VD->getStorageClass() != VarDecl::Extern &&
625 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000626 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000627 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffb5e78152008-08-08 17:50:35 +0000628 }
629 }
630 }
631}
632
Chris Lattner4b009652007-07-25 00:24:17 +0000633/// MergeVarDecl - We just parsed a variable 'New' which has the same name
634/// and scope as a previous declaration 'Old'. Figure out how to resolve this
635/// situation, merging decls or emitting diagnostics as appropriate.
636///
Steve Naroffb5e78152008-08-08 17:50:35 +0000637/// Tentative definition rules (C99 6.9.2p2) are checked by
638/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
639/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000640///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000641VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000642 // Verify the old decl was also a variable.
643 VarDecl *Old = dyn_cast<VarDecl>(OldD);
644 if (!Old) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000645 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000646 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000647 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000648 return New;
649 }
Chris Lattner402b3372008-03-03 03:28:21 +0000650
651 MergeAttributes(New, Old);
652
Chris Lattner4b009652007-07-25 00:24:17 +0000653 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000654 QualType OldCType = Context.getCanonicalType(Old->getType());
655 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000656 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000657 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000658 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000659 return New;
660 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000661 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
662 if (New->getStorageClass() == VarDecl::Static &&
663 (Old->getStorageClass() == VarDecl::None ||
664 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000665 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000666 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000667 return New;
668 }
669 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
670 if (New->getStorageClass() != VarDecl::Static &&
671 Old->getStorageClass() == VarDecl::Static) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000672 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000673 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000674 return New;
675 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000676 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
677 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000678 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000679 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000680 }
681 return New;
682}
683
Chris Lattner3e254fb2008-04-08 04:40:51 +0000684/// CheckParmsForFunctionDef - Check that the parameters of the given
685/// function are appropriate for the definition of a function. This
686/// takes care of any checks that cannot be performed on the
687/// declaration itself, e.g., that the types of each of the function
688/// parameters are complete.
689bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
690 bool HasInvalidParm = false;
691 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
692 ParmVarDecl *Param = FD->getParamDecl(p);
693
694 // C99 6.7.5.3p4: the parameters in a parameter type list in a
695 // function declarator that is part of a function definition of
696 // that function shall not have incomplete type.
697 if (Param->getType()->isIncompleteType() &&
698 !Param->isInvalidDecl()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000699 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +0000700 << Param->getType();
Chris Lattner3e254fb2008-04-08 04:40:51 +0000701 Param->setInvalidDecl();
702 HasInvalidParm = true;
703 }
704 }
705
706 return HasInvalidParm;
707}
708
Chris Lattner4b009652007-07-25 00:24:17 +0000709/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
710/// no declarator (e.g. "struct foo;") is parsed.
711Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
712 // TODO: emit error on 'int;' or 'const enum foo;'.
713 // TODO: emit error on 'typedef int;'
714 // if (!DS.isMissingDeclaratorOk()) Diag(...);
715
Steve Naroffedafc0b2007-11-17 21:37:36 +0000716 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000717}
718
Steve Narofff0b23542008-01-10 22:15:12 +0000719bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000720 // Get the type before calling CheckSingleAssignmentConstraints(), since
721 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000722 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000723
Chris Lattner005ed752008-01-04 18:04:52 +0000724 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
725 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
726 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000727}
728
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000729bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000730 const ArrayType *AT = Context.getAsArrayType(DeclT);
731
732 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000733 // C99 6.7.8p14. We have an array of character type with unknown size
734 // being initialized to a string literal.
735 llvm::APSInt ConstVal(32);
736 ConstVal = strLiteral->getByteLength() + 1;
737 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000738 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000739 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000740 } else {
741 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000742 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000743 // FIXME: Avoid truncation for 64-bit length strings.
744 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000745 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000746 diag::warn_initializer_string_for_char_array_too_long)
747 << strLiteral->getSourceRange();
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000748 }
749 // Set type from "char *" to "constant array of char".
750 strLiteral->setType(DeclT);
751 // For now, we always return false (meaning success).
752 return false;
753}
754
755StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000756 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +0000757 if (AT && AT->getElementType()->isCharType()) {
758 return dyn_cast<StringLiteral>(Init);
759 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000760 return 0;
761}
762
Douglas Gregor6428e762008-11-05 15:29:30 +0000763bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
764 SourceLocation InitLoc,
Chris Lattner271d4c22008-11-24 05:29:24 +0000765 DeclarationName InitEntity) {
Douglas Gregor81c29152008-10-29 00:13:59 +0000766 // C++ [dcl.init.ref]p1:
Sebastian Redl51504af2008-11-24 20:06:50 +0000767 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor81c29152008-10-29 00:13:59 +0000768 // (8.3.2), shall be initialized by an object, or function, of
769 // type T or by an object that can be converted into a T.
770 if (DeclType->isReferenceType())
771 return CheckReferenceInit(Init, DeclType);
772
Steve Naroff8e9337f2008-01-21 23:53:58 +0000773 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
774 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +0000775 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattner9d2cf082008-11-19 05:27:50 +0000776 return Diag(InitLoc, diag::err_variable_object_no_init)
777 << VAT->getSizeExpr()->getSourceRange();
Steve Naroff8e9337f2008-01-21 23:53:58 +0000778
Steve Naroffcb69fb72007-12-10 22:44:33 +0000779 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
780 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000781 // FIXME: Handle wide strings
782 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
783 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000784
Douglas Gregor6428e762008-11-05 15:29:30 +0000785 // C++ [dcl.init]p14:
786 // -- If the destination type is a (possibly cv-qualified) class
787 // type:
788 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
789 QualType DeclTypeC = Context.getCanonicalType(DeclType);
790 QualType InitTypeC = Context.getCanonicalType(Init->getType());
791
792 // -- If the initialization is direct-initialization, or if it is
793 // copy-initialization where the cv-unqualified version of the
794 // source type is the same class as, or a derived class of, the
795 // class of the destination, constructors are considered.
796 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
797 IsDerivedFrom(InitTypeC, DeclTypeC)) {
798 CXXConstructorDecl *Constructor
799 = PerformInitializationByConstructor(DeclType, &Init, 1,
800 InitLoc, Init->getSourceRange(),
801 InitEntity, IK_Copy);
802 return Constructor == 0;
803 }
804
805 // -- Otherwise (i.e., for the remaining copy-initialization
806 // cases), user-defined conversion sequences that can
807 // convert from the source type to the destination type or
808 // (when a conversion function is used) to a derived class
809 // thereof are enumerated as described in 13.3.1.4, and the
810 // best one is chosen through overload resolution
811 // (13.3). If the conversion cannot be done or is
812 // ambiguous, the initialization is ill-formed. The
813 // function selected is called with the initializer
814 // expression as its argument; if the function is a
815 // constructor, the call initializes a temporary of the
816 // destination type.
817 // FIXME: We're pretending to do copy elision here; return to
818 // this when we have ASTs for such things.
Chris Lattner70b93d82008-11-18 22:52:51 +0000819 if (!PerformImplicitConversion(Init, DeclType))
Douglas Gregor6428e762008-11-05 15:29:30 +0000820 return false;
Chris Lattner70b93d82008-11-18 22:52:51 +0000821
822 return Diag(InitLoc, diag::err_typecheck_convert_incompatible)
Chris Lattner271d4c22008-11-24 05:29:24 +0000823 << DeclType << InitEntity << "initializing"
Chris Lattner70b93d82008-11-18 22:52:51 +0000824 << Init->getSourceRange();
Douglas Gregor6428e762008-11-05 15:29:30 +0000825 }
826
Steve Naroffb2f72412008-09-29 20:07:05 +0000827 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +0000828 if (DeclType->isArrayType())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000829 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
830 << Init->getSourceRange();
Eli Friedman65280992008-02-08 00:48:24 +0000831
Steve Narofff0b23542008-01-10 22:15:12 +0000832 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor15e04622008-11-05 16:20:31 +0000833 } else if (getLangOptions().CPlusPlus) {
834 // C++ [dcl.init]p14:
835 // [...] If the class is an aggregate (8.5.1), and the initializer
836 // is a brace-enclosed list, see 8.5.1.
837 //
838 // Note: 8.5.1 is handled below; here, we diagnose the case where
839 // we have an initializer list and a destination type that is not
840 // an aggregate.
841 // FIXME: In C++0x, this is yet another form of initialization.
842 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
843 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
844 if (!ClassDecl->isAggregate())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000845 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000846 << DeclType << Init->getSourceRange();
Douglas Gregor15e04622008-11-05 16:20:31 +0000847 }
Steve Naroffcb69fb72007-12-10 22:44:33 +0000848 }
Eli Friedman38b7a912008-06-06 19:40:52 +0000849
Steve Naroffc4d4a482008-05-01 22:18:59 +0000850 InitListChecker CheckInitList(this, InitList, DeclType);
851 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +0000852}
853
Douglas Gregor6704b312008-11-17 22:58:34 +0000854/// GetNameForDeclarator - Determine the full declaration name for the
855/// given Declarator.
856DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
857 switch (D.getKind()) {
858 case Declarator::DK_Abstract:
859 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
860 return DeclarationName();
861
862 case Declarator::DK_Normal:
863 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
864 return DeclarationName(D.getIdentifier());
865
866 case Declarator::DK_Constructor: {
867 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
868 Ty = Context.getCanonicalType(Ty);
869 return Context.DeclarationNames.getCXXConstructorName(Ty);
870 }
871
872 case Declarator::DK_Destructor: {
873 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
874 Ty = Context.getCanonicalType(Ty);
875 return Context.DeclarationNames.getCXXDestructorName(Ty);
876 }
877
878 case Declarator::DK_Conversion: {
879 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
880 Ty = Context.getCanonicalType(Ty);
881 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
882 }
Douglas Gregor96a32dd2008-11-18 14:39:36 +0000883
884 case Declarator::DK_Operator:
885 assert(D.getIdentifier() == 0 && "operator names have no identifier");
886 return Context.DeclarationNames.getCXXOperatorName(
887 D.getOverloadedOperator());
Douglas Gregor6704b312008-11-17 22:58:34 +0000888 }
889
890 assert(false && "Unknown name kind");
891 return DeclarationName();
892}
893
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000894Sema::DeclTy *
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000895Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000896 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor6704b312008-11-17 22:58:34 +0000897 DeclarationName Name = GetNameForDeclarator(D);
898
Chris Lattner4b009652007-07-25 00:24:17 +0000899 // All of these full declarators require an identifier. If it doesn't have
900 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor6704b312008-11-17 22:58:34 +0000901 if (!Name) {
Chris Lattnercd61d592008-11-11 06:13:16 +0000902 if (!D.getInvalidType()) // Reject this if we think it is valid.
903 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000904 diag::err_declarator_need_ident)
905 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +0000906 return 0;
907 }
908
Chris Lattnera7549902007-08-26 06:24:45 +0000909 // The scope passed in may not be a decl scope. Zip up the scope tree until
910 // we find one that is.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000911 while ((S->getFlags() & Scope::DeclScope) == 0 ||
912 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattnera7549902007-08-26 06:24:45 +0000913 S = S->getParent();
914
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000915 DeclContext *DC;
916 Decl *PrevDecl;
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000917 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000918 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000919
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000920 // See if this is a redefinition of a variable in the same scope.
921 if (!D.getCXXScopeSpec().isSet()) {
922 DC = CurContext;
Douglas Gregor6704b312008-11-17 22:58:34 +0000923 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000924 } else { // Something like "int foo::x;"
925 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor6704b312008-11-17 22:58:34 +0000926 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000927
928 // C++ 7.3.1.2p2:
929 // Members (including explicit specializations of templates) of a named
930 // namespace can also be defined outside that namespace by explicit
931 // qualification of the name being defined, provided that the entity being
932 // defined was already declared in the namespace and the definition appears
933 // after the point of declaration in a namespace that encloses the
934 // declarations namespace.
935 //
936 if (PrevDecl == 0) {
937 // No previous declaration in the qualifying scope.
Chris Lattner77d52da2008-11-20 06:06:08 +0000938 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
Chris Lattnerb1753422008-11-23 21:45:46 +0000939 << Name << D.getCXXScopeSpec().getRange();
Douglas Gregor8acb7272008-12-11 16:49:14 +0000940 InvalidDecl = true;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000941 } else if (!CurContext->Encloses(DC)) {
942 // The qualifying scope doesn't enclose the original declaration.
943 // Emit diagnostic based on current scope.
944 SourceLocation L = D.getIdentifierLoc();
945 SourceRange R = D.getCXXScopeSpec().getRange();
946 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner254de7d2008-11-23 20:28:15 +0000947 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000948 } else {
Chris Lattner254de7d2008-11-23 20:28:15 +0000949 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattner271d4c22008-11-24 05:29:24 +0000950 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000951 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000952 InvalidDecl = true;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000953 }
954 }
955
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000956 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +0000957 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000958 InvalidDecl = InvalidDecl
959 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000960 // Just pretend that we didn't see the previous declaration.
961 PrevDecl = 0;
962 }
963
Douglas Gregor1d661552008-04-13 21:07:44 +0000964 // In C++, the previous declaration we find might be a tag type
965 // (class or enum). In this case, the new declaration will hide the
966 // tag type.
967 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
968 PrevDecl = 0;
969
Chris Lattner82bb4792007-11-14 06:34:38 +0000970 QualType R = GetTypeForDeclarator(D, S);
971 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
972
Chris Lattner4b009652007-07-25 00:24:17 +0000973 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000974 // Check that there are no default arguments (C++ only).
975 if (getLangOptions().CPlusPlus)
976 CheckExtraCXXDefaultArguments(D);
977
Chris Lattner82bb4792007-11-14 06:34:38 +0000978 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000979 if (!NewTD) return 0;
980
981 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000982 ProcessDeclAttributes(NewTD, D);
Steve Narofff8a09432008-01-09 23:34:55 +0000983 // Merge the decl with the existing one if appropriate. If the decl is
984 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000985 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000986 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
987 if (NewTD == 0) return 0;
988 }
989 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000990 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000991 // C99 6.7.7p2: If a typedef name specifies a variably modified type
992 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000993 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +0000994 if (NewTD->getUnderlyingType()->isVariableArrayType())
995 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
996 else
997 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
998
Steve Naroff5eb879b2007-08-31 17:20:07 +0000999 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001000 }
1001 }
Chris Lattner82bb4792007-11-14 06:34:38 +00001002 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +00001003 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +00001004 switch (D.getDeclSpec().getStorageClassSpec()) {
1005 default: assert(0 && "Unknown storage class!");
1006 case DeclSpec::SCS_auto:
1007 case DeclSpec::SCS_register:
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001008 case DeclSpec::SCS_mutable:
Chris Lattner4bfd2232008-11-24 06:25:27 +00001009 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001010 InvalidDecl = true;
1011 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001012 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1013 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1014 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +00001015 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +00001016 }
1017
Chris Lattner4c7802b2008-03-15 21:24:04 +00001018 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001019 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001020 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1021
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001022 FunctionDecl *NewFD;
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001023 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001024 // This is a C++ constructor declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001025 assert(DC->isCXXRecord() &&
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001026 "Constructors can only be declared in a member context");
1027
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001028 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001029
1030 // Create the new declaration
1031 NewFD = CXXConstructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001032 cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001033 D.getIdentifierLoc(), Name, R,
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001034 isExplicit, isInline,
1035 /*isImplicitlyDeclared=*/false);
1036
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001037 if (isInvalidDecl)
1038 NewFD->setInvalidDecl();
1039 } else if (D.getKind() == Declarator::DK_Destructor) {
1040 // This is a C++ destructor declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001041 if (DC->isCXXRecord()) {
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001042 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001043
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001044 NewFD = CXXDestructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001045 cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001046 D.getIdentifierLoc(), Name, R,
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001047 isInline,
1048 /*isImplicitlyDeclared=*/false);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001049
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001050 if (isInvalidDecl)
1051 NewFD->setInvalidDecl();
1052 } else {
1053 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1054 // Create a FunctionDecl to satisfy the function definition parsing
1055 // code path.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001056 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor6704b312008-11-17 22:58:34 +00001057 Name, R, SC, isInline, LastDeclarator,
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001058 // FIXME: Move to DeclGroup...
1059 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001060 NewFD->setInvalidDecl();
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001061 }
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001062 } else if (D.getKind() == Declarator::DK_Conversion) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001063 if (!DC->isCXXRecord()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001064 Diag(D.getIdentifierLoc(),
1065 diag::err_conv_function_not_member);
1066 return 0;
1067 } else {
1068 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
1069
1070 NewFD = CXXConversionDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001071 cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001072 D.getIdentifierLoc(), Name, R,
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001073 isInline, isExplicit);
1074
1075 if (isInvalidDecl)
1076 NewFD->setInvalidDecl();
1077 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001078 } else if (DC->isCXXRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001079 // This is a C++ method declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001080 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001081 D.getIdentifierLoc(), Name, R,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001082 (SC == FunctionDecl::Static), isInline,
1083 LastDeclarator);
1084 } else {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001085 NewFD = FunctionDecl::Create(Context, DC,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001086 D.getIdentifierLoc(),
Douglas Gregor6704b312008-11-17 22:58:34 +00001087 Name, R, SC, isInline, LastDeclarator,
Steve Naroff71cd7762008-10-03 00:02:03 +00001088 // FIXME: Move to DeclGroup...
1089 D.getDeclSpec().getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001090 }
Ted Kremenek117f1862008-02-27 22:18:07 +00001091 // Handle attributes.
Chris Lattner9b384ca2008-06-29 00:02:00 +00001092 ProcessDeclAttributes(NewFD, D);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001093
Daniel Dunbarc3540ff2008-08-05 01:35:17 +00001094 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001095 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +00001096 // The parser guarantees this is a string.
1097 StringLiteral *SE = cast<StringLiteral>(E);
1098 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1099 SE->getByteLength())));
1100 }
1101
Chris Lattner3e254fb2008-04-08 04:40:51 +00001102 // Copy the parameter declarations from the declarator D to
1103 // the function declaration NewFD, if they are available.
Eli Friedman769e7302008-08-25 21:31:01 +00001104 if (D.getNumTypeObjects() > 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001105 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1106
1107 // Create Decl objects for each parameter, adding them to the
1108 // FunctionDecl.
1109 llvm::SmallVector<ParmVarDecl*, 16> Params;
1110
1111 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1112 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +00001113 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +00001114 // We let through "const void" here because Sema::GetTypeForDeclarator
1115 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001116 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1117 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +00001118 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1119 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +00001120 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1121
Chris Lattnerda7b5f02008-04-10 02:26:16 +00001122 // In C++, the empty parameter-type-list must be spelled "void"; a
1123 // typedef of void is not permitted.
1124 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +00001125 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +00001126 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1127 }
Eli Friedman769e7302008-08-25 21:31:01 +00001128 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001129 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1130 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1131 }
1132
1133 NewFD->setParams(&Params[0], Params.size());
Douglas Gregorba3e8b72008-10-24 18:09:54 +00001134 } else if (R->getAsTypedefType()) {
1135 // When we're declaring a function with a typedef, as in the
1136 // following example, we'll need to synthesize (unnamed)
1137 // parameters for use in the declaration.
1138 //
1139 // @code
1140 // typedef void fn(int);
1141 // fn f;
1142 // @endcode
1143 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1144 if (!FT) {
1145 // This is a typedef of a function with no prototype, so we
1146 // don't need to do anything.
1147 } else if ((FT->getNumArgs() == 0) ||
1148 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1149 FT->getArgType(0)->isVoidType())) {
1150 // This is a zero-argument function. We don't need to do anything.
1151 } else {
1152 // Synthesize a parameter for each argument type.
1153 llvm::SmallVector<ParmVarDecl*, 16> Params;
1154 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1155 ArgType != FT->arg_type_end(); ++ArgType) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001156 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregorba3e8b72008-10-24 18:09:54 +00001157 SourceLocation(), 0,
1158 *ArgType, VarDecl::None,
1159 0, 0));
1160 }
1161
1162 NewFD->setParams(&Params[0], Params.size());
1163 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001164 }
1165
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001166 // C++ constructors and destructors are handled by separate
1167 // routines, since they don't require any declaration merging (C++
1168 // [class.mfct]p2) and they aren't ever pushed into scope, because
1169 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1170 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1171 return ActOnConstructorDeclarator(Constructor);
1172 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1173 return ActOnDestructorDeclarator(Destructor);
Douglas Gregorb0212bd2008-11-17 20:34:05 +00001174
1175 // Extra checking for conversion functions, including recording
1176 // the conversion function in its class.
1177 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1178 ActOnConversionDeclarator(Conversion);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001179
Douglas Gregore60e5d32008-11-06 22:13:31 +00001180 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1181 if (NewFD->isOverloadedOperator() &&
1182 CheckOverloadedOperatorDeclaration(NewFD))
1183 NewFD->setInvalidDecl();
1184
Steve Narofff8a09432008-01-09 23:34:55 +00001185 // Merge the decl with the existing one if appropriate. Since C functions
1186 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001187 if (PrevDecl &&
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001188 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregor42214c52008-04-21 02:02:58 +00001189 bool Redeclaration = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001190
1191 // If C++, determine whether NewFD is an overload of PrevDecl or
1192 // a declaration that requires merging. If it's an overload,
1193 // there's no more work to do here; we'll just add the new
1194 // function to the scope.
1195 OverloadedFunctionDecl::function_iterator MatchedDecl;
1196 if (!getLangOptions().CPlusPlus ||
1197 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1198 Decl *OldDecl = PrevDecl;
1199
1200 // If PrevDecl was an overloaded function, extract the
1201 // FunctionDecl that matched.
1202 if (isa<OverloadedFunctionDecl>(PrevDecl))
1203 OldDecl = *MatchedDecl;
1204
1205 // NewFD and PrevDecl represent declarations that need to be
1206 // merged.
1207 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1208
1209 if (NewFD == 0) return 0;
1210 if (Redeclaration) {
1211 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1212
1213 if (OldDecl == PrevDecl) {
1214 // Remove the name binding for the previous
Douglas Gregor8acb7272008-12-11 16:49:14 +00001215 // declaration.
1216 if (S->isDeclScope(PrevDecl)) {
1217 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1218 S->RemoveDecl(PrevDecl);
1219 }
1220
1221 // Introduce the new binding for this declaration.
1222 IdResolver.AddDecl(NewFD);
1223 if (getLangOptions().CPlusPlus && NewFD->getParent())
1224 NewFD->getParent()->insert(Context, NewFD);
1225
1226 // Add the redeclaration to the current scope, since we'll
1227 // be skipping PushOnScopeChains.
1228 S->AddDecl(NewFD);
Douglas Gregord2baafd2008-10-21 16:13:35 +00001229 } else {
1230 // We need to update the OverloadedFunctionDecl with the
1231 // latest declaration of this function, so that name
1232 // lookup will always refer to the latest declaration of
1233 // this function.
1234 *MatchedDecl = NewFD;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001235 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001236
Douglas Gregor8acb7272008-12-11 16:49:14 +00001237 if (getLangOptions().CPlusPlus) {
1238 // Add this declaration to the current context.
1239 CurContext->addDecl(Context, NewFD, false);
Douglas Gregord2baafd2008-10-21 16:13:35 +00001240
Douglas Gregor8acb7272008-12-11 16:49:14 +00001241 // Check default arguments now that we have merged decls.
1242 CheckCXXDefaultArguments(NewFD);
Douglas Gregord2baafd2008-10-21 16:13:35 +00001243 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001244
1245 // Set the lexical context. If the declarator has a C++
1246 // scope specifier, the lexical context will be different
1247 // from the semantic context.
1248 NewFD->setLexicalDeclContext(CurContext);
1249
1250 return NewFD;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001251 }
Douglas Gregor42214c52008-04-21 02:02:58 +00001252 }
Chris Lattner4b009652007-07-25 00:24:17 +00001253 }
1254 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001255
1256 // In C++, check default arguments now that we have merged decls.
1257 if (getLangOptions().CPlusPlus)
1258 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +00001259 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001260 // Check that there are no default arguments (C++ only).
1261 if (getLangOptions().CPlusPlus)
1262 CheckExtraCXXDefaultArguments(D);
1263
Ted Kremenek42730c52008-01-07 19:49:32 +00001264 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner65cae292008-11-19 08:23:25 +00001265 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1266 << D.getIdentifier();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001267 InvalidDecl = true;
1268 }
Chris Lattner4b009652007-07-25 00:24:17 +00001269
1270 VarDecl *NewVD;
1271 VarDecl::StorageClass SC;
1272 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +00001273 default: assert(0 && "Unknown storage class!");
1274 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1275 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1276 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1277 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1278 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1279 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001280 case DeclSpec::SCS_mutable:
1281 // mutable can only appear on non-static class members, so it's always
1282 // an error here
1283 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1284 InvalidDecl = true;
Douglas Gregor538754e2008-12-01 22:46:22 +00001285 SC = VarDecl::None;
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +00001286 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001287 }
Douglas Gregor6704b312008-11-17 22:58:34 +00001288
1289 IdentifierInfo *II = Name.getAsIdentifierInfo();
1290 if (!II) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00001291 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1292 << Name.getAsString();
Douglas Gregor6704b312008-11-17 22:58:34 +00001293 return 0;
1294 }
1295
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001296 if (DC->isCXXRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001297 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1298 // This is a static data member for a C++ class.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001299 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001300 D.getIdentifierLoc(), II,
1301 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +00001302 } else {
Daniel Dunbar5eea5622008-09-08 20:05:47 +00001303 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001304 if (S->getFnParent() == 0) {
1305 // C99 6.9p2: The storage-class specifiers auto and register shall not
1306 // appear in the declaration specifiers in an external declaration.
1307 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattner4bfd2232008-11-24 06:25:27 +00001308 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001309 InvalidDecl = true;
1310 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001311 }
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001312 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1313 II, R, SC, LastDeclarator,
1314 // FIXME: Move to DeclGroup...
1315 D.getDeclSpec().getSourceRange().getBegin());
1316 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroffcae537d2007-08-28 18:45:29 +00001317 }
Chris Lattner4b009652007-07-25 00:24:17 +00001318 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +00001319 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +00001320
Daniel Dunbarced89142008-08-06 00:03:29 +00001321 // Handle GNU asm-label extension (encoded as an attribute).
1322 if (Expr *E = (Expr*) D.getAsmLabel()) {
1323 // The parser guarantees this is a string.
1324 StringLiteral *SE = cast<StringLiteral>(E);
1325 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1326 SE->getByteLength())));
1327 }
1328
Nate Begemanea583262008-03-14 18:07:10 +00001329 // Emit an error if an address space was applied to decl with local storage.
1330 // This includes arrays of objects with address space qualifiers, but not
1331 // automatic variables that point to other address spaces.
1332 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +00001333 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1334 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1335 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +00001336 }
Steve Narofff8a09432008-01-09 23:34:55 +00001337 // Merge the decl with the existing one if appropriate. If the decl is
1338 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001339 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001340 NewVD = MergeVarDecl(NewVD, PrevDecl);
1341 if (NewVD == 0) return 0;
1342 }
Chris Lattner4b009652007-07-25 00:24:17 +00001343 New = NewVD;
1344 }
1345
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001346 // Set the lexical context. If the declarator has a C++ scope specifier, the
1347 // lexical context will be different from the semantic context.
1348 New->setLexicalDeclContext(CurContext);
1349
Chris Lattner4b009652007-07-25 00:24:17 +00001350 // If this has an identifier, add it to the scope stack.
Douglas Gregor6704b312008-11-17 22:58:34 +00001351 if (Name)
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001352 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001353 // If any semantic error occurred, mark the decl as invalid.
1354 if (D.getInvalidType() || InvalidDecl)
1355 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001356
1357 return New;
1358}
1359
Steve Narofffc08f5e2008-10-27 11:34:16 +00001360void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001361 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1362 << Init->getSourceRange();
Steve Narofffc08f5e2008-10-27 11:34:16 +00001363}
1364
Eli Friedman02c22ce2008-05-20 13:48:25 +00001365bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1366 switch (Init->getStmtClass()) {
1367 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001368 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001369 return true;
1370 case Expr::ParenExprClass: {
1371 const ParenExpr* PE = cast<ParenExpr>(Init);
1372 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1373 }
1374 case Expr::CompoundLiteralExprClass:
1375 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1376 case Expr::DeclRefExprClass: {
1377 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001378 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1379 if (VD->hasGlobalStorage())
1380 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001381 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001382 return true;
1383 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001384 if (isa<FunctionDecl>(D))
1385 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001386 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001387 return true;
1388 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001389 case Expr::MemberExprClass: {
1390 const MemberExpr *M = cast<MemberExpr>(Init);
1391 if (M->isArrow())
1392 return CheckAddressConstantExpression(M->getBase());
1393 return CheckAddressConstantExpressionLValue(M->getBase());
1394 }
1395 case Expr::ArraySubscriptExprClass: {
1396 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1397 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1398 return CheckAddressConstantExpression(ASE->getBase()) ||
1399 CheckArithmeticConstantExpression(ASE->getIdx());
1400 }
1401 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001402 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001403 return false;
1404 case Expr::UnaryOperatorClass: {
1405 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1406
1407 // C99 6.6p9
1408 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001409 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001410
Steve Narofffc08f5e2008-10-27 11:34:16 +00001411 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001412 return true;
1413 }
1414 }
1415}
1416
1417bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1418 switch (Init->getStmtClass()) {
1419 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001420 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001421 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001422 case Expr::ParenExprClass:
1423 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001424 case Expr::StringLiteralClass:
1425 case Expr::ObjCStringLiteralClass:
1426 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001427 case Expr::CallExprClass:
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001428 case Expr::CXXOperatorCallExprClass:
Chris Lattner0903cba2008-10-06 07:26:43 +00001429 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1430 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1431 Builtin::BI__builtin___CFStringMakeConstantString)
1432 return false;
1433
Steve Narofffc08f5e2008-10-27 11:34:16 +00001434 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001435 return true;
1436
Eli Friedman02c22ce2008-05-20 13:48:25 +00001437 case Expr::UnaryOperatorClass: {
1438 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1439
1440 // C99 6.6p9
1441 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1442 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1443
1444 if (Exp->getOpcode() == UnaryOperator::Extension)
1445 return CheckAddressConstantExpression(Exp->getSubExpr());
1446
Steve Narofffc08f5e2008-10-27 11:34:16 +00001447 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001448 return true;
1449 }
1450 case Expr::BinaryOperatorClass: {
1451 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1452 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1453
1454 Expr *PExp = Exp->getLHS();
1455 Expr *IExp = Exp->getRHS();
1456 if (IExp->getType()->isPointerType())
1457 std::swap(PExp, IExp);
1458
1459 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1460 return CheckAddressConstantExpression(PExp) ||
1461 CheckArithmeticConstantExpression(IExp);
1462 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001463 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001464 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001465 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001466 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1467 // Check for implicit promotion
1468 if (SubExpr->getType()->isFunctionType() ||
1469 SubExpr->getType()->isArrayType())
1470 return CheckAddressConstantExpressionLValue(SubExpr);
1471 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001472
1473 // Check for pointer->pointer cast
1474 if (SubExpr->getType()->isPointerType())
1475 return CheckAddressConstantExpression(SubExpr);
1476
Eli Friedman1fad3c62008-08-25 20:46:57 +00001477 if (SubExpr->getType()->isIntegralType()) {
1478 // Check for the special-case of a pointer->int->pointer cast;
1479 // this isn't standard, but some code requires it. See
1480 // PR2720 for an example.
1481 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1482 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1483 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1484 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1485 if (IntWidth >= PointerWidth) {
1486 return CheckAddressConstantExpression(SubCast->getSubExpr());
1487 }
1488 }
1489 }
1490 }
1491 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001492 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001493 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001494
Steve Narofffc08f5e2008-10-27 11:34:16 +00001495 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001496 return true;
1497 }
1498 case Expr::ConditionalOperatorClass: {
1499 // FIXME: Should we pedwarn here?
1500 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1501 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001502 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001503 return true;
1504 }
1505 if (CheckArithmeticConstantExpression(Exp->getCond()))
1506 return true;
1507 if (Exp->getLHS() &&
1508 CheckAddressConstantExpression(Exp->getLHS()))
1509 return true;
1510 return CheckAddressConstantExpression(Exp->getRHS());
1511 }
1512 case Expr::AddrLabelExprClass:
1513 return false;
1514 }
1515}
1516
Eli Friedman998dffb2008-06-09 05:05:07 +00001517static const Expr* FindExpressionBaseAddress(const Expr* E);
1518
1519static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1520 switch (E->getStmtClass()) {
1521 default:
1522 return E;
1523 case Expr::ParenExprClass: {
1524 const ParenExpr* PE = cast<ParenExpr>(E);
1525 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1526 }
1527 case Expr::MemberExprClass: {
1528 const MemberExpr *M = cast<MemberExpr>(E);
1529 if (M->isArrow())
1530 return FindExpressionBaseAddress(M->getBase());
1531 return FindExpressionBaseAddressLValue(M->getBase());
1532 }
1533 case Expr::ArraySubscriptExprClass: {
1534 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1535 return FindExpressionBaseAddress(ASE->getBase());
1536 }
1537 case Expr::UnaryOperatorClass: {
1538 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1539
1540 if (Exp->getOpcode() == UnaryOperator::Deref)
1541 return FindExpressionBaseAddress(Exp->getSubExpr());
1542
1543 return E;
1544 }
1545 }
1546}
1547
1548static const Expr* FindExpressionBaseAddress(const Expr* E) {
1549 switch (E->getStmtClass()) {
1550 default:
1551 return E;
1552 case Expr::ParenExprClass: {
1553 const ParenExpr* PE = cast<ParenExpr>(E);
1554 return FindExpressionBaseAddress(PE->getSubExpr());
1555 }
1556 case Expr::UnaryOperatorClass: {
1557 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1558
1559 // C99 6.6p9
1560 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1561 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1562
1563 if (Exp->getOpcode() == UnaryOperator::Extension)
1564 return FindExpressionBaseAddress(Exp->getSubExpr());
1565
1566 return E;
1567 }
1568 case Expr::BinaryOperatorClass: {
1569 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1570
1571 Expr *PExp = Exp->getLHS();
1572 Expr *IExp = Exp->getRHS();
1573 if (IExp->getType()->isPointerType())
1574 std::swap(PExp, IExp);
1575
1576 return FindExpressionBaseAddress(PExp);
1577 }
1578 case Expr::ImplicitCastExprClass: {
1579 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1580
1581 // Check for implicit promotion
1582 if (SubExpr->getType()->isFunctionType() ||
1583 SubExpr->getType()->isArrayType())
1584 return FindExpressionBaseAddressLValue(SubExpr);
1585
1586 // Check for pointer->pointer cast
1587 if (SubExpr->getType()->isPointerType())
1588 return FindExpressionBaseAddress(SubExpr);
1589
1590 // We assume that we have an arithmetic expression here;
1591 // if we don't, we'll figure it out later
1592 return 0;
1593 }
Douglas Gregor035d0882008-10-28 15:36:24 +00001594 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001595 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1596
1597 // Check for pointer->pointer cast
1598 if (SubExpr->getType()->isPointerType())
1599 return FindExpressionBaseAddress(SubExpr);
1600
1601 // We assume that we have an arithmetic expression here;
1602 // if we don't, we'll figure it out later
1603 return 0;
1604 }
1605 }
1606}
1607
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001608bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001609 switch (Init->getStmtClass()) {
1610 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001611 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001612 return true;
1613 case Expr::ParenExprClass: {
1614 const ParenExpr* PE = cast<ParenExpr>(Init);
1615 return CheckArithmeticConstantExpression(PE->getSubExpr());
1616 }
1617 case Expr::FloatingLiteralClass:
1618 case Expr::IntegerLiteralClass:
1619 case Expr::CharacterLiteralClass:
1620 case Expr::ImaginaryLiteralClass:
1621 case Expr::TypesCompatibleExprClass:
1622 case Expr::CXXBoolLiteralExprClass:
1623 return false;
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001624 case Expr::CallExprClass:
1625 case Expr::CXXOperatorCallExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001626 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001627
1628 // Allow any constant foldable calls to builtins.
1629 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001630 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001631
Steve Narofffc08f5e2008-10-27 11:34:16 +00001632 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001633 return true;
1634 }
1635 case Expr::DeclRefExprClass: {
1636 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1637 if (isa<EnumConstantDecl>(D))
1638 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001639 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001640 return true;
1641 }
1642 case Expr::CompoundLiteralExprClass:
1643 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1644 // but vectors are allowed to be magic.
1645 if (Init->getType()->isVectorType())
1646 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001647 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001648 return true;
1649 case Expr::UnaryOperatorClass: {
1650 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1651
1652 switch (Exp->getOpcode()) {
1653 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1654 // See C99 6.6p3.
1655 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001656 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001657 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001658 case UnaryOperator::OffsetOf:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001659 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1660 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001661 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001662 return true;
1663 case UnaryOperator::Extension:
1664 case UnaryOperator::LNot:
1665 case UnaryOperator::Plus:
1666 case UnaryOperator::Minus:
1667 case UnaryOperator::Not:
1668 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1669 }
1670 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001671 case Expr::SizeOfAlignOfExprClass: {
1672 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001673 // Special check for void types, which are allowed as an extension
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001674 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedman02c22ce2008-05-20 13:48:25 +00001675 return false;
1676 // alignof always evaluates to a constant.
1677 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001678 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001679 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001680 return true;
1681 }
1682 return false;
1683 }
1684 case Expr::BinaryOperatorClass: {
1685 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1686
1687 if (Exp->getLHS()->getType()->isArithmeticType() &&
1688 Exp->getRHS()->getType()->isArithmeticType()) {
1689 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1690 CheckArithmeticConstantExpression(Exp->getRHS());
1691 }
1692
Eli Friedman998dffb2008-06-09 05:05:07 +00001693 if (Exp->getLHS()->getType()->isPointerType() &&
1694 Exp->getRHS()->getType()->isPointerType()) {
1695 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1696 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1697
1698 // Only allow a null (constant integer) base; we could
1699 // allow some additional cases if necessary, but this
1700 // is sufficient to cover offsetof-like constructs.
1701 if (!LHSBase && !RHSBase) {
1702 return CheckAddressConstantExpression(Exp->getLHS()) ||
1703 CheckAddressConstantExpression(Exp->getRHS());
1704 }
1705 }
1706
Steve Narofffc08f5e2008-10-27 11:34:16 +00001707 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001708 return true;
1709 }
1710 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001711 case Expr::CStyleCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001712 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00001713 if (SubExpr->getType()->isArithmeticType())
1714 return CheckArithmeticConstantExpression(SubExpr);
1715
Eli Friedman266df142008-09-02 09:37:00 +00001716 if (SubExpr->getType()->isPointerType()) {
1717 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1718 // If the pointer has a null base, this is an offsetof-like construct
1719 if (!Base)
1720 return CheckAddressConstantExpression(SubExpr);
1721 }
1722
Steve Narofffc08f5e2008-10-27 11:34:16 +00001723 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00001724 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001725 }
1726 case Expr::ConditionalOperatorClass: {
1727 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00001728
1729 // If GNU extensions are disabled, we require all operands to be arithmetic
1730 // constant expressions.
1731 if (getLangOptions().NoExtensions) {
1732 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1733 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1734 CheckArithmeticConstantExpression(Exp->getRHS());
1735 }
1736
1737 // Otherwise, we have to emulate some of the behavior of fold here.
1738 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1739 // because it can constant fold things away. To retain compatibility with
1740 // GCC code, we see if we can fold the condition to a constant (which we
1741 // should always be able to do in theory). If so, we only require the
1742 // specified arm of the conditional to be a constant. This is a horrible
1743 // hack, but is require by real world code that uses __builtin_constant_p.
1744 APValue Val;
Chris Lattneref069662008-11-16 21:24:15 +00001745 if (!Exp->getCond()->Evaluate(Val, Context)) {
1746 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner94d45412008-10-06 05:42:39 +00001747 // won't be able to either. Use it to emit the diagnostic though.
1748 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattneref069662008-11-16 21:24:15 +00001749 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner94d45412008-10-06 05:42:39 +00001750 return Res;
1751 }
1752
1753 // Verify that the side following the condition is also a constant.
1754 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1755 if (Val.getInt() == 0)
1756 std::swap(TrueSide, FalseSide);
1757
1758 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001759 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00001760
1761 // Okay, the evaluated side evaluates to a constant, so we accept this.
1762 // Check to see if the other side is obviously not a constant. If so,
1763 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001764 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00001765 Diag(Init->getExprLoc(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00001766 diag::ext_typecheck_expression_not_constant_but_accepted)
1767 << FalseSide->getSourceRange();
Chris Lattner94d45412008-10-06 05:42:39 +00001768 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001769 }
1770 }
1771}
1772
1773bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlssonf6791c62008-12-05 05:09:56 +00001774 Expr::EvalResult Result;
1775
Nuno Lopese7280452008-07-07 16:46:50 +00001776 Init = Init->IgnoreParens();
1777
Anders Carlssonf6791c62008-12-05 05:09:56 +00001778 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
1779 return false;
1780
Eli Friedman02c22ce2008-05-20 13:48:25 +00001781 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1782 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1783 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1784
Nuno Lopese7280452008-07-07 16:46:50 +00001785 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1786 return CheckForConstantInitializer(e->getInitializer(), DclT);
1787
Eli Friedman02c22ce2008-05-20 13:48:25 +00001788 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1789 unsigned numInits = Exp->getNumInits();
1790 for (unsigned i = 0; i < numInits; i++) {
1791 // FIXME: Need to get the type of the declaration for C++,
1792 // because it could be a reference?
1793 if (CheckForConstantInitializer(Exp->getInit(i),
1794 Exp->getInit(i)->getType()))
1795 return true;
1796 }
1797 return false;
1798 }
1799
Anders Carlssonf6791c62008-12-05 05:09:56 +00001800 // FIXME: We can probably remove some of this code below, now that
1801 // Expr::Evaluate is doing the heavy lifting for scalars.
1802
Eli Friedman02c22ce2008-05-20 13:48:25 +00001803 if (Init->isNullPointerConstant(Context))
1804 return false;
1805 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001806 QualType InitTy = Context.getCanonicalType(Init->getType())
1807 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00001808 if (InitTy == Context.BoolTy) {
1809 // Special handling for pointers implicitly cast to bool;
1810 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1811 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1812 Expr* SubE = ICE->getSubExpr();
1813 if (SubE->getType()->isPointerType() ||
1814 SubE->getType()->isArrayType() ||
1815 SubE->getType()->isFunctionType()) {
1816 return CheckAddressConstantExpression(Init);
1817 }
1818 }
1819 } else if (InitTy->isIntegralType()) {
1820 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001821 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00001822 SubE = CE->getSubExpr();
1823 // Special check for pointer cast to int; we allow as an extension
1824 // an address constant cast to an integer if the integer
1825 // is of an appropriate width (this sort of code is apparently used
1826 // in some places).
1827 // FIXME: Add pedwarn?
1828 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1829 if (SubE && (SubE->getType()->isPointerType() ||
1830 SubE->getType()->isArrayType() ||
1831 SubE->getType()->isFunctionType())) {
1832 unsigned IntWidth = Context.getTypeSize(Init->getType());
1833 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1834 if (IntWidth >= PointerWidth)
1835 return CheckAddressConstantExpression(Init);
1836 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001837 }
1838
1839 return CheckArithmeticConstantExpression(Init);
1840 }
1841
1842 if (Init->getType()->isPointerType())
1843 return CheckAddressConstantExpression(Init);
1844
Eli Friedman25086f02008-05-30 18:14:48 +00001845 // An array type at the top level that isn't an init-list must
1846 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00001847 if (Init->getType()->isArrayType())
1848 return false;
1849
Nuno Lopes1dc26762008-09-01 18:42:41 +00001850 if (Init->getType()->isFunctionType())
1851 return false;
1852
Steve Naroffdff3fb22008-10-02 17:12:56 +00001853 // Allow block exprs at top level.
1854 if (Init->getType()->isBlockPointerType())
1855 return false;
1856
Steve Narofffc08f5e2008-10-27 11:34:16 +00001857 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001858 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00001859}
1860
Steve Naroff6a0e2092007-09-12 14:07:44 +00001861void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001862 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001863 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001864 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001865
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001866 // If there is no declaration, there was an error parsing it. Just ignore
1867 // the initializer.
1868 if (RealDecl == 0) {
1869 delete Init;
1870 return;
1871 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001872
Steve Naroff420d0f52007-09-12 20:13:48 +00001873 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1874 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001875 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1876 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001877 RealDecl->setInvalidDecl();
1878 return;
1879 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001880 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001881 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001882 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001883 if (VDecl->isBlockVarDecl()) {
1884 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001885 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001886 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001887 VDecl->setInvalidDecl();
1888 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001889 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00001890 VDecl->getDeclName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001891 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00001892
1893 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1894 if (!getLangOptions().CPlusPlus) {
1895 if (SC == VarDecl::Static) // C99 6.7.8p4.
1896 CheckForConstantInitializer(Init, DclT);
1897 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001898 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001899 } else if (VDecl->isFileVarDecl()) {
1900 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001901 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001902 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00001903 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00001904 VDecl->getDeclName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001905 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001906
Anders Carlssonea7140a2008-08-22 05:00:02 +00001907 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1908 if (!getLangOptions().CPlusPlus) {
1909 // C99 6.7.8p4. All file scoped initializers need to be constant.
1910 CheckForConstantInitializer(Init, DclT);
1911 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001912 }
1913 // If the type changed, it means we had an incomplete type that was
1914 // completed by the initializer. For example:
1915 // int ary[] = { 1, 3, 5 };
1916 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001917 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001918 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001919 Init->setType(DclT);
1920 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001921
1922 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001923 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001924 return;
1925}
1926
Douglas Gregor81c29152008-10-29 00:13:59 +00001927void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1928 Decl *RealDecl = static_cast<Decl *>(dcl);
1929
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00001930 // If there is no declaration, there was an error parsing it. Just ignore it.
1931 if (RealDecl == 0)
1932 return;
1933
Douglas Gregor81c29152008-10-29 00:13:59 +00001934 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1935 QualType Type = Var->getType();
1936 // C++ [dcl.init.ref]p3:
1937 // The initializer can be omitted for a reference only in a
1938 // parameter declaration (8.3.5), in the declaration of a
1939 // function return type, in the declaration of a class member
1940 // within its class declaration (9.2), and where the extern
1941 // specifier is explicitly used.
Douglas Gregor5870a952008-11-03 20:45:27 +00001942 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Chris Lattner77d52da2008-11-20 06:06:08 +00001943 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattner271d4c22008-11-24 05:29:24 +00001944 << Var->getDeclName()
1945 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor5870a952008-11-03 20:45:27 +00001946 Var->setInvalidDecl();
1947 return;
1948 }
1949
1950 // C++ [dcl.init]p9:
1951 //
1952 // If no initializer is specified for an object, and the object
1953 // is of (possibly cv-qualified) non-POD class type (or array
1954 // thereof), the object shall be default-initialized; if the
1955 // object is of const-qualified type, the underlying class type
1956 // shall have a user-declared default constructor.
1957 if (getLangOptions().CPlusPlus) {
1958 QualType InitType = Type;
1959 if (const ArrayType *Array = Context.getAsArrayType(Type))
1960 InitType = Array->getElementType();
1961 if (InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001962 const CXXConstructorDecl *Constructor
1963 = PerformInitializationByConstructor(InitType, 0, 0,
1964 Var->getLocation(),
1965 SourceRange(Var->getLocation(),
1966 Var->getLocation()),
Chris Lattner271d4c22008-11-24 05:29:24 +00001967 Var->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00001968 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00001969 if (!Constructor)
1970 Var->setInvalidDecl();
1971 }
1972 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001973
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001974#if 0
1975 // FIXME: Temporarily disabled because we are not properly parsing
1976 // linkage specifications on declarations, e.g.,
1977 //
1978 // extern "C" const CGPoint CGPointerZero;
1979 //
Douglas Gregor81c29152008-10-29 00:13:59 +00001980 // C++ [dcl.init]p9:
1981 //
1982 // If no initializer is specified for an object, and the
1983 // object is of (possibly cv-qualified) non-POD class type (or
1984 // array thereof), the object shall be default-initialized; if
1985 // the object is of const-qualified type, the underlying class
1986 // type shall have a user-declared default
1987 // constructor. Otherwise, if no initializer is specified for
1988 // an object, the object and its subobjects, if any, have an
1989 // indeterminate initial value; if the object or any of its
1990 // subobjects are of const-qualified type, the program is
1991 // ill-formed.
1992 //
1993 // This isn't technically an error in C, so we don't diagnose it.
1994 //
1995 // FIXME: Actually perform the POD/user-defined default
1996 // constructor check.
1997 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001998 Context.getCanonicalType(Type).isConstQualified() &&
1999 Var->getStorageClass() != VarDecl::Extern)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002000 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2001 << Var->getName()
2002 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002003#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00002004 }
2005}
2006
Chris Lattner4b009652007-07-25 00:24:17 +00002007/// The declarators are chained together backwards, reverse the list.
2008Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2009 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002010 Decl *GroupDecl = static_cast<Decl*>(group);
2011 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00002012 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00002013
2014 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2015 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002016 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00002017 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002018 else { // reverse the list.
2019 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00002020 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002021 Group->setNextDeclarator(NewGroup);
2022 NewGroup = Group;
2023 Group = Next;
2024 }
2025 }
2026 // Perform semantic analysis that depends on having fully processed both
2027 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002028 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00002029 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2030 if (!IDecl)
2031 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002032 QualType T = IDecl->getType();
2033
Anders Carlsson68adbd12008-12-07 00:20:55 +00002034 if (T->isVariableArrayType()) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002035 const VariableArrayType *VAT =
2036 cast<VariableArrayType>(T.getUnqualifiedType());
2037
2038 // FIXME: This won't give the correct result for
2039 // int a[10][n];
2040 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002041 if (IDecl->isFileVarDecl()) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002042 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2043 SizeRange;
2044
Eli Friedman8ff07782008-02-15 18:16:39 +00002045 IDecl->setInvalidDecl();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002046 } else {
2047 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2048 // static storage duration, it shall not have a variable length array.
2049 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002050 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2051 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002052 IDecl->setInvalidDecl();
2053 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002054 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2055 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002056 IDecl->setInvalidDecl();
2057 }
2058 }
2059 } else if (T->isVariablyModifiedType()) {
2060 if (IDecl->isFileVarDecl()) {
2061 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2062 IDecl->setInvalidDecl();
2063 } else {
2064 if (IDecl->getStorageClass() == VarDecl::Extern) {
2065 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2066 IDecl->setInvalidDecl();
2067 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002068 }
2069 }
Anders Carlsson68adbd12008-12-07 00:20:55 +00002070
Steve Naroff6a0e2092007-09-12 14:07:44 +00002071 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2072 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002073 if (IDecl->isBlockVarDecl() &&
2074 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00002075 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner271d4c22008-11-24 05:29:24 +00002076 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002077 IDecl->setInvalidDecl();
2078 }
2079 }
2080 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2081 // object that has file scope without an initializer, and without a
2082 // storage-class specifier or with the storage-class specifier "static",
2083 // constitutes a tentative definition. Note: A tentative definition with
2084 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00002085 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00002086 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00002087 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2088 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00002089 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00002090 // C99 6.9.2p3: If the declaration of an identifier for an object is
2091 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2092 // declared type shall not be an incomplete type.
Chris Lattner271d4c22008-11-24 05:29:24 +00002093 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002094 IDecl->setInvalidDecl();
2095 }
2096 }
Steve Naroffb5e78152008-08-08 17:50:35 +00002097 if (IDecl->isFileVarDecl())
2098 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002099 }
2100 return NewGroup;
2101}
Steve Naroff91b03f72007-08-28 03:03:08 +00002102
Chris Lattner3e254fb2008-04-08 04:40:51 +00002103/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2104/// to introduce parameters into function prototype scope.
2105Sema::DeclTy *
2106Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002107 // FIXME: disallow CXXScopeSpec for param declarators.
Chris Lattner5e77ade2008-06-26 06:49:43 +00002108 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002109
2110 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002111 VarDecl::StorageClass StorageClass = VarDecl::None;
2112 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2113 StorageClass = VarDecl::Register;
2114 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002115 Diag(DS.getStorageClassSpecLoc(),
2116 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002117 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002118 }
2119 if (DS.isThreadSpecified()) {
2120 Diag(DS.getThreadSpecLoc(),
2121 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002122 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002123 }
2124
Douglas Gregor2b9422f2008-05-07 04:49:29 +00002125 // Check that there are no default arguments inside the type of this
2126 // parameter (C++ only).
2127 if (getLangOptions().CPlusPlus)
2128 CheckExtraCXXDefaultArguments(D);
2129
Chris Lattner3e254fb2008-04-08 04:40:51 +00002130 // In this context, we *do not* check D.getInvalidType(). If the declarator
2131 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2132 // though it will not reflect the user specified type.
2133 QualType parmDeclType = GetTypeForDeclarator(D, S);
2134
2135 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2136
Chris Lattner4b009652007-07-25 00:24:17 +00002137 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2138 // Can this happen for params? We already checked that they don't conflict
2139 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002140 IdentifierInfo *II = D.getIdentifier();
2141 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002142 if (PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002143 // Maybe we will complain about the shadowed template parameter.
2144 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2145 // Just pretend that we didn't see the previous declaration.
2146 PrevDecl = 0;
2147 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002148 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002149
2150 // Recover by removing the name
2151 II = 0;
2152 D.SetIdentifier(0, D.getIdentifierLoc());
2153 }
Chris Lattner4b009652007-07-25 00:24:17 +00002154 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00002155
2156 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2157 // Doing the promotion here has a win and a loss. The win is the type for
2158 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2159 // code generator). The loss is the orginal type isn't preserved. For example:
2160 //
2161 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2162 // int blockvardecl[5];
2163 // sizeof(parmvardecl); // size == 4
2164 // sizeof(blockvardecl); // size == 20
2165 // }
2166 //
2167 // For expressions, all implicit conversions are captured using the
2168 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2169 //
2170 // FIXME: If a source translation tool needs to see the original type, then
2171 // we need to consider storing both types (in ParmVarDecl)...
2172 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00002173 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00002174 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00002175 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00002176 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00002177 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002178
Chris Lattner3e254fb2008-04-08 04:40:51 +00002179 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2180 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002181 parmDeclType, StorageClass,
Chris Lattner3e254fb2008-04-08 04:40:51 +00002182 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00002183
Chris Lattner3e254fb2008-04-08 04:40:51 +00002184 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00002185 New->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002186
2187 // Add the parameter declaration into this scope.
2188 S->AddDecl(New);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002189 if (II)
Douglas Gregor8acb7272008-12-11 16:49:14 +00002190 IdResolver.AddDecl(New);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00002191
Chris Lattner9b384ca2008-06-29 00:02:00 +00002192 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00002193 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002194
Chris Lattner4b009652007-07-25 00:24:17 +00002195}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00002196
Chris Lattnerea148702007-10-09 17:14:05 +00002197Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002198 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00002199 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2200 "Not a function declarator!");
2201 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002202
Chris Lattner4b009652007-07-25 00:24:17 +00002203 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2204 // for a K&R function.
2205 if (!FTI.hasPrototype) {
2206 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002207 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002208 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2209 << FTI.ArgInfo[i].Ident;
Chris Lattner4b009652007-07-25 00:24:17 +00002210 // Implicitly declare the argument as type 'int' for lack of a better
2211 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002212 DeclSpec DS;
2213 const char* PrevSpec; // unused
2214 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2215 PrevSpec);
2216 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2217 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2218 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00002219 }
2220 }
Chris Lattner4b009652007-07-25 00:24:17 +00002221 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002222 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00002223 }
2224
2225 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00002226
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002227 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002228 ActOnDeclarator(GlobalScope, D, 0));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002229}
2230
2231Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2232 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002233 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002234
2235 // See if this is a redefinition.
2236 const FunctionDecl *Definition;
2237 if (FD->getBody(Definition)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002238 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00002239 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor56da7862008-10-29 15:10:40 +00002240 }
2241
Douglas Gregor8acb7272008-12-11 16:49:14 +00002242 PushDeclContext(FnBodyScope, FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00002243
2244 // Check the validity of our function parameters
2245 CheckParmsForFunctionDef(FD);
2246
2247 // Introduce our parameters into the function scope
2248 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2249 ParmVarDecl *Param = FD->getParamDecl(p);
2250 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002251 if (Param->getIdentifier())
2252 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002253 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002254
Chris Lattner4b009652007-07-25 00:24:17 +00002255 return FD;
2256}
2257
Steve Naroff99ee4302007-11-11 23:20:51 +00002258Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
2259 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002260 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002261 FD->setBody((Stmt*)Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002262 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002263 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002264 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002265 } else
2266 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002267 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002268 // Verify and clean out per-function state.
2269
2270 // Check goto/label use.
2271 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2272 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2273 // Verify that we have no forward references left. If so, there was a goto
2274 // or address of a label taken, but no definition of it. Label fwd
2275 // definitions are indicated with a null substmt.
2276 if (I->second->getSubStmt() == 0) {
2277 LabelStmt *L = I->second;
2278 // Emit error.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002279 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Chris Lattner4b009652007-07-25 00:24:17 +00002280
2281 // At this point, we have gotos that use the bogus label. Stitch it into
2282 // the function body so that they aren't leaked and that the AST is well
2283 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002284 if (Body) {
2285 L->setSubStmt(new NullStmt(L->getIdentLoc()));
2286 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2287 } else {
2288 // The whole function wasn't parsed correctly, just delete this.
2289 delete L;
2290 }
Chris Lattner4b009652007-07-25 00:24:17 +00002291 }
2292 }
2293 LabelMap.clear();
2294
Steve Naroff99ee4302007-11-11 23:20:51 +00002295 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002296}
2297
Chris Lattner4b009652007-07-25 00:24:17 +00002298/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2299/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00002300ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2301 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002302 // Extension in C99. Legal in C90, but warn about it.
2303 if (getLangOptions().C99)
Chris Lattner65cae292008-11-19 08:23:25 +00002304 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002305 else
Chris Lattner65cae292008-11-19 08:23:25 +00002306 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Chris Lattner4b009652007-07-25 00:24:17 +00002307
2308 // FIXME: handle stuff like:
2309 // void foo() { extern float X(); }
2310 // void bar() { X(); } <-- implicit decl for X in another scope.
2311
2312 // Set a Declarator for the implicit definition: int foo();
2313 const char *Dummy;
2314 DeclSpec DS;
2315 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2316 Error = Error; // Silence warning.
2317 assert(!Error && "Error setting up implicit decl!");
2318 Declarator D(DS, Declarator::BlockContext);
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00002319 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Chris Lattner4b009652007-07-25 00:24:17 +00002320 D.SetIdentifier(&II, Loc);
2321
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002322 // Insert this function into translation-unit scope.
2323
2324 DeclContext *PrevDC = CurContext;
2325 CurContext = Context.getTranslationUnitDecl();
2326
Steve Naroff9104f3c2008-04-04 14:32:09 +00002327 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002328 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002329 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002330
2331 CurContext = PrevDC;
2332
Steve Naroff9104f3c2008-04-04 14:32:09 +00002333 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002334}
2335
2336
Chris Lattner82bb4792007-11-14 06:34:38 +00002337TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00002338 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002339 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002340 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002341
2342 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002343 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2344 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002345 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00002346 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002347 if (D.getInvalidType())
2348 NewTD->setInvalidDecl();
2349 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002350}
2351
Steve Naroff0acc9c92007-09-15 18:49:24 +00002352/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002353/// former case, Name will be non-null. In the later case, Name will be null.
2354/// TagType indicates what kind of tag this is. TK indicates whether this is a
2355/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002356Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002357 SourceLocation KWLoc, const CXXScopeSpec &SS,
2358 IdentifierInfo *Name, SourceLocation NameLoc,
2359 AttributeList *Attr) {
Chris Lattner4b009652007-07-25 00:24:17 +00002360 // If this is a use of an existing tag, it must have a name.
2361 assert((Name != 0 || TK == TK_Definition) &&
2362 "Nameless record must be a definition!");
2363
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002364 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00002365 switch (TagType) {
2366 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002367 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2368 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2369 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2370 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002371 }
2372
Ted Kremenek46a837c2008-09-05 17:16:31 +00002373 // Two code paths: a new one for structs/unions/classes where we create
2374 // separate decls for forward declarations, and an old (eventually to
2375 // be removed) code path for enums.
2376 if (Kind != TagDecl::TK_enum)
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002377 return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr);
Ted Kremenek46a837c2008-09-05 17:16:31 +00002378
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002379 DeclContext *DC = CurContext;
2380 ScopedDecl *PrevDecl = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002381
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002382 if (Name && SS.isNotEmpty()) {
2383 // We have a nested-name tag ('struct foo::bar').
2384
2385 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002386 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002387 Name = 0;
2388 goto CreateNewDecl;
2389 }
2390
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002391 DC = static_cast<DeclContext*>(SS.getScopeRep());
2392 // Look-up name inside 'foo::'.
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002393 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2394
2395 // A tag 'foo::bar' must already exist.
2396 if (PrevDecl == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002397 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002398 Name = 0;
2399 goto CreateNewDecl;
2400 }
2401 } else {
2402 // If this is a named struct, check to see if there was a previous forward
2403 // declaration or definition.
2404 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2405 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2406 }
2407
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002408 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002409 // Maybe we will complain about the shadowed template parameter.
2410 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2411 // Just pretend that we didn't see the previous declaration.
2412 PrevDecl = 0;
2413 }
2414
Ted Kremenekd4434152008-09-02 21:26:19 +00002415 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002416 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2417 "unexpected Decl type");
2418 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002419 // If this is a use of a previous tag, or if the tag is already declared
2420 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002421 // rementions the tag), reuse the decl.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002422 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002423 // Make sure that this wasn't declared as an enum and now used as a
2424 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002425 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner65cae292008-11-19 08:23:25 +00002426 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002427 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002428 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002429 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002430 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002431 } else {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002432 // If this is a use or a forward declaration, we're good.
2433 if (TK != TK_Definition)
2434 return PrevDecl;
2435
2436 // Diagnose attempts to redefine a tag.
2437 if (PrevTagDecl->isDefinition()) {
Chris Lattner65cae292008-11-19 08:23:25 +00002438 Diag(NameLoc, diag::err_redefinition) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002439 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002440 // If this is a redefinition, recover by making this struct be
2441 // anonymous, which will make any later references get the previous
2442 // definition.
2443 Name = 0;
2444 } else {
2445 // Okay, this is definition of a previously declared or referenced
2446 // tag. Move the location of the decl to be the definition site.
2447 PrevDecl->setLocation(NameLoc);
2448 return PrevDecl;
2449 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002450 }
Chris Lattner4b009652007-07-25 00:24:17 +00002451 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002452 // If we get here, this is a definition of a new struct type in a nested
2453 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2454 // type.
2455 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002456 // PrevDecl is a namespace.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002457 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002458 // The tag name clashes with a namespace name, issue an error and
2459 // recover by making this tag be anonymous.
Chris Lattner65cae292008-11-19 08:23:25 +00002460 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002461 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002462 Name = 0;
2463 }
Chris Lattner4b009652007-07-25 00:24:17 +00002464 }
Chris Lattner4b009652007-07-25 00:24:17 +00002465 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002466
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002467 CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00002468
2469 // If there is an identifier, use the location of the identifier as the
2470 // location of the decl, otherwise use the location of the struct/union
2471 // keyword.
2472 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2473
2474 // Otherwise, if this is the first time we've seen this tag, create the decl.
2475 TagDecl *New;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002476 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00002477 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2478 // enum X { A, B, C } D; D should chain to X.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002479 New = EnumDecl::Create(Context, DC, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002480 // If this is an undefined enum, warn.
2481 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002482 } else {
2483 // struct/union/class
2484
Chris Lattner4b009652007-07-25 00:24:17 +00002485 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2486 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002487 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002488 // FIXME: Look for a way to use RecordDecl for simple structs.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002489 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002490 else
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002491 New = RecordDecl::Create(Context, Kind, DC, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002492 }
Chris Lattner4b009652007-07-25 00:24:17 +00002493
2494 // If this has an identifier, add it to the scope stack.
2495 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00002496 // The scope passed in may not be a decl scope. Zip up the scope tree until
2497 // we find one that is.
2498 while ((S->getFlags() & Scope::DeclScope) == 0)
2499 S = S->getParent();
2500
2501 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002502 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002503 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00002504
Chris Lattnerd7e83d82008-06-28 23:58:55 +00002505 if (Attr)
2506 ProcessDeclAttributeList(New, Attr);
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00002507
2508 // Set the lexical context. If the tag has a C++ scope specifier, the
2509 // lexical context will be different from the semantic context.
2510 New->setLexicalDeclContext(CurContext);
2511
Chris Lattner4b009652007-07-25 00:24:17 +00002512 return New;
2513}
2514
Ted Kremenek46a837c2008-09-05 17:16:31 +00002515/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2516/// the logic for enums, we create separate decls for forward declarations.
2517/// This is called by ActOnTag, but eventually will replace its logic.
2518Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002519 SourceLocation KWLoc, const CXXScopeSpec &SS,
2520 IdentifierInfo *Name, SourceLocation NameLoc,
2521 AttributeList *Attr) {
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002522 DeclContext *DC = CurContext;
2523 ScopedDecl *PrevDecl = 0;
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002524
2525 if (Name && SS.isNotEmpty()) {
2526 // We have a nested-name tag ('struct foo::bar').
2527
2528 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002529 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002530 Name = 0;
2531 goto CreateNewDecl;
2532 }
2533
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002534 DC = static_cast<DeclContext*>(SS.getScopeRep());
2535 // Look-up name inside 'foo::'.
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002536 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2537
2538 // A tag 'foo::bar' must already exist.
2539 if (PrevDecl == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002540 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002541 Name = 0;
2542 goto CreateNewDecl;
2543 }
2544 } else {
2545 // If this is a named struct, check to see if there was a previous forward
2546 // declaration or definition.
2547 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2548 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2549 }
Ted Kremenek46a837c2008-09-05 17:16:31 +00002550
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002551 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002552 // Maybe we will complain about the shadowed template parameter.
2553 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2554 // Just pretend that we didn't see the previous declaration.
2555 PrevDecl = 0;
2556 }
2557
Ted Kremenek46a837c2008-09-05 17:16:31 +00002558 if (PrevDecl) {
2559 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2560 "unexpected Decl type");
2561
2562 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2563 // If this is a use of a previous tag, or if the tag is already declared
2564 // in the same scope (so that the definition/declaration completes or
2565 // rementions the tag), reuse the decl.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002566 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002567 // Make sure that this wasn't declared as an enum and now used as a
2568 // struct or something similar.
2569 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner65cae292008-11-19 08:23:25 +00002570 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002571 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Ted Kremenek46a837c2008-09-05 17:16:31 +00002572 // Recover by making this an anonymous redefinition.
2573 Name = 0;
2574 PrevDecl = 0;
2575 } else {
2576 // If this is a use, return the original decl.
2577
2578 // FIXME: In the future, return a variant or some other clue
2579 // for the consumer of this Decl to know it doesn't own it.
2580 // For our current ASTs this shouldn't be a problem, but will
2581 // need to be changed with DeclGroups.
2582 if (TK == TK_Reference)
2583 return PrevDecl;
2584
2585 // The new decl is a definition?
2586 if (TK == TK_Definition) {
2587 // Diagnose attempts to redefine a tag.
2588 if (RecordDecl* DefRecord =
2589 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
Chris Lattner65cae292008-11-19 08:23:25 +00002590 Diag(NameLoc, diag::err_redefinition) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002591 Diag(DefRecord->getLocation(), diag::note_previous_definition);
Ted Kremenek46a837c2008-09-05 17:16:31 +00002592 // If this is a redefinition, recover by making this struct be
2593 // anonymous, which will make any later references get the previous
2594 // definition.
2595 Name = 0;
2596 PrevDecl = 0;
2597 }
2598 // Okay, this is definition of a previously declared or referenced
2599 // tag. We're going to create a new Decl.
2600 }
2601 }
2602 // If we get here we have (another) forward declaration. Just create
2603 // a new decl.
2604 }
2605 else {
2606 // If we get here, this is a definition of a new struct type in a nested
2607 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2608 // new decl/type. We set PrevDecl to NULL so that the Records
2609 // have distinct types.
2610 PrevDecl = 0;
2611 }
2612 } else {
2613 // PrevDecl is a namespace.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002614 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002615 // The tag name clashes with a namespace name, issue an error and
2616 // recover by making this tag be anonymous.
Chris Lattner65cae292008-11-19 08:23:25 +00002617 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002618 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Ted Kremenek46a837c2008-09-05 17:16:31 +00002619 Name = 0;
2620 }
2621 }
2622 }
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002623
2624 CreateNewDecl:
2625
Ted Kremenek46a837c2008-09-05 17:16:31 +00002626 // If there is an identifier, use the location of the identifier as the
2627 // location of the decl, otherwise use the location of the struct/union
2628 // keyword.
2629 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2630
2631 // Otherwise, if this is the first time we've seen this tag, create the decl.
2632 TagDecl *New;
2633
2634 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2635 // struct X { int A; } D; D should chain to X.
2636 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002637 // FIXME: Look for a way to use RecordDecl for simple structs.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002638 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek46a837c2008-09-05 17:16:31 +00002639 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2640 else
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002641 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek46a837c2008-09-05 17:16:31 +00002642 dyn_cast_or_null<RecordDecl>(PrevDecl));
2643
2644 // If this has an identifier, add it to the scope stack.
2645 if ((TK == TK_Definition || !PrevDecl) && Name) {
2646 // The scope passed in may not be a decl scope. Zip up the scope tree until
2647 // we find one that is.
2648 while ((S->getFlags() & Scope::DeclScope) == 0)
2649 S = S->getParent();
2650
2651 // Add it to the decl chain.
2652 PushOnScopeChains(New, S);
2653 }
Daniel Dunbar2cb762f2008-10-16 02:34:03 +00002654
2655 // Handle #pragma pack: if the #pragma pack stack has non-default
2656 // alignment, make up a packed attribute for this decl. These
2657 // attributes are checked when the ASTContext lays out the
2658 // structure.
2659 //
2660 // It is important for implementing the correct semantics that this
2661 // happen here (in act on tag decl). The #pragma pack stack is
2662 // maintained as a result of parser callbacks which can occur at
2663 // many points during the parsing of a struct declaration (because
2664 // the #pragma tokens are effectively skipped over during the
2665 // parsing of the struct).
2666 if (unsigned Alignment = PackContext.getAlignment())
2667 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek46a837c2008-09-05 17:16:31 +00002668
2669 if (Attr)
2670 ProcessDeclAttributeList(New, Attr);
2671
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00002672 // Set the lexical context. If the tag has a C++ scope specifier, the
2673 // lexical context will be different from the semantic context.
2674 New->setLexicalDeclContext(CurContext);
2675
Ted Kremenek46a837c2008-09-05 17:16:31 +00002676 return New;
2677}
2678
2679
Chris Lattner1bf58f62008-06-21 19:39:06 +00002680/// Collect the instance variables declared in an Objective-C object. Used in
2681/// the creation of structures from objects using the @defs directive.
Douglas Gregor8acb7272008-12-11 16:49:14 +00002682static void CollectIvars(ObjCInterfaceDecl *Class, RecordDecl *Record,
2683 ASTContext& Ctx,
Chris Lattnere705e5e2008-07-21 22:17:28 +00002684 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00002685 if (Class->getSuperClass())
Douglas Gregor8acb7272008-12-11 16:49:14 +00002686 CollectIvars(Class->getSuperClass(), Record, Ctx, ivars);
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002687
2688 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremenek40e70e72008-09-03 18:03:35 +00002689 for (ObjCInterfaceDecl::ivar_iterator
2690 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2691
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002692 ObjCIvarDecl* ID = *I;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002693 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, Record,
2694 ID->getLocation(),
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002695 ID->getIdentifier(),
2696 ID->getType(),
2697 ID->getBitWidth()));
2698 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002699}
2700
2701/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2702/// instance variables of ClassName into Decls.
Douglas Gregor8acb7272008-12-11 16:49:14 +00002703void Sema::ActOnDefs(Scope *S, DeclTy *TagD, SourceLocation DeclStart,
Chris Lattner1bf58f62008-06-21 19:39:06 +00002704 IdentifierInfo *ClassName,
Chris Lattnere705e5e2008-07-21 22:17:28 +00002705 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00002706 // Check that ClassName is a valid class
2707 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2708 if (!Class) {
Chris Lattner65cae292008-11-19 08:23:25 +00002709 Diag(DeclStart, diag::err_undef_interface) << ClassName;
Chris Lattner1bf58f62008-06-21 19:39:06 +00002710 return;
2711 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002712 // Collect the instance variables
Douglas Gregor8acb7272008-12-11 16:49:14 +00002713 CollectIvars(Class, dyn_cast<RecordDecl>((Decl*)TagD), Context, Decls);
2714
2715 // Introduce all of these fields into the appropriate scope.
2716 for (llvm::SmallVectorImpl<DeclTy*>::iterator D = Decls.begin();
2717 D != Decls.end(); ++D) {
2718 FieldDecl *FD = cast<FieldDecl>((Decl*)*D);
2719 if (getLangOptions().CPlusPlus)
2720 PushOnScopeChains(cast<FieldDecl>(FD), S);
2721 else if (RecordDecl *Record = dyn_cast<RecordDecl>((Decl*)TagD))
2722 Record->addDecl(Context, FD);
2723 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002724}
2725
Chris Lattnera73e2202008-11-12 21:17:48 +00002726/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2727/// types into constant array types in certain situations which would otherwise
2728/// be errors (for GCC compatibility).
2729static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2730 ASTContext &Context) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002731 // This method tries to turn a variable array into a constant
2732 // array even when the size isn't an ICE. This is necessary
2733 // for compatibility with code that depends on gcc's buggy
2734 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002735 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2736 if (!VLATy) return QualType();
2737
2738 APValue Result;
2739 if (!VLATy->getSizeExpr() ||
Chris Lattneref069662008-11-16 21:24:15 +00002740 !VLATy->getSizeExpr()->Evaluate(Result, Context))
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002741 return QualType();
2742
2743 assert(Result.isInt() && "Size expressions must be integers!");
2744 llvm::APSInt &Res = Result.getInt();
2745 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2746 return Context.getConstantArrayType(VLATy->getElementType(),
2747 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002748 return QualType();
2749}
2750
Anders Carlsson108229a2008-12-06 20:33:04 +00002751bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
2752 QualType FieldTy, const Expr *BitWidth)
2753{
2754 // FIXME: 6.7.2.1p4 - verify the field type.
2755
2756 llvm::APSInt Value;
2757 if (VerifyIntegerConstantExpression(BitWidth, &Value))
2758 return true;
2759
2760 if (Value.isNegative()) {
2761 Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
2762 return true;
2763 }
2764
2765 uint64_t TypeSize = Context.getTypeSize(FieldTy);
2766 // FIXME: We won't need the 0 size once we check that the field type is valid.
2767 if (TypeSize && Value.getZExtValue() > TypeSize) {
2768 Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) <<
2769 FieldName << (unsigned)TypeSize;
2770 return true;
2771 }
2772
2773 return false;
2774}
2775
Steve Naroff0acc9c92007-09-15 18:49:24 +00002776/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00002777/// to create a FieldDecl object for it.
Douglas Gregor8acb7272008-12-11 16:49:14 +00002778Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Chris Lattner4b009652007-07-25 00:24:17 +00002779 SourceLocation DeclStart,
2780 Declarator &D, ExprTy *BitfieldWidth) {
2781 IdentifierInfo *II = D.getIdentifier();
2782 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00002783 SourceLocation Loc = DeclStart;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002784 RecordDecl *Record = (RecordDecl *)TagD;
Chris Lattner4b009652007-07-25 00:24:17 +00002785 if (II) Loc = D.getIdentifierLoc();
2786
2787 // FIXME: Unnamed fields can be handled in various different ways, for
2788 // example, unnamed unions inject all members into the struct namespace!
Chris Lattner4b009652007-07-25 00:24:17 +00002789
Chris Lattner4b009652007-07-25 00:24:17 +00002790 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002791 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2792 bool InvalidDecl = false;
Anders Carlsson108229a2008-12-06 20:33:04 +00002793
Chris Lattner4b009652007-07-25 00:24:17 +00002794 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2795 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00002796 if (T->isVariablyModifiedType()) {
Chris Lattnera73e2202008-11-12 21:17:48 +00002797 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002798 if (!FixedTy.isNull()) {
Chris Lattner86be8572008-11-13 18:49:38 +00002799 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002800 T = FixedTy;
2801 } else {
Chris Lattner86be8572008-11-13 18:49:38 +00002802 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner2a884752008-11-12 19:45:49 +00002803 T = Context.IntTy;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002804 InvalidDecl = true;
2805 }
Chris Lattner4b009652007-07-25 00:24:17 +00002806 }
Anders Carlsson108229a2008-12-06 20:33:04 +00002807
2808 if (BitWidth) {
2809 if (VerifyBitField(Loc, II, T, BitWidth))
2810 InvalidDecl = true;
2811 } else {
2812 // Not a bitfield.
2813
2814 // validate II.
2815
2816 }
2817
Chris Lattner4b009652007-07-25 00:24:17 +00002818 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002819 FieldDecl *NewFD;
2820
Douglas Gregor8acb7272008-12-11 16:49:14 +00002821 // FIXME: We don't want CurContext for C, do we? No, we'll need some
2822 // other way to determine the current RecordDecl.
2823 NewFD = FieldDecl::Create(Context, Record,
2824 Loc, II, T, BitWidth,
2825 D.getDeclSpec().getStorageClassSpec() ==
2826 DeclSpec::SCS_mutable,
2827 /*PrevDecl=*/0);
2828
Chris Lattner9b384ca2008-06-29 00:02:00 +00002829 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002830
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002831 if (D.getInvalidType() || InvalidDecl)
2832 NewFD->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002833
2834 if (II && getLangOptions().CPlusPlus)
2835 PushOnScopeChains(NewFD, S);
2836 else
2837 Record->addDecl(Context, NewFD);
2838
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002839 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00002840}
2841
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002842/// TranslateIvarVisibility - Translate visibility from a token ID to an
2843/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00002844static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002845TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00002846 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00002847 default: assert(0 && "Unknown visitibility kind");
2848 case tok::objc_private: return ObjCIvarDecl::Private;
2849 case tok::objc_public: return ObjCIvarDecl::Public;
2850 case tok::objc_protected: return ObjCIvarDecl::Protected;
2851 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00002852 }
2853}
2854
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002855/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2856/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002857Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002858 SourceLocation DeclStart,
2859 Declarator &D, ExprTy *BitfieldWidth,
2860 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002861 IdentifierInfo *II = D.getIdentifier();
2862 Expr *BitWidth = (Expr*)BitfieldWidth;
2863 SourceLocation Loc = DeclStart;
2864 if (II) Loc = D.getIdentifierLoc();
2865
2866 // FIXME: Unnamed fields can be handled in various different ways, for
2867 // example, unnamed unions inject all members into the struct namespace!
2868
Anders Carlsson108229a2008-12-06 20:33:04 +00002869 QualType T = GetTypeForDeclarator(D, S);
2870 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2871 bool InvalidDecl = false;
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002872
2873 if (BitWidth) {
2874 // TODO: Validate.
2875 //printf("WARNING: BITFIELDS IGNORED!\n");
2876
2877 // 6.7.2.1p3
2878 // 6.7.2.1p4
2879
2880 } else {
2881 // Not a bitfield.
2882
2883 // validate II.
2884
2885 }
2886
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002887 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2888 // than a variably modified type.
2889 if (T->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00002890 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002891 InvalidDecl = true;
2892 }
2893
Ted Kremenek173dd312008-07-23 18:04:17 +00002894 // Get the visibility (access control) for this ivar.
2895 ObjCIvarDecl::AccessControl ac =
2896 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2897 : ObjCIvarDecl::None;
2898
2899 // Construct the decl.
2900 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00002901 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002902
Ted Kremenek173dd312008-07-23 18:04:17 +00002903 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00002904 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002905
2906 if (D.getInvalidType() || InvalidDecl)
2907 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00002908
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002909 return NewID;
2910}
2911
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00002912void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002913 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00002914 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00002915 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00002916 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002917 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2918 assert(EnclosingDecl && "missing record or interface decl");
2919 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2920
Ted Kremenek46a837c2008-09-05 17:16:31 +00002921 if (Record)
2922 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2923 // Diagnose code like:
2924 // struct S { struct S {} X; };
2925 // We discover this when we complete the outer S. Reject and ignore the
2926 // outer S.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002927 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
Chris Lattner271d4c22008-11-24 05:29:24 +00002928 << DefRecord->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00002929 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek46a837c2008-09-05 17:16:31 +00002930 Record->setInvalidDecl();
2931 return;
2932 }
2933
Chris Lattner4b009652007-07-25 00:24:17 +00002934 // Verify that all the fields are okay.
2935 unsigned NumNamedMembers = 0;
2936 llvm::SmallVector<FieldDecl*, 32> RecFields;
2937 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00002938
Chris Lattner4b009652007-07-25 00:24:17 +00002939 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002940
Steve Naroff9bb759f2007-09-14 22:20:54 +00002941 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2942 assert(FD && "missing field decl");
2943
2944 // Remember all fields.
2945 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00002946
2947 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00002948 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00002949
Chris Lattner4b009652007-07-25 00:24:17 +00002950 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00002951 if (FDTy->isFunctionType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002952 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattner271d4c22008-11-24 05:29:24 +00002953 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00002954 FD->setInvalidDecl();
2955 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002956 continue;
2957 }
Chris Lattner4b009652007-07-25 00:24:17 +00002958 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2959 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002960 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattner271d4c22008-11-24 05:29:24 +00002961 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00002962 FD->setInvalidDecl();
2963 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002964 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002965 }
Chris Lattner4b009652007-07-25 00:24:17 +00002966 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002967 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002968 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner271d4c22008-11-24 05:29:24 +00002969 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00002970 FD->setInvalidDecl();
2971 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002972 continue;
2973 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002974 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002975 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00002976 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00002977 FD->setInvalidDecl();
2978 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002979 continue;
2980 }
Chris Lattner4b009652007-07-25 00:24:17 +00002981 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002982 if (Record)
2983 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002984 }
Chris Lattner4b009652007-07-25 00:24:17 +00002985 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2986 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002987 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002988 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2989 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002990 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002991 Record->setHasFlexibleArrayMember(true);
2992 } else {
2993 // If this is a struct/class and this is not the last element, reject
2994 // it. Note that GCC supports variable sized arrays in the middle of
2995 // structures.
2996 if (i != NumFields-1) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002997 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00002998 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00002999 FD->setInvalidDecl();
3000 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003001 continue;
3002 }
Chris Lattner4b009652007-07-25 00:24:17 +00003003 // We support flexible arrays at the end of structs in other structs
3004 // as an extension.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003005 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003006 << FD->getDeclName();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003007 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003008 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003009 }
3010 }
3011 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003012 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00003013 if (FDTy->isObjCInterfaceType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003014 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattnerb1753422008-11-23 21:45:46 +00003015 << FD->getDeclName();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003016 FD->setInvalidDecl();
3017 EnclosingDecl->setInvalidDecl();
3018 continue;
3019 }
Chris Lattner4b009652007-07-25 00:24:17 +00003020 // Keep track of the number of named members.
3021 if (IdentifierInfo *II = FD->getIdentifier()) {
3022 // Detect duplicate member names.
3023 if (!FieldIDs.insert(II)) {
Chris Lattner65cae292008-11-19 08:23:25 +00003024 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Chris Lattner4b009652007-07-25 00:24:17 +00003025 // Find the previous decl.
3026 SourceLocation PrevLoc;
Chris Lattner504c5432008-10-12 00:28:42 +00003027 for (unsigned i = 0; ; ++i) {
3028 assert(i != RecFields.size() && "Didn't find previous def!");
Chris Lattner4b009652007-07-25 00:24:17 +00003029 if (RecFields[i]->getIdentifier() == II) {
3030 PrevLoc = RecFields[i]->getLocation();
3031 break;
3032 }
3033 }
Chris Lattner1336cab2008-11-23 23:12:31 +00003034 Diag(PrevLoc, diag::note_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003035 FD->setInvalidDecl();
3036 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003037 continue;
3038 }
3039 ++NumNamedMembers;
3040 }
Chris Lattner4b009652007-07-25 00:24:17 +00003041 }
3042
Chris Lattner4b009652007-07-25 00:24:17 +00003043 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00003044 if (Record) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003045 Record->completeDefinition(Context);
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +00003046 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
3047 // Sema::ActOnFinishCXXClassDef.
3048 if (!isa<CXXRecordDecl>(Record))
3049 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003050 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003051 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
3052 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
3053 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
3054 else if (ObjCImplementationDecl *IMPDecl =
3055 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003056 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3057 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00003058 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00003059 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00003060 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00003061
3062 if (Attr)
3063 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00003064}
3065
Steve Naroff0acc9c92007-09-15 18:49:24 +00003066Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00003067 DeclTy *lastEnumConst,
3068 SourceLocation IdLoc, IdentifierInfo *Id,
3069 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00003070 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003071 EnumConstantDecl *LastEnumConst =
3072 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3073 Expr *Val = static_cast<Expr*>(val);
3074
Chris Lattnera7549902007-08-26 06:24:45 +00003075 // The scope passed in may not be a decl scope. Zip up the scope tree until
3076 // we find one that is.
3077 while ((S->getFlags() & Scope::DeclScope) == 0)
3078 S = S->getParent();
3079
Chris Lattner4b009652007-07-25 00:24:17 +00003080 // Verify that there isn't already something declared with this name in this
3081 // scope.
Douglas Gregordd861062008-12-05 18:15:24 +00003082 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregor2715a1f2008-12-08 18:40:42 +00003083 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00003084 // Maybe we will complain about the shadowed template parameter.
3085 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3086 // Just pretend that we didn't see the previous declaration.
3087 PrevDecl = 0;
3088 }
3089
3090 if (PrevDecl) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00003091 // When in C++, we may get a TagDecl with the same name; in this case the
3092 // enum constant will 'hide' the tag.
3093 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3094 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00003095 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003096 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner65cae292008-11-19 08:23:25 +00003097 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner4b009652007-07-25 00:24:17 +00003098 else
Chris Lattner65cae292008-11-19 08:23:25 +00003099 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner1336cab2008-11-23 23:12:31 +00003100 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003101 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00003102 return 0;
3103 }
3104 }
3105
3106 llvm::APSInt EnumVal(32);
3107 QualType EltTy;
3108 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00003109 // Make sure to promote the operand type to int.
3110 UsualUnaryConversions(Val);
3111
Chris Lattner4b009652007-07-25 00:24:17 +00003112 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3113 SourceLocation ExpLoc;
Anders Carlsson5374c6b2008-12-05 16:33:57 +00003114 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003115 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00003116 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00003117 } else {
3118 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003119 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00003120 }
3121
3122 if (!Val) {
3123 if (LastEnumConst) {
3124 // Assign the last value + 1.
3125 EnumVal = LastEnumConst->getInitVal();
3126 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00003127
3128 // Check for overflow on increment.
3129 if (EnumVal < LastEnumConst->getInitVal())
3130 Diag(IdLoc, diag::warn_enum_value_overflow);
3131
Chris Lattnere7f53a42007-08-27 17:37:24 +00003132 EltTy = LastEnumConst->getType();
3133 } else {
3134 // First value, set to zero.
3135 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003136 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00003137 }
Chris Lattner4b009652007-07-25 00:24:17 +00003138 }
3139
Chris Lattnere4650482008-03-15 06:12:44 +00003140 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00003141 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3142 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00003143 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00003144
3145 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00003146 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00003147 return New;
3148}
3149
Steve Naroffb0726b82008-08-07 14:08:16 +00003150// FIXME: For consistency with ActOnFields(), we should have the parser
3151// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00003152void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00003153 DeclTy **Elements, unsigned NumElements) {
3154 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Chris Lattner4b009652007-07-25 00:24:17 +00003155
Steve Naroffb0726b82008-08-07 14:08:16 +00003156 if (Enum && Enum->isDefinition()) {
3157 // Diagnose code like:
3158 // enum e0 {
3159 // E0 = sizeof(enum e0 { E1 })
3160 // };
Chris Lattner271d4c22008-11-24 05:29:24 +00003161 Diag(Enum->getLocation(), diag::err_nested_redefinition)
3162 << Enum->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00003163 Diag(EnumLoc, diag::note_previous_definition);
Steve Naroffb0726b82008-08-07 14:08:16 +00003164 Enum->setInvalidDecl();
3165 return;
3166 }
Chris Lattner435c3fd2007-08-28 05:10:31 +00003167 // TODO: If the result value doesn't fit in an int, it must be a long or long
3168 // long value. ISO C does not support this, but GCC does as an extension,
3169 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00003170 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00003171
Chris Lattner206754a2007-08-28 06:15:15 +00003172 // Verify that all the values are okay, compute the size of the values, and
3173 // reverse the list.
3174 unsigned NumNegativeBits = 0;
3175 unsigned NumPositiveBits = 0;
3176
3177 // Keep track of whether all elements have type int.
3178 bool AllElementsInt = true;
3179
Chris Lattner4b009652007-07-25 00:24:17 +00003180 EnumConstantDecl *EltList = 0;
3181 for (unsigned i = 0; i != NumElements; ++i) {
3182 EnumConstantDecl *ECD =
3183 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3184 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003185
3186 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003187 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003188 assert(InitVal.getBitWidth() >= IntWidth &&
3189 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00003190 if (InitVal.getBitWidth() > IntWidth) {
3191 llvm::APSInt V(InitVal);
3192 V.trunc(IntWidth);
3193 V.extend(InitVal.getBitWidth());
3194 if (V != InitVal)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003195 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3196 << InitVal.toString(10);
Chris Lattnercb33ae12007-08-28 05:27:00 +00003197 }
Chris Lattner206754a2007-08-28 06:15:15 +00003198
3199 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003200 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00003201 NumPositiveBits = std::max(NumPositiveBits,
3202 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00003203 else
Chris Lattneraff63f02008-01-14 21:47:29 +00003204 NumNegativeBits = std::max(NumNegativeBits,
3205 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00003206
Chris Lattner206754a2007-08-28 06:15:15 +00003207 // Keep track of whether every enum element has type int (very commmon).
3208 if (AllElementsInt)
3209 AllElementsInt = ECD->getType() == Context.IntTy;
3210
Chris Lattner4b009652007-07-25 00:24:17 +00003211 ECD->setNextDeclarator(EltList);
3212 EltList = ECD;
3213 }
3214
Chris Lattner206754a2007-08-28 06:15:15 +00003215 // Figure out the type that should be used for this enum.
3216 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3217 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003218 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00003219
3220 if (NumNegativeBits) {
3221 // If there is a negative value, figure out the smallest integer type (of
3222 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003223 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003224 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003225 BestWidth = IntWidth;
3226 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003227 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003228
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003229 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003230 BestType = Context.LongTy;
3231 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003232 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003233
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003234 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003235 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3236 BestType = Context.LongLongTy;
3237 }
3238 }
3239 } else {
3240 // If there is no negative value, figure out which of uint, ulong, ulonglong
3241 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003242 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003243 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003244 BestWidth = IntWidth;
3245 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00003246 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00003247 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003248 } else {
3249 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003250 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00003251 "How could an initializer get larger than ULL?");
3252 BestType = Context.UnsignedLongLongTy;
3253 }
3254 }
3255
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003256 // Loop over all of the enumerator constants, changing their types to match
3257 // the type of the enum if needed.
3258 for (unsigned i = 0; i != NumElements; ++i) {
3259 EnumConstantDecl *ECD =
3260 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3261 if (!ECD) continue; // Already issued a diagnostic.
3262
3263 // Standard C says the enumerators have int type, but we allow, as an
3264 // extension, the enumerators to be larger than int size. If each
3265 // enumerator value fits in an int, type it as an int, otherwise type it the
3266 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3267 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003268 if (ECD->getType() == Context.IntTy) {
3269 // Make sure the init value is signed.
3270 llvm::APSInt IV = ECD->getInitVal();
3271 IV.setIsSigned(true);
3272 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003273 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003274 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003275
3276 // Determine whether the value fits into an int.
3277 llvm::APSInt InitVal = ECD->getInitVal();
3278 bool FitsInInt;
3279 if (InitVal.isUnsigned() || !InitVal.isNegative())
3280 FitsInInt = InitVal.getActiveBits() < IntWidth;
3281 else
3282 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3283
3284 // If it fits into an integer type, force it. Otherwise force it to match
3285 // the enum decl type.
3286 QualType NewTy;
3287 unsigned NewWidth;
3288 bool NewSign;
3289 if (FitsInInt) {
3290 NewTy = Context.IntTy;
3291 NewWidth = IntWidth;
3292 NewSign = true;
3293 } else if (ECD->getType() == BestType) {
3294 // Already the right type!
3295 continue;
3296 } else {
3297 NewTy = BestType;
3298 NewWidth = BestWidth;
3299 NewSign = BestType->isSignedIntegerType();
3300 }
3301
3302 // Adjust the APSInt value.
3303 InitVal.extOrTrunc(NewWidth);
3304 InitVal.setIsSigned(NewSign);
3305 ECD->setInitVal(InitVal);
3306
3307 // Adjust the Expr initializer and type.
Douglas Gregor70d26122008-11-12 17:17:38 +00003308 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3309 /*isLvalue=*/false));
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003310 ECD->setType(NewTy);
3311 }
Chris Lattner206754a2007-08-28 06:15:15 +00003312
Douglas Gregor8acb7272008-12-11 16:49:14 +00003313 Enum->completeDefinition(Context, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003314 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003315}
3316
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003317Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3318 ExprTy *expr) {
3319 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
3320
Chris Lattner81db64a2008-03-16 00:16:02 +00003321 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003322}
3323
Chris Lattner806a5f52008-01-12 07:05:38 +00003324Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00003325 SourceLocation LBrace,
3326 SourceLocation RBrace,
3327 const char *Lang,
3328 unsigned StrSize,
3329 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00003330 LinkageSpecDecl::LanguageIDs Language;
3331 Decl *dcl = static_cast<Decl *>(D);
3332 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3333 Language = LinkageSpecDecl::lang_c;
3334 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3335 Language = LinkageSpecDecl::lang_cxx;
3336 else {
3337 Diag(Loc, diag::err_bad_language);
3338 return 0;
3339 }
3340
3341 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00003342 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00003343}
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003344
3345void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3346 ExprTy *alignment, SourceLocation PragmaLoc,
3347 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3348 Expr *Alignment = static_cast<Expr *>(alignment);
3349
3350 // If specified then alignment must be a "small" power of two.
3351 unsigned AlignmentVal = 0;
3352 if (Alignment) {
3353 llvm::APSInt Val;
3354 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3355 !Val.isPowerOf2() ||
3356 Val.getZExtValue() > 16) {
3357 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3358 delete Alignment;
3359 return; // Ignore
3360 }
3361
3362 AlignmentVal = (unsigned) Val.getZExtValue();
3363 }
3364
3365 switch (Kind) {
3366 case Action::PPK_Default: // pack([n])
3367 PackContext.setAlignment(AlignmentVal);
3368 break;
3369
3370 case Action::PPK_Show: // pack(show)
3371 // Show the current alignment, making sure to show the right value
3372 // for the default.
3373 AlignmentVal = PackContext.getAlignment();
3374 // FIXME: This should come from the target.
3375 if (AlignmentVal == 0)
3376 AlignmentVal = 8;
Chris Lattnera5cc1882008-11-19 07:25:44 +00003377 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003378 break;
3379
3380 case Action::PPK_Push: // pack(push [, id] [, [n])
3381 PackContext.push(Name);
3382 // Set the new alignment if specified.
3383 if (Alignment)
3384 PackContext.setAlignment(AlignmentVal);
3385 break;
3386
3387 case Action::PPK_Pop: // pack(pop [, id] [, n])
3388 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3389 // "#pragma pack(pop, identifier, n) is undefined"
3390 if (Alignment && Name)
3391 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3392
3393 // Do the pop.
3394 if (!PackContext.pop(Name)) {
3395 // If a name was specified then failure indicates the name
3396 // wasn't found. Otherwise failure indicates the stack was
3397 // empty.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003398 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3399 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003400
3401 // FIXME: Warn about popping named records as MSVC does.
3402 } else {
3403 // Pop succeeded, set the new alignment if specified.
3404 if (Alignment)
3405 PackContext.setAlignment(AlignmentVal);
3406 }
3407 break;
3408
3409 default:
3410 assert(0 && "Invalid #pragma pack kind.");
3411 }
3412}
3413
3414bool PragmaPackStack::pop(IdentifierInfo *Name) {
3415 if (Stack.empty())
3416 return false;
3417
3418 // If name is empty just pop top.
3419 if (!Name) {
3420 Alignment = Stack.back().first;
3421 Stack.pop_back();
3422 return true;
3423 }
3424
3425 // Otherwise, find the named record.
3426 for (unsigned i = Stack.size(); i != 0; ) {
3427 --i;
Daniel Dunbarc13c54c2008-11-19 10:32:38 +00003428 if (Stack[i].second == Name) {
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003429 // Found it, pop up to and including this record.
3430 Alignment = Stack[i].first;
3431 Stack.erase(Stack.begin() + i, Stack.end());
3432 return true;
3433 }
3434 }
3435
3436 return false;
3437}