blob: d6d9845af79662dbd78778ca4ed2509bead90cf9 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
28using namespace clang;
29
Douglas Gregor2def4832008-11-17 20:34:05 +000030Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000031 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-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 Naroffb327ce02008-04-02 14:35:35 +000039
Douglas Gregor2ce52f32008-04-13 21:07:44 +000040 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
41 isa<ObjCInterfaceDecl>(IIDecl) ||
42 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000043 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000044 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000045}
46
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000047DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000048 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000049 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000050 if (MD->isOutOfLineDefinition())
51 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000052
53 // A C++ inline method is parsed *after* the topmost class it was declared in
54 // is fully parsed (it's "complete").
55 // The parsing of a C++ inline method happens at the declaration context of
56 // the topmost (non-nested) class it is declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000057 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
58 DC = MD->getParent();
59 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
60 DC = RD;
61
62 // Return the declaration context of the topmost class the inline method is
63 // declared in.
64 return DC;
65 }
66
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000067 if (isa<ObjCMethodDecl>(DC))
68 return Context.getTranslationUnitDecl();
69
70 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
71 return SD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000072
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000073 return DC->getParent();
74}
75
Chris Lattner9fdf9c62008-04-22 18:39:57 +000076void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000077 assert(getContainingDC(DC) == CurContext &&
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000078 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000079 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000080}
81
Chris Lattnerb048c982008-04-06 04:47:34 +000082void Sema::PopDeclContext() {
83 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000084 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000085}
86
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000087/// Add this decl to the scope shadowed decl chains.
88void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000089 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000090
91 // C++ [basic.scope]p4:
92 // -- exactly one declaration shall declare a class name or
93 // enumeration name that is not a typedef name and the other
94 // declarations shall all refer to the same object or
95 // enumerator, or all refer to functions and function templates;
96 // in this case the class name or enumeration name is hidden.
97 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
98 // We are pushing the name of a tag (enum or class).
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +000099 IdentifierResolver::iterator
100 I = IdResolver.begin(TD->getIdentifier(),
101 TD->getDeclContext(), false/*LookInParentCtx*/);
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000102 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000103 // There is already a declaration with the same name in the same
104 // scope. It must be found before we find the new declaration,
105 // so swap the order on the shadowed declaration chain.
106
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000107 IdResolver.AddShadowedDecl(TD, *I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000108 return;
109 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000110 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
111 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000112 // We are pushing the name of a function, which might be an
113 // overloaded name.
114 IdentifierResolver::iterator
Douglas Gregor2def4832008-11-17 20:34:05 +0000115 I = IdResolver.begin(FD->getDeclName(),
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000116 FD->getDeclContext(), false/*LookInParentCtx*/);
117 if (I != IdResolver.end() &&
118 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
119 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
120 // There is already a declaration with the same name in the same
121 // scope. It must be a function or an overloaded function.
122 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
123 if (!Ovl) {
124 // We haven't yet overloaded this function. Take the existing
125 // FunctionDecl and put it into an OverloadedFunctionDecl.
126 Ovl = OverloadedFunctionDecl::Create(Context,
127 FD->getDeclContext(),
Douglas Gregor2def4832008-11-17 20:34:05 +0000128 FD->getDeclName());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000129 Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
130
131 // Remove the name binding to the existing FunctionDecl...
132 IdResolver.RemoveDecl(*I);
133
134 // ... and put the OverloadedFunctionDecl in its place.
135 IdResolver.AddDecl(Ovl);
136 }
137
138 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
139 // to its list of overloads.
140 Ovl->addOverload(FD);
141
142 return;
143 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000144 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000145
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000146 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000147}
148
Steve Naroffb216c882007-10-09 22:01:59 +0000149void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000150 if (S->decl_empty()) return;
151 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000152
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
154 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000155 Decl *TmpD = static_cast<Decl*>(*I);
156 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000157
158 if (isa<CXXFieldDecl>(TmpD)) continue;
159
160 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
161 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000162
Reid Spencer5f016e22007-07-11 17:01:13 +0000163 IdentifierInfo *II = D->getIdentifier();
164 if (!II) continue;
165
Ted Kremeneka89d1972008-09-03 18:03:35 +0000166 // We only want to remove the decls from the identifier decl chains for
167 // local scopes, when inside a function/method.
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000168 if (S->getFnParent() != 0)
169 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000170
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000171 // Chain this decl to the containing DeclContext.
172 D->setNext(CurContext->getDeclChain());
173 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000174 }
175}
176
Steve Naroffe8043c32008-04-01 23:04:06 +0000177/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
178/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000179ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000180 // The third "scope" argument is 0 since we aren't enabling lazy built-in
181 // creation from this context.
182 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000183
Steve Naroffb327ce02008-04-02 14:35:35 +0000184 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000185}
186
Steve Naroffe8043c32008-04-01 23:04:06 +0000187/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000188/// namespace.
Douglas Gregor2def4832008-11-17 20:34:05 +0000189Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000190 const DeclContext *LookupCtx,
191 bool enableLazyBuiltinCreation) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000192 if (!Name) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000193 unsigned NS = NSI;
194 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
195 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000196
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000197 IdentifierResolver::iterator
Douglas Gregor2def4832008-11-17 20:34:05 +0000198 I = LookupCtx ? IdResolver.begin(Name, LookupCtx, false/*LookInParentCtx*/)
199 : IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/);
Reid Spencer5f016e22007-07-11 17:01:13 +0000200 // Scan up the scope chain looking for a decl that matches this identifier
201 // that is in the appropriate namespace. This search should not take long, as
202 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000203 for (; I != IdResolver.end(); ++I)
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000204 if ((*I)->getIdentifierNamespace() & NS)
205 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000206
Reid Spencer5f016e22007-07-11 17:01:13 +0000207 // If we didn't find a use of this identifier, and if the identifier
208 // corresponds to a compiler builtin, create the decl object for the builtin
209 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000210 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000211 IdentifierInfo *II = Name.getAsIdentifierInfo();
212 if (enableLazyBuiltinCreation && II &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000213 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000214 // If this is a builtin on this (or all) targets, create the decl.
215 if (unsigned BuiltinID = II->getBuiltinID())
216 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
217 }
Douglas Gregor2def4832008-11-17 20:34:05 +0000218 if (getLangOptions().ObjC1 && II) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000219 // @interface and @compatibility_alias introduce typedef-like names.
220 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000221 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000222 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000223 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
224 if (IDI != ObjCInterfaceDecls.end())
225 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000226 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
227 if (I != ObjCAliasDecls.end())
228 return I->second->getClassInterface();
229 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000230 }
231 return 0;
232}
233
Chris Lattner95e2c712008-05-05 22:18:14 +0000234void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000235 if (!Context.getBuiltinVaListType().isNull())
236 return;
237
238 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000239 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000240 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000241 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
242}
243
Reid Spencer5f016e22007-07-11 17:01:13 +0000244/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
245/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000246ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
247 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 Builtin::ID BID = (Builtin::ID)bid;
249
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000250 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000251 InitBuiltinVaListType();
252
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000253 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000254 FunctionDecl *New = FunctionDecl::Create(Context,
255 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000256 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000257 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000258
Chris Lattner95e2c712008-05-05 22:18:14 +0000259 // Create Decl objects for each parameter, adding them to the
260 // FunctionDecl.
261 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
262 llvm::SmallVector<ParmVarDecl*, 16> Params;
263 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
264 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
265 FT->getArgType(i), VarDecl::None, 0,
266 0));
267 New->setParams(&Params[0], Params.size());
268 }
269
270
271
Chris Lattner7f925cc2008-04-11 07:00:53 +0000272 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000273 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 return New;
275}
276
Sebastian Redlc42e1182008-11-11 11:37:55 +0000277/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
278/// everything from the standard library is defined.
279NamespaceDecl *Sema::GetStdNamespace() {
280 if (!StdNamespace) {
281 DeclContext *Global = Context.getTranslationUnitDecl();
282 Decl *Std = LookupDecl(Ident_StdNs, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
283 0, Global, /*enableLazyBuiltinCreation=*/false);
284 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
285 }
286 return StdNamespace;
287}
288
Reid Spencer5f016e22007-07-11 17:01:13 +0000289/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
290/// and scope as a previous declaration 'Old'. Figure out how to resolve this
291/// situation, merging decls or emitting diagnostics as appropriate.
292///
Steve Naroffe8043c32008-04-01 23:04:06 +0000293TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000294 // Allow multiple definitions for ObjC built-in typedefs.
295 // FIXME: Verify the underlying types are equivalent!
296 if (getLangOptions().ObjC1) {
297 const IdentifierInfo *typeIdent = New->getIdentifier();
298 if (typeIdent == Ident_id) {
299 Context.setObjCIdType(New);
300 return New;
301 } else if (typeIdent == Ident_Class) {
302 Context.setObjCClassType(New);
303 return New;
304 } else if (typeIdent == Ident_SEL) {
305 Context.setObjCSelType(New);
306 return New;
307 } else if (typeIdent == Ident_Protocol) {
308 Context.setObjCProtoType(New->getUnderlyingType());
309 return New;
310 }
311 // Fall through - the typedef name was not a builtin type.
312 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 // Verify the old decl was also a typedef.
314 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
315 if (!Old) {
316 Diag(New->getLocation(), diag::err_redefinition_different_kind,
317 New->getName());
318 Diag(OldD->getLocation(), diag::err_previous_definition);
319 return New;
320 }
321
Chris Lattner99cb9972008-07-25 18:44:27 +0000322 // If the typedef types are not identical, reject them in all languages and
323 // with any extensions enabled.
324 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
325 Context.getCanonicalType(Old->getUnderlyingType()) !=
326 Context.getCanonicalType(New->getUnderlyingType())) {
327 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
328 New->getUnderlyingType().getAsString(),
329 Old->getUnderlyingType().getAsString());
330 Diag(Old->getLocation(), diag::err_previous_definition);
331 return Old;
332 }
333
Eli Friedman54ecfce2008-06-11 06:20:39 +0000334 if (getLangOptions().Microsoft) return New;
335
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000336 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
337 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
338 // *either* declaration is in a system header. The code below implements
339 // this adhoc compatibility rule. FIXME: The following code will not
340 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000341 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
342 SourceManager &SrcMgr = Context.getSourceManager();
343 if (SrcMgr.isInSystemHeader(Old->getLocation()))
344 return New;
345 if (SrcMgr.isInSystemHeader(New->getLocation()))
346 return New;
347 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000348
Ted Kremenek2d05c082008-05-23 21:28:18 +0000349 Diag(New->getLocation(), diag::err_redefinition, New->getName());
350 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000351 return New;
352}
353
Chris Lattner6b6b5372008-06-26 18:38:35 +0000354/// DeclhasAttr - returns true if decl Declaration already has the target
355/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000356static bool DeclHasAttr(const Decl *decl, const Attr *target) {
357 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
358 if (attr->getKind() == target->getKind())
359 return true;
360
361 return false;
362}
363
364/// MergeAttributes - append attributes from the Old decl to the New one.
365static void MergeAttributes(Decl *New, Decl *Old) {
366 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
367
Chris Lattnerddee4232008-03-03 03:28:21 +0000368 while (attr) {
369 tmp = attr;
370 attr = attr->getNext();
371
372 if (!DeclHasAttr(New, tmp)) {
373 New->addAttr(tmp);
374 } else {
375 tmp->setNext(0);
376 delete(tmp);
377 }
378 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000379
380 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000381}
382
Chris Lattner04421082008-04-08 04:40:51 +0000383/// MergeFunctionDecl - We just parsed a function 'New' from
384/// declarator D which has the same name and scope as a previous
385/// declaration 'Old'. Figure out how to resolve this situation,
386/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000387/// Redeclaration will be set true if this New is a redeclaration OldD.
388///
389/// In C++, New and Old must be declarations that are not
390/// overloaded. Use IsOverload to determine whether New and Old are
391/// overloaded, and to select the Old declaration that New should be
392/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000393FunctionDecl *
394Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000395 assert(!isa<OverloadedFunctionDecl>(OldD) &&
396 "Cannot merge with an overloaded function declaration");
397
Douglas Gregorf0097952008-04-21 02:02:58 +0000398 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000399 // Verify the old decl was also a function.
400 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
401 if (!Old) {
402 Diag(New->getLocation(), diag::err_redefinition_different_kind,
403 New->getName());
404 Diag(OldD->getLocation(), diag::err_previous_definition);
405 return New;
406 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000407
408 // Determine whether the previous declaration was a definition,
409 // implicit declaration, or a declaration.
410 diag::kind PrevDiag;
411 if (Old->isThisDeclarationADefinition())
412 PrevDiag = diag::err_previous_definition;
413 else if (Old->isImplicit())
414 PrevDiag = diag::err_previous_implicit_declaration;
415 else
416 PrevDiag = diag::err_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000417
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000418 QualType OldQType = Context.getCanonicalType(Old->getType());
419 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000420
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000421 if (getLangOptions().CPlusPlus) {
422 // (C++98 13.1p2):
423 // Certain function declarations cannot be overloaded:
424 // -- Function declarations that differ only in the return type
425 // cannot be overloaded.
426 QualType OldReturnType
427 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
428 QualType NewReturnType
429 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
430 if (OldReturnType != NewReturnType) {
431 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
432 Diag(Old->getLocation(), PrevDiag);
433 return New;
434 }
435
436 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
437 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
438 if (OldMethod && NewMethod) {
439 // -- Member function declarations with the same name and the
440 // same parameter types cannot be overloaded if any of them
441 // is a static member function declaration.
442 if (OldMethod->isStatic() || NewMethod->isStatic()) {
443 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
444 Diag(Old->getLocation(), PrevDiag);
445 return New;
446 }
447 }
448
449 // (C++98 8.3.5p3):
450 // All declarations for a function shall agree exactly in both the
451 // return type and the parameter-type-list.
452 if (OldQType == NewQType) {
453 // We have a redeclaration.
454 MergeAttributes(New, Old);
455 Redeclaration = true;
456 return MergeCXXFunctionDecl(New, Old);
457 }
458
459 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000460 }
Chris Lattner04421082008-04-08 04:40:51 +0000461
462 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000463 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000464 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000465 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000466 MergeAttributes(New, Old);
467 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000468 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000469 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000470
Steve Naroff837618c2008-01-16 15:01:34 +0000471 // A function that has already been declared has been redeclared or defined
472 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000473
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
475 // TODO: This is totally simplistic. It should handle merging functions
476 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000477 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
478 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000479 return New;
480}
481
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000482/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000483static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000484 if (VD->isFileVarDecl())
485 return (!VD->getInit() &&
486 (VD->getStorageClass() == VarDecl::None ||
487 VD->getStorageClass() == VarDecl::Static));
488 return false;
489}
490
491/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
492/// when dealing with C "tentative" external object definitions (C99 6.9.2).
493void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
494 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000495 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000496
497 for (IdentifierResolver::iterator
498 I = IdResolver.begin(VD->getIdentifier(),
499 VD->getDeclContext(), false/*LookInParentCtx*/),
500 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000501 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000502 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
503
Steve Narofff855e6f2008-08-10 15:20:13 +0000504 // Handle the following case:
505 // int a[10];
506 // int a[]; - the code below makes sure we set the correct type.
507 // int a[11]; - this is an error, size isn't 10.
508 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
509 OldDecl->getType()->isConstantArrayType())
510 VD->setType(OldDecl->getType());
511
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000512 // Check for "tentative" definitions. We can't accomplish this in
513 // MergeVarDecl since the initializer hasn't been attached.
514 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
515 continue;
516
517 // Handle __private_extern__ just like extern.
518 if (OldDecl->getStorageClass() != VarDecl::Extern &&
519 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
520 VD->getStorageClass() != VarDecl::Extern &&
521 VD->getStorageClass() != VarDecl::PrivateExtern) {
522 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
523 Diag(OldDecl->getLocation(), diag::err_previous_definition);
524 }
525 }
526 }
527}
528
Reid Spencer5f016e22007-07-11 17:01:13 +0000529/// MergeVarDecl - We just parsed a variable 'New' which has the same name
530/// and scope as a previous declaration 'Old'. Figure out how to resolve this
531/// situation, merging decls or emitting diagnostics as appropriate.
532///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000533/// Tentative definition rules (C99 6.9.2p2) are checked by
534/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
535/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000536///
Steve Naroffe8043c32008-04-01 23:04:06 +0000537VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000538 // Verify the old decl was also a variable.
539 VarDecl *Old = dyn_cast<VarDecl>(OldD);
540 if (!Old) {
541 Diag(New->getLocation(), diag::err_redefinition_different_kind,
542 New->getName());
543 Diag(OldD->getLocation(), diag::err_previous_definition);
544 return New;
545 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000546
547 MergeAttributes(New, Old);
548
Reid Spencer5f016e22007-07-11 17:01:13 +0000549 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000550 QualType OldCType = Context.getCanonicalType(Old->getType());
551 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000552 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 Diag(New->getLocation(), diag::err_redefinition, New->getName());
554 Diag(Old->getLocation(), diag::err_previous_definition);
555 return New;
556 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000557 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
558 if (New->getStorageClass() == VarDecl::Static &&
559 (Old->getStorageClass() == VarDecl::None ||
560 Old->getStorageClass() == VarDecl::Extern)) {
561 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
562 Diag(Old->getLocation(), diag::err_previous_definition);
563 return New;
564 }
565 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
566 if (New->getStorageClass() != VarDecl::Static &&
567 Old->getStorageClass() == VarDecl::Static) {
568 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
569 Diag(Old->getLocation(), diag::err_previous_definition);
570 return New;
571 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000572 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
573 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000574 Diag(New->getLocation(), diag::err_redefinition, New->getName());
575 Diag(Old->getLocation(), diag::err_previous_definition);
576 }
577 return New;
578}
579
Chris Lattner04421082008-04-08 04:40:51 +0000580/// CheckParmsForFunctionDef - Check that the parameters of the given
581/// function are appropriate for the definition of a function. This
582/// takes care of any checks that cannot be performed on the
583/// declaration itself, e.g., that the types of each of the function
584/// parameters are complete.
585bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
586 bool HasInvalidParm = false;
587 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
588 ParmVarDecl *Param = FD->getParamDecl(p);
589
590 // C99 6.7.5.3p4: the parameters in a parameter type list in a
591 // function declarator that is part of a function definition of
592 // that function shall not have incomplete type.
593 if (Param->getType()->isIncompleteType() &&
594 !Param->isInvalidDecl()) {
595 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
596 Param->getType().getAsString());
597 Param->setInvalidDecl();
598 HasInvalidParm = true;
599 }
600 }
601
602 return HasInvalidParm;
603}
604
Reid Spencer5f016e22007-07-11 17:01:13 +0000605/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
606/// no declarator (e.g. "struct foo;") is parsed.
607Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
608 // TODO: emit error on 'int;' or 'const enum foo;'.
609 // TODO: emit error on 'typedef int;'
610 // if (!DS.isMissingDeclaratorOk()) Diag(...);
611
Steve Naroff92199282007-11-17 21:37:36 +0000612 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000613}
614
Steve Naroffd0091aa2008-01-10 22:15:12 +0000615bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000616 // Get the type before calling CheckSingleAssignmentConstraints(), since
617 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000618 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000619
Chris Lattner5cf216b2008-01-04 18:04:52 +0000620 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
621 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
622 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000623}
624
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000625bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000626 const ArrayType *AT = Context.getAsArrayType(DeclT);
627
628 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000629 // C99 6.7.8p14. We have an array of character type with unknown size
630 // being initialized to a string literal.
631 llvm::APSInt ConstVal(32);
632 ConstVal = strLiteral->getByteLength() + 1;
633 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000634 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000635 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000636 } else {
637 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000638 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000639 // FIXME: Avoid truncation for 64-bit length strings.
640 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000641 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000642 diag::warn_initializer_string_for_char_array_too_long)
643 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000644 }
645 // Set type from "char *" to "constant array of char".
646 strLiteral->setType(DeclT);
647 // For now, we always return false (meaning success).
648 return false;
649}
650
651StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000652 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000653 if (AT && AT->getElementType()->isCharType()) {
654 return dyn_cast<StringLiteral>(Init);
655 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000656 return 0;
657}
658
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000659bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
660 SourceLocation InitLoc,
661 std::string InitEntity) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000662 // C++ [dcl.init.ref]p1:
663 // A variable declared to be a T&, that is “reference to type T”
664 // (8.3.2), shall be initialized by an object, or function, of
665 // type T or by an object that can be converted into a T.
666 if (DeclType->isReferenceType())
667 return CheckReferenceInit(Init, DeclType);
668
Steve Naroffca107302008-01-21 23:53:58 +0000669 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
670 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000671 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000672 return Diag(InitLoc, diag::err_variable_object_no_init)
673 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +0000674
Steve Naroff2fdc3742007-12-10 22:44:33 +0000675 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
676 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000677 // FIXME: Handle wide strings
678 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
679 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000680
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000681 // C++ [dcl.init]p14:
682 // -- If the destination type is a (possibly cv-qualified) class
683 // type:
684 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
685 QualType DeclTypeC = Context.getCanonicalType(DeclType);
686 QualType InitTypeC = Context.getCanonicalType(Init->getType());
687
688 // -- If the initialization is direct-initialization, or if it is
689 // copy-initialization where the cv-unqualified version of the
690 // source type is the same class as, or a derived class of, the
691 // class of the destination, constructors are considered.
692 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
693 IsDerivedFrom(InitTypeC, DeclTypeC)) {
694 CXXConstructorDecl *Constructor
695 = PerformInitializationByConstructor(DeclType, &Init, 1,
696 InitLoc, Init->getSourceRange(),
697 InitEntity, IK_Copy);
698 return Constructor == 0;
699 }
700
701 // -- Otherwise (i.e., for the remaining copy-initialization
702 // cases), user-defined conversion sequences that can
703 // convert from the source type to the destination type or
704 // (when a conversion function is used) to a derived class
705 // thereof are enumerated as described in 13.3.1.4, and the
706 // best one is chosen through overload resolution
707 // (13.3). If the conversion cannot be done or is
708 // ambiguous, the initialization is ill-formed. The
709 // function selected is called with the initializer
710 // expression as its argument; if the function is a
711 // constructor, the call initializes a temporary of the
712 // destination type.
713 // FIXME: We're pretending to do copy elision here; return to
714 // this when we have ASTs for such things.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000715 if (!PerformImplicitConversion(Init, DeclType))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000716 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000717
718 return Diag(InitLoc, diag::err_typecheck_convert_incompatible)
719 << DeclType.getAsString() << InitEntity << "initializing"
720 << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000721 }
722
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000723 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000724 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000725 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
726 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +0000727
Steve Naroffd0091aa2008-01-10 22:15:12 +0000728 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000729 } else if (getLangOptions().CPlusPlus) {
730 // C++ [dcl.init]p14:
731 // [...] If the class is an aggregate (8.5.1), and the initializer
732 // is a brace-enclosed list, see 8.5.1.
733 //
734 // Note: 8.5.1 is handled below; here, we diagnose the case where
735 // we have an initializer list and a destination type that is not
736 // an aggregate.
737 // FIXME: In C++0x, this is yet another form of initialization.
738 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
739 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
740 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000741 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
742 << DeclType.getAsString() << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +0000743 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000744 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000745
Steve Naroff0cca7492008-05-01 22:18:59 +0000746 InitListChecker CheckInitList(this, InitList, DeclType);
747 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000748}
749
Douglas Gregor10bd3682008-11-17 22:58:34 +0000750/// GetNameForDeclarator - Determine the full declaration name for the
751/// given Declarator.
752DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
753 switch (D.getKind()) {
754 case Declarator::DK_Abstract:
755 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
756 return DeclarationName();
757
758 case Declarator::DK_Normal:
759 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
760 return DeclarationName(D.getIdentifier());
761
762 case Declarator::DK_Constructor: {
763 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
764 Ty = Context.getCanonicalType(Ty);
765 return Context.DeclarationNames.getCXXConstructorName(Ty);
766 }
767
768 case Declarator::DK_Destructor: {
769 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
770 Ty = Context.getCanonicalType(Ty);
771 return Context.DeclarationNames.getCXXDestructorName(Ty);
772 }
773
774 case Declarator::DK_Conversion: {
775 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
776 Ty = Context.getCanonicalType(Ty);
777 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
778 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000779
780 case Declarator::DK_Operator:
781 assert(D.getIdentifier() == 0 && "operator names have no identifier");
782 return Context.DeclarationNames.getCXXOperatorName(
783 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000784 }
785
786 assert(false && "Unknown name kind");
787 return DeclarationName();
788}
789
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000790Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000791Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000792 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +0000793 DeclarationName Name = GetNameForDeclarator(D);
794
Chris Lattnere80a59c2007-07-25 00:24:17 +0000795 // All of these full declarators require an identifier. If it doesn't have
796 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +0000797 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +0000798 if (!D.getInvalidType()) // Reject this if we think it is valid.
799 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000800 diag::err_declarator_need_ident)
801 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +0000802 return 0;
803 }
804
Chris Lattner31e05722007-08-26 06:24:45 +0000805 // The scope passed in may not be a decl scope. Zip up the scope tree until
806 // we find one that is.
807 while ((S->getFlags() & Scope::DeclScope) == 0)
808 S = S->getParent();
809
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000810 DeclContext *DC;
811 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +0000812 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000813 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000814
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000815 // See if this is a redefinition of a variable in the same scope.
816 if (!D.getCXXScopeSpec().isSet()) {
817 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +0000818 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000819 } else { // Something like "int foo::x;"
820 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000821 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000822
823 // C++ 7.3.1.2p2:
824 // Members (including explicit specializations of templates) of a named
825 // namespace can also be defined outside that namespace by explicit
826 // qualification of the name being defined, provided that the entity being
827 // defined was already declared in the namespace and the definition appears
828 // after the point of declaration in a namespace that encloses the
829 // declarations namespace.
830 //
831 if (PrevDecl == 0) {
832 // No previous declaration in the qualifying scope.
833 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member,
Douglas Gregor10bd3682008-11-17 22:58:34 +0000834 Name.getAsString(), D.getCXXScopeSpec().getRange());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000835 } else if (!CurContext->Encloses(DC)) {
836 // The qualifying scope doesn't enclose the original declaration.
837 // Emit diagnostic based on current scope.
838 SourceLocation L = D.getIdentifierLoc();
839 SourceRange R = D.getCXXScopeSpec().getRange();
840 if (isa<FunctionDecl>(CurContext)) {
Douglas Gregor10bd3682008-11-17 22:58:34 +0000841 Diag(L, diag::err_invalid_declarator_in_function, Name.getAsString(),
842 R);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000843 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000844 Diag(L, diag::err_invalid_declarator_scope)
845 << Name.getAsString() << cast<NamedDecl>(DC)->getName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000846 }
847 }
848 }
849
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000850 // In C++, the previous declaration we find might be a tag type
851 // (class or enum). In this case, the new declaration will hide the
852 // tag type.
853 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
854 PrevDecl = 0;
855
Chris Lattner41af0932007-11-14 06:34:38 +0000856 QualType R = GetTypeForDeclarator(D, S);
857 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
858
Reid Spencer5f016e22007-07-11 17:01:13 +0000859 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000860 // Check that there are no default arguments (C++ only).
861 if (getLangOptions().CPlusPlus)
862 CheckExtraCXXDefaultArguments(D);
863
Chris Lattner41af0932007-11-14 06:34:38 +0000864 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000865 if (!NewTD) return 0;
866
867 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000868 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000869 // Merge the decl with the existing one if appropriate. If the decl is
870 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000871 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
873 if (NewTD == 0) return 0;
874 }
875 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000876 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000877 // C99 6.7.7p2: If a typedef name specifies a variably modified type
878 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000879 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
880 // FIXME: Diagnostic needs to be fixed.
881 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000882 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000883 }
884 }
Chris Lattner41af0932007-11-14 06:34:38 +0000885 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000886 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000887 switch (D.getDeclSpec().getStorageClassSpec()) {
888 default: assert(0 && "Unknown storage class!");
889 case DeclSpec::SCS_auto:
890 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +0000891 case DeclSpec::SCS_mutable:
Reid Spencer5f016e22007-07-11 17:01:13 +0000892 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
893 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000894 InvalidDecl = true;
895 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000896 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
897 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
898 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000899 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000900 }
901
Chris Lattnera98e58d2008-03-15 21:24:04 +0000902 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +0000903 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +0000904 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
905
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000906 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +0000907 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +0000908 // This is a C++ constructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000909 assert(DC->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +0000910 "Constructors can only be declared in a member context");
911
Douglas Gregor42a552f2008-11-05 20:51:48 +0000912 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +0000913
914 // Create the new declaration
915 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000916 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000917 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +0000918 isExplicit, isInline,
919 /*isImplicitlyDeclared=*/false);
920
Douglas Gregor42a552f2008-11-05 20:51:48 +0000921 if (isInvalidDecl)
922 NewFD->setInvalidDecl();
923 } else if (D.getKind() == Declarator::DK_Destructor) {
924 // This is a C++ destructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000925 if (DC->isCXXRecord()) {
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000926 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000927
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000928 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000929 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000930 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000931 isInline,
932 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000933
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000934 if (isInvalidDecl)
935 NewFD->setInvalidDecl();
936 } else {
937 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
938 // Create a FunctionDecl to satisfy the function definition parsing
939 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000940 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000941 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000942 // FIXME: Move to DeclGroup...
943 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000944 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000945 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000946 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000947 if (!DC->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000948 Diag(D.getIdentifierLoc(),
949 diag::err_conv_function_not_member);
950 return 0;
951 } else {
952 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
953
954 NewFD = CXXConversionDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000955 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000956 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000957 isInline, isExplicit);
958
959 if (isInvalidDecl)
960 NewFD->setInvalidDecl();
961 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000962 } else if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000963 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000964 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000965 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000966 (SC == FunctionDecl::Static), isInline,
967 LastDeclarator);
968 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000969 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000970 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000971 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +0000972 // FIXME: Move to DeclGroup...
973 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000974 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000975 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000976 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000977
Daniel Dunbara80f8742008-08-05 01:35:17 +0000978 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +0000979 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +0000980 // The parser guarantees this is a string.
981 StringLiteral *SE = cast<StringLiteral>(E);
982 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
983 SE->getByteLength())));
984 }
985
Chris Lattner04421082008-04-08 04:40:51 +0000986 // Copy the parameter declarations from the declarator D to
987 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000988 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000989 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
990
991 // Create Decl objects for each parameter, adding them to the
992 // FunctionDecl.
993 llvm::SmallVector<ParmVarDecl*, 16> Params;
994
995 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
996 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000997 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000998 // We let through "const void" here because Sema::GetTypeForDeclarator
999 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001000 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1001 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001002 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1003 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001004 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1005
Chris Lattnerdef026a2008-04-10 02:26:16 +00001006 // In C++, the empty parameter-type-list must be spelled "void"; a
1007 // typedef of void is not permitted.
1008 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001009 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001010 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1011 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001012 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001013 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1014 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1015 }
1016
1017 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001018 } else if (R->getAsTypedefType()) {
1019 // When we're declaring a function with a typedef, as in the
1020 // following example, we'll need to synthesize (unnamed)
1021 // parameters for use in the declaration.
1022 //
1023 // @code
1024 // typedef void fn(int);
1025 // fn f;
1026 // @endcode
1027 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1028 if (!FT) {
1029 // This is a typedef of a function with no prototype, so we
1030 // don't need to do anything.
1031 } else if ((FT->getNumArgs() == 0) ||
1032 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1033 FT->getArgType(0)->isVoidType())) {
1034 // This is a zero-argument function. We don't need to do anything.
1035 } else {
1036 // Synthesize a parameter for each argument type.
1037 llvm::SmallVector<ParmVarDecl*, 16> Params;
1038 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1039 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001040 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001041 SourceLocation(), 0,
1042 *ArgType, VarDecl::None,
1043 0, 0));
1044 }
1045
1046 NewFD->setParams(&Params[0], Params.size());
1047 }
Chris Lattner04421082008-04-08 04:40:51 +00001048 }
1049
Douglas Gregor42a552f2008-11-05 20:51:48 +00001050 // C++ constructors and destructors are handled by separate
1051 // routines, since they don't require any declaration merging (C++
1052 // [class.mfct]p2) and they aren't ever pushed into scope, because
1053 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1054 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1055 return ActOnConstructorDeclarator(Constructor);
1056 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1057 return ActOnDestructorDeclarator(Destructor);
Douglas Gregor2def4832008-11-17 20:34:05 +00001058
1059 // Extra checking for conversion functions, including recording
1060 // the conversion function in its class.
1061 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1062 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001063
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001064 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1065 if (NewFD->isOverloadedOperator() &&
1066 CheckOverloadedOperatorDeclaration(NewFD))
1067 NewFD->setInvalidDecl();
1068
Steve Naroffffce4d52008-01-09 23:34:55 +00001069 // Merge the decl with the existing one if appropriate. Since C functions
1070 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001071 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001072 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001073 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001074
1075 // If C++, determine whether NewFD is an overload of PrevDecl or
1076 // a declaration that requires merging. If it's an overload,
1077 // there's no more work to do here; we'll just add the new
1078 // function to the scope.
1079 OverloadedFunctionDecl::function_iterator MatchedDecl;
1080 if (!getLangOptions().CPlusPlus ||
1081 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1082 Decl *OldDecl = PrevDecl;
1083
1084 // If PrevDecl was an overloaded function, extract the
1085 // FunctionDecl that matched.
1086 if (isa<OverloadedFunctionDecl>(PrevDecl))
1087 OldDecl = *MatchedDecl;
1088
1089 // NewFD and PrevDecl represent declarations that need to be
1090 // merged.
1091 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1092
1093 if (NewFD == 0) return 0;
1094 if (Redeclaration) {
1095 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1096
1097 if (OldDecl == PrevDecl) {
1098 // Remove the name binding for the previous
1099 // declaration. We'll add the binding back later, but then
1100 // it will refer to the new declaration (which will
1101 // contain more information).
1102 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1103 } else {
1104 // We need to update the OverloadedFunctionDecl with the
1105 // latest declaration of this function, so that name
1106 // lookup will always refer to the latest declaration of
1107 // this function.
1108 *MatchedDecl = NewFD;
1109
1110 // Add the redeclaration to the current scope, since we'll
1111 // be skipping PushOnScopeChains.
1112 S->AddDecl(NewFD);
1113
1114 return NewFD;
1115 }
1116 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001117 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001118 }
1119 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001120
1121 // In C++, check default arguments now that we have merged decls.
1122 if (getLangOptions().CPlusPlus)
1123 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001124 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001125 // Check that there are no default arguments (C++ only).
1126 if (getLangOptions().CPlusPlus)
1127 CheckExtraCXXDefaultArguments(D);
1128
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001129 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001130 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1131 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001132 InvalidDecl = true;
1133 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001134
1135 VarDecl *NewVD;
1136 VarDecl::StorageClass SC;
1137 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001138 default: assert(0 && "Unknown storage class!");
1139 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1140 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1141 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1142 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1143 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1144 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001145 case DeclSpec::SCS_mutable:
1146 // mutable can only appear on non-static class members, so it's always
1147 // an error here
1148 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1149 InvalidDecl = true;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001150 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001151 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001152
1153 IdentifierInfo *II = Name.getAsIdentifierInfo();
1154 if (!II) {
1155 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name,
1156 Name.getAsString());
1157 return 0;
1158 }
1159
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001160 if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001161 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1162 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001163 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001164 D.getIdentifierLoc(), II,
1165 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001166 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001167 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001168 if (S->getFnParent() == 0) {
1169 // C99 6.9p2: The storage-class specifiers auto and register shall not
1170 // appear in the declaration specifiers in an external declaration.
1171 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1172 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
1173 R.getAsString());
1174 InvalidDecl = true;
1175 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001176 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001177 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1178 II, R, SC, LastDeclarator,
1179 // FIXME: Move to DeclGroup...
1180 D.getDeclSpec().getSourceRange().getBegin());
1181 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001182 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001183 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001184 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001185
Daniel Dunbara735ad82008-08-06 00:03:29 +00001186 // Handle GNU asm-label extension (encoded as an attribute).
1187 if (Expr *E = (Expr*) D.getAsmLabel()) {
1188 // The parser guarantees this is a string.
1189 StringLiteral *SE = cast<StringLiteral>(E);
1190 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1191 SE->getByteLength())));
1192 }
1193
Nate Begemanc8e89a82008-03-14 18:07:10 +00001194 // Emit an error if an address space was applied to decl with local storage.
1195 // This includes arrays of objects with address space qualifiers, but not
1196 // automatic variables that point to other address spaces.
1197 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001198 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1199 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1200 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001201 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001202 // Merge the decl with the existing one if appropriate. If the decl is
1203 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001204 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 NewVD = MergeVarDecl(NewVD, PrevDecl);
1206 if (NewVD == 0) return 0;
1207 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 New = NewVD;
1209 }
1210
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001211 // Set the lexical context. If the declarator has a C++ scope specifier, the
1212 // lexical context will be different from the semantic context.
1213 New->setLexicalDeclContext(CurContext);
1214
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001216 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001217 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001218 // If any semantic error occurred, mark the decl as invalid.
1219 if (D.getInvalidType() || InvalidDecl)
1220 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001221
1222 return New;
1223}
1224
Steve Naroff6594a702008-10-27 11:34:16 +00001225void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001226 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1227 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001228}
1229
Eli Friedmanc594b322008-05-20 13:48:25 +00001230bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1231 switch (Init->getStmtClass()) {
1232 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001233 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001234 return true;
1235 case Expr::ParenExprClass: {
1236 const ParenExpr* PE = cast<ParenExpr>(Init);
1237 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1238 }
1239 case Expr::CompoundLiteralExprClass:
1240 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1241 case Expr::DeclRefExprClass: {
1242 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001243 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1244 if (VD->hasGlobalStorage())
1245 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001246 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001247 return true;
1248 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001249 if (isa<FunctionDecl>(D))
1250 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001251 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001252 return true;
1253 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001254 case Expr::MemberExprClass: {
1255 const MemberExpr *M = cast<MemberExpr>(Init);
1256 if (M->isArrow())
1257 return CheckAddressConstantExpression(M->getBase());
1258 return CheckAddressConstantExpressionLValue(M->getBase());
1259 }
1260 case Expr::ArraySubscriptExprClass: {
1261 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1262 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1263 return CheckAddressConstantExpression(ASE->getBase()) ||
1264 CheckArithmeticConstantExpression(ASE->getIdx());
1265 }
1266 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001267 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001268 return false;
1269 case Expr::UnaryOperatorClass: {
1270 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1271
1272 // C99 6.6p9
1273 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001274 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001275
Steve Naroff6594a702008-10-27 11:34:16 +00001276 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001277 return true;
1278 }
1279 }
1280}
1281
1282bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1283 switch (Init->getStmtClass()) {
1284 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001285 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001286 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001287 case Expr::ParenExprClass:
1288 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001289 case Expr::StringLiteralClass:
1290 case Expr::ObjCStringLiteralClass:
1291 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001292 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001293 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001294 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1295 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1296 Builtin::BI__builtin___CFStringMakeConstantString)
1297 return false;
1298
Steve Naroff6594a702008-10-27 11:34:16 +00001299 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001300 return true;
1301
Eli Friedmanc594b322008-05-20 13:48:25 +00001302 case Expr::UnaryOperatorClass: {
1303 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1304
1305 // C99 6.6p9
1306 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1307 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1308
1309 if (Exp->getOpcode() == UnaryOperator::Extension)
1310 return CheckAddressConstantExpression(Exp->getSubExpr());
1311
Steve Naroff6594a702008-10-27 11:34:16 +00001312 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001313 return true;
1314 }
1315 case Expr::BinaryOperatorClass: {
1316 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1317 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1318
1319 Expr *PExp = Exp->getLHS();
1320 Expr *IExp = Exp->getRHS();
1321 if (IExp->getType()->isPointerType())
1322 std::swap(PExp, IExp);
1323
1324 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1325 return CheckAddressConstantExpression(PExp) ||
1326 CheckArithmeticConstantExpression(IExp);
1327 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001328 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001329 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001330 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001331 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1332 // Check for implicit promotion
1333 if (SubExpr->getType()->isFunctionType() ||
1334 SubExpr->getType()->isArrayType())
1335 return CheckAddressConstantExpressionLValue(SubExpr);
1336 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001337
1338 // Check for pointer->pointer cast
1339 if (SubExpr->getType()->isPointerType())
1340 return CheckAddressConstantExpression(SubExpr);
1341
Eli Friedmanc3f07642008-08-25 20:46:57 +00001342 if (SubExpr->getType()->isIntegralType()) {
1343 // Check for the special-case of a pointer->int->pointer cast;
1344 // this isn't standard, but some code requires it. See
1345 // PR2720 for an example.
1346 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1347 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1348 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1349 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1350 if (IntWidth >= PointerWidth) {
1351 return CheckAddressConstantExpression(SubCast->getSubExpr());
1352 }
1353 }
1354 }
1355 }
1356 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001357 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001358 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001359
Steve Naroff6594a702008-10-27 11:34:16 +00001360 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001361 return true;
1362 }
1363 case Expr::ConditionalOperatorClass: {
1364 // FIXME: Should we pedwarn here?
1365 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1366 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001367 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001368 return true;
1369 }
1370 if (CheckArithmeticConstantExpression(Exp->getCond()))
1371 return true;
1372 if (Exp->getLHS() &&
1373 CheckAddressConstantExpression(Exp->getLHS()))
1374 return true;
1375 return CheckAddressConstantExpression(Exp->getRHS());
1376 }
1377 case Expr::AddrLabelExprClass:
1378 return false;
1379 }
1380}
1381
Eli Friedman4caf0552008-06-09 05:05:07 +00001382static const Expr* FindExpressionBaseAddress(const Expr* E);
1383
1384static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1385 switch (E->getStmtClass()) {
1386 default:
1387 return E;
1388 case Expr::ParenExprClass: {
1389 const ParenExpr* PE = cast<ParenExpr>(E);
1390 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1391 }
1392 case Expr::MemberExprClass: {
1393 const MemberExpr *M = cast<MemberExpr>(E);
1394 if (M->isArrow())
1395 return FindExpressionBaseAddress(M->getBase());
1396 return FindExpressionBaseAddressLValue(M->getBase());
1397 }
1398 case Expr::ArraySubscriptExprClass: {
1399 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1400 return FindExpressionBaseAddress(ASE->getBase());
1401 }
1402 case Expr::UnaryOperatorClass: {
1403 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1404
1405 if (Exp->getOpcode() == UnaryOperator::Deref)
1406 return FindExpressionBaseAddress(Exp->getSubExpr());
1407
1408 return E;
1409 }
1410 }
1411}
1412
1413static const Expr* FindExpressionBaseAddress(const Expr* E) {
1414 switch (E->getStmtClass()) {
1415 default:
1416 return E;
1417 case Expr::ParenExprClass: {
1418 const ParenExpr* PE = cast<ParenExpr>(E);
1419 return FindExpressionBaseAddress(PE->getSubExpr());
1420 }
1421 case Expr::UnaryOperatorClass: {
1422 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1423
1424 // C99 6.6p9
1425 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1426 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1427
1428 if (Exp->getOpcode() == UnaryOperator::Extension)
1429 return FindExpressionBaseAddress(Exp->getSubExpr());
1430
1431 return E;
1432 }
1433 case Expr::BinaryOperatorClass: {
1434 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1435
1436 Expr *PExp = Exp->getLHS();
1437 Expr *IExp = Exp->getRHS();
1438 if (IExp->getType()->isPointerType())
1439 std::swap(PExp, IExp);
1440
1441 return FindExpressionBaseAddress(PExp);
1442 }
1443 case Expr::ImplicitCastExprClass: {
1444 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1445
1446 // Check for implicit promotion
1447 if (SubExpr->getType()->isFunctionType() ||
1448 SubExpr->getType()->isArrayType())
1449 return FindExpressionBaseAddressLValue(SubExpr);
1450
1451 // Check for pointer->pointer cast
1452 if (SubExpr->getType()->isPointerType())
1453 return FindExpressionBaseAddress(SubExpr);
1454
1455 // We assume that we have an arithmetic expression here;
1456 // if we don't, we'll figure it out later
1457 return 0;
1458 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001459 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001460 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1461
1462 // Check for pointer->pointer cast
1463 if (SubExpr->getType()->isPointerType())
1464 return FindExpressionBaseAddress(SubExpr);
1465
1466 // We assume that we have an arithmetic expression here;
1467 // if we don't, we'll figure it out later
1468 return 0;
1469 }
1470 }
1471}
1472
Eli Friedmanc594b322008-05-20 13:48:25 +00001473bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1474 switch (Init->getStmtClass()) {
1475 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001476 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001477 return true;
1478 case Expr::ParenExprClass: {
1479 const ParenExpr* PE = cast<ParenExpr>(Init);
1480 return CheckArithmeticConstantExpression(PE->getSubExpr());
1481 }
1482 case Expr::FloatingLiteralClass:
1483 case Expr::IntegerLiteralClass:
1484 case Expr::CharacterLiteralClass:
1485 case Expr::ImaginaryLiteralClass:
1486 case Expr::TypesCompatibleExprClass:
1487 case Expr::CXXBoolLiteralExprClass:
1488 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001489 case Expr::CallExprClass:
1490 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001491 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001492
1493 // Allow any constant foldable calls to builtins.
1494 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001495 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001496
Steve Naroff6594a702008-10-27 11:34:16 +00001497 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001498 return true;
1499 }
1500 case Expr::DeclRefExprClass: {
1501 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1502 if (isa<EnumConstantDecl>(D))
1503 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001504 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001505 return true;
1506 }
1507 case Expr::CompoundLiteralExprClass:
1508 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1509 // but vectors are allowed to be magic.
1510 if (Init->getType()->isVectorType())
1511 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001512 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001513 return true;
1514 case Expr::UnaryOperatorClass: {
1515 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1516
1517 switch (Exp->getOpcode()) {
1518 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1519 // See C99 6.6p3.
1520 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001521 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001522 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001523 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00001524 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1525 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001526 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001527 return true;
1528 case UnaryOperator::Extension:
1529 case UnaryOperator::LNot:
1530 case UnaryOperator::Plus:
1531 case UnaryOperator::Minus:
1532 case UnaryOperator::Not:
1533 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1534 }
1535 }
Sebastian Redl05189992008-11-11 17:56:53 +00001536 case Expr::SizeOfAlignOfExprClass: {
1537 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001538 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00001539 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00001540 return false;
1541 // alignof always evaluates to a constant.
1542 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00001543 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001544 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001545 return true;
1546 }
1547 return false;
1548 }
1549 case Expr::BinaryOperatorClass: {
1550 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1551
1552 if (Exp->getLHS()->getType()->isArithmeticType() &&
1553 Exp->getRHS()->getType()->isArithmeticType()) {
1554 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1555 CheckArithmeticConstantExpression(Exp->getRHS());
1556 }
1557
Eli Friedman4caf0552008-06-09 05:05:07 +00001558 if (Exp->getLHS()->getType()->isPointerType() &&
1559 Exp->getRHS()->getType()->isPointerType()) {
1560 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1561 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1562
1563 // Only allow a null (constant integer) base; we could
1564 // allow some additional cases if necessary, but this
1565 // is sufficient to cover offsetof-like constructs.
1566 if (!LHSBase && !RHSBase) {
1567 return CheckAddressConstantExpression(Exp->getLHS()) ||
1568 CheckAddressConstantExpression(Exp->getRHS());
1569 }
1570 }
1571
Steve Naroff6594a702008-10-27 11:34:16 +00001572 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001573 return true;
1574 }
1575 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001576 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001577 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001578 if (SubExpr->getType()->isArithmeticType())
1579 return CheckArithmeticConstantExpression(SubExpr);
1580
Eli Friedmanb529d832008-09-02 09:37:00 +00001581 if (SubExpr->getType()->isPointerType()) {
1582 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1583 // If the pointer has a null base, this is an offsetof-like construct
1584 if (!Base)
1585 return CheckAddressConstantExpression(SubExpr);
1586 }
1587
Steve Naroff6594a702008-10-27 11:34:16 +00001588 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001589 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001590 }
1591 case Expr::ConditionalOperatorClass: {
1592 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001593
1594 // If GNU extensions are disabled, we require all operands to be arithmetic
1595 // constant expressions.
1596 if (getLangOptions().NoExtensions) {
1597 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1598 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1599 CheckArithmeticConstantExpression(Exp->getRHS());
1600 }
1601
1602 // Otherwise, we have to emulate some of the behavior of fold here.
1603 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1604 // because it can constant fold things away. To retain compatibility with
1605 // GCC code, we see if we can fold the condition to a constant (which we
1606 // should always be able to do in theory). If so, we only require the
1607 // specified arm of the conditional to be a constant. This is a horrible
1608 // hack, but is require by real world code that uses __builtin_constant_p.
1609 APValue Val;
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001610 if (!Exp->getCond()->Evaluate(Val, Context)) {
1611 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00001612 // won't be able to either. Use it to emit the diagnostic though.
1613 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001614 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00001615 return Res;
1616 }
1617
1618 // Verify that the side following the condition is also a constant.
1619 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1620 if (Val.getInt() == 0)
1621 std::swap(TrueSide, FalseSide);
1622
1623 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001624 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001625
1626 // Okay, the evaluated side evaluates to a constant, so we accept this.
1627 // Check to see if the other side is obviously not a constant. If so,
1628 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001629 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001630 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001631 diag::ext_typecheck_expression_not_constant_but_accepted)
1632 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00001633 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001634 }
1635 }
1636}
1637
1638bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes9a979c32008-07-07 16:46:50 +00001639 Init = Init->IgnoreParens();
1640
Eli Friedmanc594b322008-05-20 13:48:25 +00001641 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1642 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1643 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1644
Nuno Lopes9a979c32008-07-07 16:46:50 +00001645 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1646 return CheckForConstantInitializer(e->getInitializer(), DclT);
1647
Eli Friedmanc594b322008-05-20 13:48:25 +00001648 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1649 unsigned numInits = Exp->getNumInits();
1650 for (unsigned i = 0; i < numInits; i++) {
1651 // FIXME: Need to get the type of the declaration for C++,
1652 // because it could be a reference?
1653 if (CheckForConstantInitializer(Exp->getInit(i),
1654 Exp->getInit(i)->getType()))
1655 return true;
1656 }
1657 return false;
1658 }
1659
1660 if (Init->isNullPointerConstant(Context))
1661 return false;
1662 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001663 QualType InitTy = Context.getCanonicalType(Init->getType())
1664 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001665 if (InitTy == Context.BoolTy) {
1666 // Special handling for pointers implicitly cast to bool;
1667 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1668 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1669 Expr* SubE = ICE->getSubExpr();
1670 if (SubE->getType()->isPointerType() ||
1671 SubE->getType()->isArrayType() ||
1672 SubE->getType()->isFunctionType()) {
1673 return CheckAddressConstantExpression(Init);
1674 }
1675 }
1676 } else if (InitTy->isIntegralType()) {
1677 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001678 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001679 SubE = CE->getSubExpr();
1680 // Special check for pointer cast to int; we allow as an extension
1681 // an address constant cast to an integer if the integer
1682 // is of an appropriate width (this sort of code is apparently used
1683 // in some places).
1684 // FIXME: Add pedwarn?
1685 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1686 if (SubE && (SubE->getType()->isPointerType() ||
1687 SubE->getType()->isArrayType() ||
1688 SubE->getType()->isFunctionType())) {
1689 unsigned IntWidth = Context.getTypeSize(Init->getType());
1690 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1691 if (IntWidth >= PointerWidth)
1692 return CheckAddressConstantExpression(Init);
1693 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001694 }
1695
1696 return CheckArithmeticConstantExpression(Init);
1697 }
1698
1699 if (Init->getType()->isPointerType())
1700 return CheckAddressConstantExpression(Init);
1701
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001702 // An array type at the top level that isn't an init-list must
1703 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001704 if (Init->getType()->isArrayType())
1705 return false;
1706
Nuno Lopes73419bf2008-09-01 18:42:41 +00001707 if (Init->getType()->isFunctionType())
1708 return false;
1709
Steve Naroff8af6a452008-10-02 17:12:56 +00001710 // Allow block exprs at top level.
1711 if (Init->getType()->isBlockPointerType())
1712 return false;
1713
Steve Naroff6594a702008-10-27 11:34:16 +00001714 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001715 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001716}
1717
Steve Naroffbb204692007-09-12 14:07:44 +00001718void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001719 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001720 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001721 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001722
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001723 // If there is no declaration, there was an error parsing it. Just ignore
1724 // the initializer.
1725 if (RealDecl == 0) {
1726 delete Init;
1727 return;
1728 }
Steve Naroffbb204692007-09-12 14:07:44 +00001729
Steve Naroff410e3e22007-09-12 20:13:48 +00001730 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1731 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001732 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1733 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001734 RealDecl->setInvalidDecl();
1735 return;
1736 }
Steve Naroffbb204692007-09-12 14:07:44 +00001737 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001738 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001739 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001740 if (VDecl->isBlockVarDecl()) {
1741 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001742 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001743 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001744 VDecl->setInvalidDecl();
1745 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001746 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1747 VDecl->getName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001748 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001749
1750 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1751 if (!getLangOptions().CPlusPlus) {
1752 if (SC == VarDecl::Static) // C99 6.7.8p4.
1753 CheckForConstantInitializer(Init, DclT);
1754 }
Steve Naroffbb204692007-09-12 14:07:44 +00001755 }
Steve Naroff248a7532008-04-15 22:42:06 +00001756 } else if (VDecl->isFileVarDecl()) {
1757 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001758 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001759 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001760 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1761 VDecl->getName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001762 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001763
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001764 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1765 if (!getLangOptions().CPlusPlus) {
1766 // C99 6.7.8p4. All file scoped initializers need to be constant.
1767 CheckForConstantInitializer(Init, DclT);
1768 }
Steve Naroffbb204692007-09-12 14:07:44 +00001769 }
1770 // If the type changed, it means we had an incomplete type that was
1771 // completed by the initializer. For example:
1772 // int ary[] = { 1, 3, 5 };
1773 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001774 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001775 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001776 Init->setType(DclT);
1777 }
Steve Naroffbb204692007-09-12 14:07:44 +00001778
1779 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001780 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001781 return;
1782}
1783
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001784void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1785 Decl *RealDecl = static_cast<Decl *>(dcl);
1786
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00001787 // If there is no declaration, there was an error parsing it. Just ignore it.
1788 if (RealDecl == 0)
1789 return;
1790
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001791 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1792 QualType Type = Var->getType();
1793 // C++ [dcl.init.ref]p3:
1794 // The initializer can be omitted for a reference only in a
1795 // parameter declaration (8.3.5), in the declaration of a
1796 // function return type, in the declaration of a class member
1797 // within its class declaration (9.2), and where the extern
1798 // specifier is explicitly used.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001799 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001800 Diag(Var->getLocation(),
1801 diag::err_reference_var_requires_init,
1802 Var->getName(),
1803 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor18fe5682008-11-03 20:45:27 +00001804 Var->setInvalidDecl();
1805 return;
1806 }
1807
1808 // C++ [dcl.init]p9:
1809 //
1810 // If no initializer is specified for an object, and the object
1811 // is of (possibly cv-qualified) non-POD class type (or array
1812 // thereof), the object shall be default-initialized; if the
1813 // object is of const-qualified type, the underlying class type
1814 // shall have a user-declared default constructor.
1815 if (getLangOptions().CPlusPlus) {
1816 QualType InitType = Type;
1817 if (const ArrayType *Array = Context.getAsArrayType(Type))
1818 InitType = Array->getElementType();
1819 if (InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001820 const CXXConstructorDecl *Constructor
1821 = PerformInitializationByConstructor(InitType, 0, 0,
1822 Var->getLocation(),
1823 SourceRange(Var->getLocation(),
1824 Var->getLocation()),
1825 Var->getName(),
1826 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001827 if (!Constructor)
1828 Var->setInvalidDecl();
1829 }
1830 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001831
Douglas Gregor818ce482008-10-29 13:50:18 +00001832#if 0
1833 // FIXME: Temporarily disabled because we are not properly parsing
1834 // linkage specifications on declarations, e.g.,
1835 //
1836 // extern "C" const CGPoint CGPointerZero;
1837 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001838 // C++ [dcl.init]p9:
1839 //
1840 // If no initializer is specified for an object, and the
1841 // object is of (possibly cv-qualified) non-POD class type (or
1842 // array thereof), the object shall be default-initialized; if
1843 // the object is of const-qualified type, the underlying class
1844 // type shall have a user-declared default
1845 // constructor. Otherwise, if no initializer is specified for
1846 // an object, the object and its subobjects, if any, have an
1847 // indeterminate initial value; if the object or any of its
1848 // subobjects are of const-qualified type, the program is
1849 // ill-formed.
1850 //
1851 // This isn't technically an error in C, so we don't diagnose it.
1852 //
1853 // FIXME: Actually perform the POD/user-defined default
1854 // constructor check.
1855 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00001856 Context.getCanonicalType(Type).isConstQualified() &&
1857 Var->getStorageClass() != VarDecl::Extern)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001858 Diag(Var->getLocation(),
1859 diag::err_const_var_requires_init,
1860 Var->getName(),
1861 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor818ce482008-10-29 13:50:18 +00001862#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001863 }
1864}
1865
Reid Spencer5f016e22007-07-11 17:01:13 +00001866/// The declarators are chained together backwards, reverse the list.
1867Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1868 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001869 Decl *GroupDecl = static_cast<Decl*>(group);
1870 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001871 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001872
1873 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1874 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001875 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001876 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001877 else { // reverse the list.
1878 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001879 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001880 Group->setNextDeclarator(NewGroup);
1881 NewGroup = Group;
1882 Group = Next;
1883 }
1884 }
1885 // Perform semantic analysis that depends on having fully processed both
1886 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001887 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001888 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1889 if (!IDecl)
1890 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001891 QualType T = IDecl->getType();
1892
1893 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1894 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001895 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1896 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001897 if (T->isVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001898 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1899 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001900 }
1901 }
1902 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1903 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001904 if (IDecl->isBlockVarDecl() &&
1905 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001906 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001907 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1908 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001909 IDecl->setInvalidDecl();
1910 }
1911 }
1912 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1913 // object that has file scope without an initializer, and without a
1914 // storage-class specifier or with the storage-class specifier "static",
1915 // constitutes a tentative definition. Note: A tentative definition with
1916 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001917 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001918 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001919 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1920 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001921 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001922 // C99 6.9.2p3: If the declaration of an identifier for an object is
1923 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1924 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001925 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1926 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001927 IDecl->setInvalidDecl();
1928 }
1929 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001930 if (IDecl->isFileVarDecl())
1931 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001932 }
1933 return NewGroup;
1934}
Steve Naroffe1223f72007-08-28 03:03:08 +00001935
Chris Lattner04421082008-04-08 04:40:51 +00001936/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1937/// to introduce parameters into function prototype scope.
1938Sema::DeclTy *
1939Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001940 // FIXME: disallow CXXScopeSpec for param declarators.
Chris Lattner985abd92008-06-26 06:49:43 +00001941 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001942
1943 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001944 VarDecl::StorageClass StorageClass = VarDecl::None;
1945 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1946 StorageClass = VarDecl::Register;
1947 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00001948 Diag(DS.getStorageClassSpecLoc(),
1949 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001950 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001951 }
1952 if (DS.isThreadSpecified()) {
1953 Diag(DS.getThreadSpecLoc(),
1954 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001955 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001956 }
1957
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001958 // Check that there are no default arguments inside the type of this
1959 // parameter (C++ only).
1960 if (getLangOptions().CPlusPlus)
1961 CheckExtraCXXDefaultArguments(D);
1962
Chris Lattner04421082008-04-08 04:40:51 +00001963 // In this context, we *do not* check D.getInvalidType(). If the declarator
1964 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1965 // though it will not reflect the user specified type.
1966 QualType parmDeclType = GetTypeForDeclarator(D, S);
1967
1968 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1969
Reid Spencer5f016e22007-07-11 17:01:13 +00001970 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1971 // Can this happen for params? We already checked that they don't conflict
1972 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001973 IdentifierInfo *II = D.getIdentifier();
1974 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1975 if (S->isDeclScope(PrevDecl)) {
1976 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1977 dyn_cast<NamedDecl>(PrevDecl)->getName());
1978
1979 // Recover by removing the name
1980 II = 0;
1981 D.SetIdentifier(0, D.getIdentifierLoc());
1982 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001983 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001984
1985 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1986 // Doing the promotion here has a win and a loss. The win is the type for
1987 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1988 // code generator). The loss is the orginal type isn't preserved. For example:
1989 //
1990 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1991 // int blockvardecl[5];
1992 // sizeof(parmvardecl); // size == 4
1993 // sizeof(blockvardecl); // size == 20
1994 // }
1995 //
1996 // For expressions, all implicit conversions are captured using the
1997 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1998 //
1999 // FIXME: If a source translation tool needs to see the original type, then
2000 // we need to consider storing both types (in ParmVarDecl)...
2001 //
Chris Lattnere6327742008-04-02 05:18:44 +00002002 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002003 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002004 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002005 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002006 parmDeclType = Context.getPointerType(parmDeclType);
2007
Chris Lattner04421082008-04-08 04:40:51 +00002008 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2009 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002010 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002011 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002012
Chris Lattner04421082008-04-08 04:40:51 +00002013 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002014 New->setInvalidDecl();
2015
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002016 if (II)
2017 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00002018
Chris Lattner3ff30c82008-06-29 00:02:00 +00002019 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002020 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002021
Reid Spencer5f016e22007-07-11 17:01:13 +00002022}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002023
Chris Lattnerb652cea2007-10-09 17:14:05 +00002024Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002025 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2027 "Not a function declarator!");
2028 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002029
Reid Spencer5f016e22007-07-11 17:01:13 +00002030 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2031 // for a K&R function.
2032 if (!FTI.hasPrototype) {
2033 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002034 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002035 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2036 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002037 // Implicitly declare the argument as type 'int' for lack of a better
2038 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002039 DeclSpec DS;
2040 const char* PrevSpec; // unused
2041 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2042 PrevSpec);
2043 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2044 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2045 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002046 }
2047 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002048 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002049 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002050 }
2051
2052 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002053
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002054 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00002055 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002056}
2057
2058Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2059 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002060 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002061
2062 // See if this is a redefinition.
2063 const FunctionDecl *Definition;
2064 if (FD->getBody(Definition)) {
2065 Diag(FD->getLocation(), diag::err_redefinition,
2066 FD->getName());
2067 Diag(Definition->getLocation(), diag::err_previous_definition);
2068 }
2069
Chris Lattnerb048c982008-04-06 04:47:34 +00002070 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00002071
2072 // Check the validity of our function parameters
2073 CheckParmsForFunctionDef(FD);
2074
2075 // Introduce our parameters into the function scope
2076 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2077 ParmVarDecl *Param = FD->getParamDecl(p);
2078 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002079 if (Param->getIdentifier())
2080 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002081 }
Chris Lattner04421082008-04-08 04:40:51 +00002082
Reid Spencer5f016e22007-07-11 17:01:13 +00002083 return FD;
2084}
2085
Steve Naroffd6d054d2007-11-11 23:20:51 +00002086Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
2087 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00002088 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002089 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002090 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002091 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002092 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002093 } else
2094 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002095 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002096 // Verify and clean out per-function state.
2097
2098 // Check goto/label use.
2099 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2100 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2101 // Verify that we have no forward references left. If so, there was a goto
2102 // or address of a label taken, but no definition of it. Label fwd
2103 // definitions are indicated with a null substmt.
2104 if (I->second->getSubStmt() == 0) {
2105 LabelStmt *L = I->second;
2106 // Emit error.
2107 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
2108
2109 // At this point, we have gotos that use the bogus label. Stitch it into
2110 // the function body so that they aren't leaked and that the AST is well
2111 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002112 if (Body) {
2113 L->setSubStmt(new NullStmt(L->getIdentLoc()));
2114 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2115 } else {
2116 // The whole function wasn't parsed correctly, just delete this.
2117 delete L;
2118 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 }
2120 }
2121 LabelMap.clear();
2122
Steve Naroffd6d054d2007-11-11 23:20:51 +00002123 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002124}
2125
Reid Spencer5f016e22007-07-11 17:01:13 +00002126/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2127/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002128ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2129 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002130 // Extension in C99. Legal in C90, but warn about it.
2131 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002132 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002133 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002134 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002135
2136 // FIXME: handle stuff like:
2137 // void foo() { extern float X(); }
2138 // void bar() { X(); } <-- implicit decl for X in another scope.
2139
2140 // Set a Declarator for the implicit definition: int foo();
2141 const char *Dummy;
2142 DeclSpec DS;
2143 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2144 Error = Error; // Silence warning.
2145 assert(!Error && "Error setting up implicit decl!");
2146 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002147 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002148 D.SetIdentifier(&II, Loc);
2149
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002150 // Insert this function into translation-unit scope.
2151
2152 DeclContext *PrevDC = CurContext;
2153 CurContext = Context.getTranslationUnitDecl();
2154
Steve Naroffe2ef8152008-04-04 14:32:09 +00002155 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002156 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002157 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002158
2159 CurContext = PrevDC;
2160
Steve Naroffe2ef8152008-04-04 14:32:09 +00002161 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002162}
2163
2164
Chris Lattner41af0932007-11-14 06:34:38 +00002165TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002166 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002167 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002168 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002169
2170 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002171 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2172 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002173 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002174 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002175 if (D.getInvalidType())
2176 NewTD->setInvalidDecl();
2177 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002178}
2179
Steve Naroff08d92e42007-09-15 18:49:24 +00002180/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002181/// former case, Name will be non-null. In the later case, Name will be null.
2182/// TagType indicates what kind of tag this is. TK indicates whether this is a
2183/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002184Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002185 SourceLocation KWLoc, const CXXScopeSpec &SS,
2186 IdentifierInfo *Name, SourceLocation NameLoc,
2187 AttributeList *Attr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002188 // If this is a use of an existing tag, it must have a name.
2189 assert((Name != 0 || TK == TK_Definition) &&
2190 "Nameless record must be a definition!");
2191
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002192 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002193 switch (TagType) {
2194 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002195 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2196 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2197 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2198 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002199 }
2200
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002201 // Two code paths: a new one for structs/unions/classes where we create
2202 // separate decls for forward declarations, and an old (eventually to
2203 // be removed) code path for enums.
2204 if (Kind != TagDecl::TK_enum)
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002205 return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002206
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002207 DeclContext *DC = CurContext;
2208 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002209
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002210 if (Name && SS.isNotEmpty()) {
2211 // We have a nested-name tag ('struct foo::bar').
2212
2213 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002214 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002215 Name = 0;
2216 goto CreateNewDecl;
2217 }
2218
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002219 DC = static_cast<DeclContext*>(SS.getScopeRep());
2220 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002221 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2222
2223 // A tag 'foo::bar' must already exist.
2224 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002225 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002226 Name = 0;
2227 goto CreateNewDecl;
2228 }
2229 } else {
2230 // If this is a named struct, check to see if there was a previous forward
2231 // declaration or definition.
2232 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2233 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2234 }
2235
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002236 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002237 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2238 "unexpected Decl type");
2239 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002240 // If this is a use of a previous tag, or if the tag is already declared
2241 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002242 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002243 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002244 // Make sure that this wasn't declared as an enum and now used as a
2245 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002246 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002247 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002248 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002249 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002250 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002251 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002252 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00002253 // If this is a use or a forward declaration, we're good.
2254 if (TK != TK_Definition)
2255 return PrevDecl;
2256
2257 // Diagnose attempts to redefine a tag.
2258 if (PrevTagDecl->isDefinition()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002259 Diag(NameLoc, diag::err_redefinition) << Name;
Chris Lattner14943b92008-07-03 03:30:58 +00002260 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2261 // If this is a redefinition, recover by making this struct be
2262 // anonymous, which will make any later references get the previous
2263 // definition.
2264 Name = 0;
2265 } else {
2266 // Okay, this is definition of a previously declared or referenced
2267 // tag. Move the location of the decl to be the definition site.
2268 PrevDecl->setLocation(NameLoc);
2269 return PrevDecl;
2270 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002271 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002272 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002273 // If we get here, this is a definition of a new struct type in a nested
2274 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2275 // type.
2276 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002277 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002278 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002279 // The tag name clashes with a namespace name, issue an error and
2280 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002281 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002282 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2283 Name = 0;
2284 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002285 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002286 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002287
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002288 CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002289
2290 // If there is an identifier, use the location of the identifier as the
2291 // location of the decl, otherwise use the location of the struct/union
2292 // keyword.
2293 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2294
2295 // Otherwise, if this is the first time we've seen this tag, create the decl.
2296 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002297 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002298 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2299 // enum X { A, B, C } D; D should chain to X.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002300 New = EnumDecl::Create(Context, DC, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002301 // If this is an undefined enum, warn.
2302 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002303 } else {
2304 // struct/union/class
2305
Reid Spencer5f016e22007-07-11 17:01:13 +00002306 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2307 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002308 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002309 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002310 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002311 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002312 New = RecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002313 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002314
2315 // If this has an identifier, add it to the scope stack.
2316 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002317 // The scope passed in may not be a decl scope. Zip up the scope tree until
2318 // we find one that is.
2319 while ((S->getFlags() & Scope::DeclScope) == 0)
2320 S = S->getParent();
2321
2322 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002323 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002324 }
Chris Lattnere1e79852008-02-06 00:51:33 +00002325
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00002326 if (Attr)
2327 ProcessDeclAttributeList(New, Attr);
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002328
2329 // Set the lexical context. If the tag has a C++ scope specifier, the
2330 // lexical context will be different from the semantic context.
2331 New->setLexicalDeclContext(CurContext);
2332
Reid Spencer5f016e22007-07-11 17:01:13 +00002333 return New;
2334}
2335
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002336/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2337/// the logic for enums, we create separate decls for forward declarations.
2338/// This is called by ActOnTag, but eventually will replace its logic.
2339Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002340 SourceLocation KWLoc, const CXXScopeSpec &SS,
2341 IdentifierInfo *Name, SourceLocation NameLoc,
2342 AttributeList *Attr) {
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002343 DeclContext *DC = CurContext;
2344 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002345
2346 if (Name && SS.isNotEmpty()) {
2347 // We have a nested-name tag ('struct foo::bar').
2348
2349 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002350 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002351 Name = 0;
2352 goto CreateNewDecl;
2353 }
2354
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002355 DC = static_cast<DeclContext*>(SS.getScopeRep());
2356 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002357 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2358
2359 // A tag 'foo::bar' must already exist.
2360 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002361 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002362 Name = 0;
2363 goto CreateNewDecl;
2364 }
2365 } else {
2366 // If this is a named struct, check to see if there was a previous forward
2367 // declaration or definition.
2368 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2369 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2370 }
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002371
2372 if (PrevDecl) {
2373 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2374 "unexpected Decl type");
2375
2376 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2377 // If this is a use of a previous tag, or if the tag is already declared
2378 // in the same scope (so that the definition/declaration completes or
2379 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002380 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002381 // Make sure that this wasn't declared as an enum and now used as a
2382 // struct or something similar.
2383 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002384 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002385 Diag(PrevDecl->getLocation(), diag::err_previous_use);
2386 // Recover by making this an anonymous redefinition.
2387 Name = 0;
2388 PrevDecl = 0;
2389 } else {
2390 // If this is a use, return the original decl.
2391
2392 // FIXME: In the future, return a variant or some other clue
2393 // for the consumer of this Decl to know it doesn't own it.
2394 // For our current ASTs this shouldn't be a problem, but will
2395 // need to be changed with DeclGroups.
2396 if (TK == TK_Reference)
2397 return PrevDecl;
2398
2399 // The new decl is a definition?
2400 if (TK == TK_Definition) {
2401 // Diagnose attempts to redefine a tag.
2402 if (RecordDecl* DefRecord =
2403 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002404 Diag(NameLoc, diag::err_redefinition) << Name;
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002405 Diag(DefRecord->getLocation(), diag::err_previous_definition);
2406 // If this is a redefinition, recover by making this struct be
2407 // anonymous, which will make any later references get the previous
2408 // definition.
2409 Name = 0;
2410 PrevDecl = 0;
2411 }
2412 // Okay, this is definition of a previously declared or referenced
2413 // tag. We're going to create a new Decl.
2414 }
2415 }
2416 // If we get here we have (another) forward declaration. Just create
2417 // a new decl.
2418 }
2419 else {
2420 // If we get here, this is a definition of a new struct type in a nested
2421 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2422 // new decl/type. We set PrevDecl to NULL so that the Records
2423 // have distinct types.
2424 PrevDecl = 0;
2425 }
2426 } else {
2427 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002428 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002429 // The tag name clashes with a namespace name, issue an error and
2430 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002431 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002432 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2433 Name = 0;
2434 }
2435 }
2436 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002437
2438 CreateNewDecl:
2439
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002440 // If there is an identifier, use the location of the identifier as the
2441 // location of the decl, otherwise use the location of the struct/union
2442 // keyword.
2443 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2444
2445 // Otherwise, if this is the first time we've seen this tag, create the decl.
2446 TagDecl *New;
2447
2448 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2449 // struct X { int A; } D; D should chain to X.
2450 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002451 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002452 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002453 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2454 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002455 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002456 dyn_cast_or_null<RecordDecl>(PrevDecl));
2457
2458 // If this has an identifier, add it to the scope stack.
2459 if ((TK == TK_Definition || !PrevDecl) && Name) {
2460 // The scope passed in may not be a decl scope. Zip up the scope tree until
2461 // we find one that is.
2462 while ((S->getFlags() & Scope::DeclScope) == 0)
2463 S = S->getParent();
2464
2465 // Add it to the decl chain.
2466 PushOnScopeChains(New, S);
2467 }
Daniel Dunbar3b0db902008-10-16 02:34:03 +00002468
2469 // Handle #pragma pack: if the #pragma pack stack has non-default
2470 // alignment, make up a packed attribute for this decl. These
2471 // attributes are checked when the ASTContext lays out the
2472 // structure.
2473 //
2474 // It is important for implementing the correct semantics that this
2475 // happen here (in act on tag decl). The #pragma pack stack is
2476 // maintained as a result of parser callbacks which can occur at
2477 // many points during the parsing of a struct declaration (because
2478 // the #pragma tokens are effectively skipped over during the
2479 // parsing of the struct).
2480 if (unsigned Alignment = PackContext.getAlignment())
2481 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002482
2483 if (Attr)
2484 ProcessDeclAttributeList(New, Attr);
2485
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002486 // Set the lexical context. If the tag has a C++ scope specifier, the
2487 // lexical context will be different from the semantic context.
2488 New->setLexicalDeclContext(CurContext);
2489
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002490 return New;
2491}
2492
2493
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002494/// Collect the instance variables declared in an Objective-C object. Used in
2495/// the creation of structures from objects using the @defs directive.
Ted Kremenek01e67792008-08-20 03:26:33 +00002496static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002497 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002498 if (Class->getSuperClass())
Ted Kremenek01e67792008-08-20 03:26:33 +00002499 CollectIvars(Class->getSuperClass(), Ctx, ivars);
2500
2501 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremeneka89d1972008-09-03 18:03:35 +00002502 for (ObjCInterfaceDecl::ivar_iterator
2503 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2504
Ted Kremenek01e67792008-08-20 03:26:33 +00002505 ObjCIvarDecl* ID = *I;
2506 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2507 ID->getIdentifier(),
2508 ID->getType(),
2509 ID->getBitWidth()));
2510 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002511}
2512
2513/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2514/// instance variables of ClassName into Decls.
2515void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2516 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002517 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002518 // Check that ClassName is a valid class
2519 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2520 if (!Class) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002521 Diag(DeclStart, diag::err_undef_interface) << ClassName;
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002522 return;
2523 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002524 // Collect the instance variables
Ted Kremenek01e67792008-08-20 03:26:33 +00002525 CollectIvars(Class, Context, Decls);
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002526}
2527
Chris Lattner1d353ba2008-11-12 21:17:48 +00002528/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2529/// types into constant array types in certain situations which would otherwise
2530/// be errors (for GCC compatibility).
2531static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2532 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002533 // This method tries to turn a variable array into a constant
2534 // array even when the size isn't an ICE. This is necessary
2535 // for compatibility with code that depends on gcc's buggy
2536 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00002537 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2538 if (!VLATy) return QualType();
2539
2540 APValue Result;
2541 if (!VLATy->getSizeExpr() ||
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002542 !VLATy->getSizeExpr()->Evaluate(Result, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00002543 return QualType();
2544
2545 assert(Result.isInt() && "Size expressions must be integers!");
2546 llvm::APSInt &Res = Result.getInt();
2547 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2548 return Context.getConstantArrayType(VLATy->getElementType(),
2549 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002550 return QualType();
2551}
2552
Steve Naroff08d92e42007-09-15 18:49:24 +00002553/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002554/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002555Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00002556 SourceLocation DeclStart,
2557 Declarator &D, ExprTy *BitfieldWidth) {
2558 IdentifierInfo *II = D.getIdentifier();
2559 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002560 SourceLocation Loc = DeclStart;
2561 if (II) Loc = D.getIdentifierLoc();
2562
2563 // FIXME: Unnamed fields can be handled in various different ways, for
2564 // example, unnamed unions inject all members into the struct namespace!
Ted Kremeneka89d1972008-09-03 18:03:35 +00002565
Reid Spencer5f016e22007-07-11 17:01:13 +00002566 if (BitWidth) {
2567 // TODO: Validate.
2568 //printf("WARNING: BITFIELDS IGNORED!\n");
2569
2570 // 6.7.2.1p3
2571 // 6.7.2.1p4
2572
2573 } else {
2574 // Not a bitfield.
2575
2576 // validate II.
2577
2578 }
2579
2580 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002581 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2582 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00002583
Reid Spencer5f016e22007-07-11 17:01:13 +00002584 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2585 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002586 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00002587 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002588 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002589 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002590 T = FixedTy;
2591 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002592 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00002593 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002594 InvalidDecl = true;
2595 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002596 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002597 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002598 FieldDecl *NewFD;
2599
2600 if (getLangOptions().CPlusPlus) {
2601 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2602 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
Sebastian Redla11f42f2008-11-17 23:24:37 +00002603 Loc, II, T,
2604 D.getDeclSpec().getStorageClassSpec() ==
2605 DeclSpec::SCS_mutable, BitWidth);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002606 if (II)
2607 PushOnScopeChains(NewFD, S);
2608 }
2609 else
2610 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00002611
Chris Lattner3ff30c82008-06-29 00:02:00 +00002612 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002613
Steve Naroff5912a352007-08-28 20:14:24 +00002614 if (D.getInvalidType() || InvalidDecl)
2615 NewFD->setInvalidDecl();
2616 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002617}
2618
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002619/// TranslateIvarVisibility - Translate visibility from a token ID to an
2620/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002621static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002622TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002623 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002624 default: assert(0 && "Unknown visitibility kind");
2625 case tok::objc_private: return ObjCIvarDecl::Private;
2626 case tok::objc_public: return ObjCIvarDecl::Public;
2627 case tok::objc_protected: return ObjCIvarDecl::Protected;
2628 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002629 }
2630}
2631
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002632/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2633/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002634Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002635 SourceLocation DeclStart,
2636 Declarator &D, ExprTy *BitfieldWidth,
2637 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002638 IdentifierInfo *II = D.getIdentifier();
2639 Expr *BitWidth = (Expr*)BitfieldWidth;
2640 SourceLocation Loc = DeclStart;
2641 if (II) Loc = D.getIdentifierLoc();
2642
2643 // FIXME: Unnamed fields can be handled in various different ways, for
2644 // example, unnamed unions inject all members into the struct namespace!
2645
2646
2647 if (BitWidth) {
2648 // TODO: Validate.
2649 //printf("WARNING: BITFIELDS IGNORED!\n");
2650
2651 // 6.7.2.1p3
2652 // 6.7.2.1p4
2653
2654 } else {
2655 // Not a bitfield.
2656
2657 // validate II.
2658
2659 }
2660
2661 QualType T = GetTypeForDeclarator(D, S);
2662 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2663 bool InvalidDecl = false;
2664
2665 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2666 // than a variably modified type.
2667 if (T->isVariablyModifiedType()) {
2668 // FIXME: This diagnostic needs work
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002669 Diag(Loc, diag::err_typecheck_illegal_vla) << SourceRange(Loc);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002670 InvalidDecl = true;
2671 }
2672
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002673 // Get the visibility (access control) for this ivar.
2674 ObjCIvarDecl::AccessControl ac =
2675 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2676 : ObjCIvarDecl::None;
2677
2678 // Construct the decl.
2679 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002680 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002681
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002682 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002683 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002684
2685 if (D.getInvalidType() || InvalidDecl)
2686 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002687
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002688 return NewID;
2689}
2690
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002691void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002692 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002693 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002694 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002695 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002696 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2697 assert(EnclosingDecl && "missing record or interface decl");
2698 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2699
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002700 if (Record)
2701 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2702 // Diagnose code like:
2703 // struct S { struct S {} X; };
2704 // We discover this when we complete the outer S. Reject and ignore the
2705 // outer S.
2706 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2707 DefRecord->getKindName());
2708 Diag(RecLoc, diag::err_previous_definition);
2709 Record->setInvalidDecl();
2710 return;
2711 }
2712
Reid Spencer5f016e22007-07-11 17:01:13 +00002713 // Verify that all the fields are okay.
2714 unsigned NumNamedMembers = 0;
2715 llvm::SmallVector<FieldDecl*, 32> RecFields;
2716 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002717
Reid Spencer5f016e22007-07-11 17:01:13 +00002718 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002719
Steve Naroff74216642007-09-14 22:20:54 +00002720 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2721 assert(FD && "missing field decl");
2722
2723 // Remember all fields.
2724 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002725
2726 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002727 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002728
Reid Spencer5f016e22007-07-11 17:01:13 +00002729 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002730 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00002731 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00002732 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002733 FD->setInvalidDecl();
2734 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002735 continue;
2736 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2738 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002739 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002740 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002741 FD->setInvalidDecl();
2742 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002743 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002744 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002745 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002746 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002747 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002748 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002749 FD->setInvalidDecl();
2750 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002751 continue;
2752 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002753 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002754 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2755 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002756 FD->setInvalidDecl();
2757 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002758 continue;
2759 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002760 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002761 if (Record)
2762 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002763 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002764 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2765 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002766 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002767 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2768 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002769 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002770 Record->setHasFlexibleArrayMember(true);
2771 } else {
2772 // If this is a struct/class and this is not the last element, reject
2773 // it. Note that GCC supports variable sized arrays in the middle of
2774 // structures.
2775 if (i != NumFields-1) {
2776 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2777 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002778 FD->setInvalidDecl();
2779 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002780 continue;
2781 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002782 // We support flexible arrays at the end of structs in other structs
2783 // as an extension.
2784 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2785 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002786 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002787 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 }
2789 }
2790 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002791 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002792 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002793 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2794 FD->getName());
2795 FD->setInvalidDecl();
2796 EnclosingDecl->setInvalidDecl();
2797 continue;
2798 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002799 // Keep track of the number of named members.
2800 if (IdentifierInfo *II = FD->getIdentifier()) {
2801 // Detect duplicate member names.
2802 if (!FieldIDs.insert(II)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002803 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002804 // Find the previous decl.
2805 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00002806 for (unsigned i = 0; ; ++i) {
2807 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00002808 if (RecFields[i]->getIdentifier() == II) {
2809 PrevLoc = RecFields[i]->getLocation();
2810 break;
2811 }
2812 }
2813 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002814 FD->setInvalidDecl();
2815 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002816 continue;
2817 }
2818 ++NumNamedMembers;
2819 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002820 }
2821
Reid Spencer5f016e22007-07-11 17:01:13 +00002822 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002823 if (Record) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002824 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00002825 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2826 // Sema::ActOnFinishCXXClassDef.
2827 if (!isa<CXXRecordDecl>(Record))
2828 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00002829 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002830 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2831 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2832 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2833 else if (ObjCImplementationDecl *IMPDecl =
2834 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002835 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2836 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002837 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002838 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002839 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00002840
2841 if (Attr)
2842 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002843}
2844
Steve Naroff08d92e42007-09-15 18:49:24 +00002845Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002846 DeclTy *lastEnumConst,
2847 SourceLocation IdLoc, IdentifierInfo *Id,
2848 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002849 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002850 EnumConstantDecl *LastEnumConst =
2851 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2852 Expr *Val = static_cast<Expr*>(val);
2853
Chris Lattner31e05722007-08-26 06:24:45 +00002854 // The scope passed in may not be a decl scope. Zip up the scope tree until
2855 // we find one that is.
2856 while ((S->getFlags() & Scope::DeclScope) == 0)
2857 S = S->getParent();
2858
Reid Spencer5f016e22007-07-11 17:01:13 +00002859 // Verify that there isn't already something declared with this name in this
2860 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002861 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002862 // When in C++, we may get a TagDecl with the same name; in this case the
2863 // enum constant will 'hide' the tag.
2864 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2865 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002866 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002867 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00002868 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00002869 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002870 Diag(IdLoc, diag::err_redefinition) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00002871 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002872 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002873 return 0;
2874 }
2875 }
2876
2877 llvm::APSInt EnumVal(32);
2878 QualType EltTy;
2879 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002880 // Make sure to promote the operand type to int.
2881 UsualUnaryConversions(Val);
2882
Reid Spencer5f016e22007-07-11 17:01:13 +00002883 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2884 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002885 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002886 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr) << Id;
Chris Lattnera73349d2008-02-26 00:33:57 +00002887 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002888 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002889 } else {
2890 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002891 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002892 }
2893
2894 if (!Val) {
2895 if (LastEnumConst) {
2896 // Assign the last value + 1.
2897 EnumVal = LastEnumConst->getInitVal();
2898 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002899
2900 // Check for overflow on increment.
2901 if (EnumVal < LastEnumConst->getInitVal())
2902 Diag(IdLoc, diag::warn_enum_value_overflow);
2903
Chris Lattnerb7416f92007-08-27 17:37:24 +00002904 EltTy = LastEnumConst->getType();
2905 } else {
2906 // First value, set to zero.
2907 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002908 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002909 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002910 }
2911
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002912 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002913 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2914 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002915 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002916
2917 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002918 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002919 return New;
2920}
2921
Steve Naroff02408c62008-08-07 14:08:16 +00002922// FIXME: For consistency with ActOnFields(), we should have the parser
2923// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00002924void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002925 DeclTy **Elements, unsigned NumElements) {
2926 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00002927
Steve Naroff02408c62008-08-07 14:08:16 +00002928 if (Enum && Enum->isDefinition()) {
2929 // Diagnose code like:
2930 // enum e0 {
2931 // E0 = sizeof(enum e0 { E1 })
2932 // };
2933 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2934 Enum->getName());
2935 Diag(EnumLoc, diag::err_previous_definition);
2936 Enum->setInvalidDecl();
2937 return;
2938 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00002939 // TODO: If the result value doesn't fit in an int, it must be a long or long
2940 // long value. ISO C does not support this, but GCC does as an extension,
2941 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002942 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002943
Chris Lattnerac609682007-08-28 06:15:15 +00002944 // Verify that all the values are okay, compute the size of the values, and
2945 // reverse the list.
2946 unsigned NumNegativeBits = 0;
2947 unsigned NumPositiveBits = 0;
2948
2949 // Keep track of whether all elements have type int.
2950 bool AllElementsInt = true;
2951
Reid Spencer5f016e22007-07-11 17:01:13 +00002952 EnumConstantDecl *EltList = 0;
2953 for (unsigned i = 0; i != NumElements; ++i) {
2954 EnumConstantDecl *ECD =
2955 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2956 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002957
2958 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002959 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002960 assert(InitVal.getBitWidth() >= IntWidth &&
2961 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002962 if (InitVal.getBitWidth() > IntWidth) {
2963 llvm::APSInt V(InitVal);
2964 V.trunc(IntWidth);
2965 V.extend(InitVal.getBitWidth());
2966 if (V != InitVal)
2967 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattner9aa77f12008-08-17 07:19:51 +00002968 InitVal.toString(10));
Chris Lattner211a30e2007-08-28 05:27:00 +00002969 }
Chris Lattnerac609682007-08-28 06:15:15 +00002970
2971 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002972 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002973 NumPositiveBits = std::max(NumPositiveBits,
2974 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002975 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002976 NumNegativeBits = std::max(NumNegativeBits,
2977 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002978
Chris Lattnerac609682007-08-28 06:15:15 +00002979 // Keep track of whether every enum element has type int (very commmon).
2980 if (AllElementsInt)
2981 AllElementsInt = ECD->getType() == Context.IntTy;
2982
Reid Spencer5f016e22007-07-11 17:01:13 +00002983 ECD->setNextDeclarator(EltList);
2984 EltList = ECD;
2985 }
2986
Chris Lattnerac609682007-08-28 06:15:15 +00002987 // Figure out the type that should be used for this enum.
2988 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2989 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002990 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002991
2992 if (NumNegativeBits) {
2993 // If there is a negative value, figure out the smallest integer type (of
2994 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002995 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002996 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002997 BestWidth = IntWidth;
2998 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002999 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003000
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003001 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003002 BestType = Context.LongTy;
3003 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003004 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003005
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003006 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003007 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3008 BestType = Context.LongLongTy;
3009 }
3010 }
3011 } else {
3012 // If there is no negative value, figure out which of uint, ulong, ulonglong
3013 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003014 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003015 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003016 BestWidth = IntWidth;
3017 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003018 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003019 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003020 } else {
3021 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003022 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003023 "How could an initializer get larger than ULL?");
3024 BestType = Context.UnsignedLongLongTy;
3025 }
3026 }
3027
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003028 // Loop over all of the enumerator constants, changing their types to match
3029 // the type of the enum if needed.
3030 for (unsigned i = 0; i != NumElements; ++i) {
3031 EnumConstantDecl *ECD =
3032 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3033 if (!ECD) continue; // Already issued a diagnostic.
3034
3035 // Standard C says the enumerators have int type, but we allow, as an
3036 // extension, the enumerators to be larger than int size. If each
3037 // enumerator value fits in an int, type it as an int, otherwise type it the
3038 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3039 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003040 if (ECD->getType() == Context.IntTy) {
3041 // Make sure the init value is signed.
3042 llvm::APSInt IV = ECD->getInitVal();
3043 IV.setIsSigned(true);
3044 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003045 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003046 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003047
3048 // Determine whether the value fits into an int.
3049 llvm::APSInt InitVal = ECD->getInitVal();
3050 bool FitsInInt;
3051 if (InitVal.isUnsigned() || !InitVal.isNegative())
3052 FitsInInt = InitVal.getActiveBits() < IntWidth;
3053 else
3054 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3055
3056 // If it fits into an integer type, force it. Otherwise force it to match
3057 // the enum decl type.
3058 QualType NewTy;
3059 unsigned NewWidth;
3060 bool NewSign;
3061 if (FitsInInt) {
3062 NewTy = Context.IntTy;
3063 NewWidth = IntWidth;
3064 NewSign = true;
3065 } else if (ECD->getType() == BestType) {
3066 // Already the right type!
3067 continue;
3068 } else {
3069 NewTy = BestType;
3070 NewWidth = BestWidth;
3071 NewSign = BestType->isSignedIntegerType();
3072 }
3073
3074 // Adjust the APSInt value.
3075 InitVal.extOrTrunc(NewWidth);
3076 InitVal.setIsSigned(NewSign);
3077 ECD->setInitVal(InitVal);
3078
3079 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003080 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3081 /*isLvalue=*/false));
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003082 ECD->setType(NewTy);
3083 }
Chris Lattnerac609682007-08-28 06:15:15 +00003084
Chris Lattnere00b18c2007-08-28 18:24:31 +00003085 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003086 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003087}
3088
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003089Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3090 ExprTy *expr) {
3091 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
3092
Chris Lattner8e25d862008-03-16 00:16:02 +00003093 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003094}
3095
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003096Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00003097 SourceLocation LBrace,
3098 SourceLocation RBrace,
3099 const char *Lang,
3100 unsigned StrSize,
3101 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003102 LinkageSpecDecl::LanguageIDs Language;
3103 Decl *dcl = static_cast<Decl *>(D);
3104 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3105 Language = LinkageSpecDecl::lang_c;
3106 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3107 Language = LinkageSpecDecl::lang_cxx;
3108 else {
3109 Diag(Loc, diag::err_bad_language);
3110 return 0;
3111 }
3112
3113 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00003114 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003115}
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003116
3117void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3118 ExprTy *alignment, SourceLocation PragmaLoc,
3119 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3120 Expr *Alignment = static_cast<Expr *>(alignment);
3121
3122 // If specified then alignment must be a "small" power of two.
3123 unsigned AlignmentVal = 0;
3124 if (Alignment) {
3125 llvm::APSInt Val;
3126 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3127 !Val.isPowerOf2() ||
3128 Val.getZExtValue() > 16) {
3129 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3130 delete Alignment;
3131 return; // Ignore
3132 }
3133
3134 AlignmentVal = (unsigned) Val.getZExtValue();
3135 }
3136
3137 switch (Kind) {
3138 case Action::PPK_Default: // pack([n])
3139 PackContext.setAlignment(AlignmentVal);
3140 break;
3141
3142 case Action::PPK_Show: // pack(show)
3143 // Show the current alignment, making sure to show the right value
3144 // for the default.
3145 AlignmentVal = PackContext.getAlignment();
3146 // FIXME: This should come from the target.
3147 if (AlignmentVal == 0)
3148 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003149 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003150 break;
3151
3152 case Action::PPK_Push: // pack(push [, id] [, [n])
3153 PackContext.push(Name);
3154 // Set the new alignment if specified.
3155 if (Alignment)
3156 PackContext.setAlignment(AlignmentVal);
3157 break;
3158
3159 case Action::PPK_Pop: // pack(pop [, id] [, n])
3160 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3161 // "#pragma pack(pop, identifier, n) is undefined"
3162 if (Alignment && Name)
3163 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3164
3165 // Do the pop.
3166 if (!PackContext.pop(Name)) {
3167 // If a name was specified then failure indicates the name
3168 // wasn't found. Otherwise failure indicates the stack was
3169 // empty.
3170 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
3171 Name ? "no record matching name" : "stack empty");
3172
3173 // FIXME: Warn about popping named records as MSVC does.
3174 } else {
3175 // Pop succeeded, set the new alignment if specified.
3176 if (Alignment)
3177 PackContext.setAlignment(AlignmentVal);
3178 }
3179 break;
3180
3181 default:
3182 assert(0 && "Invalid #pragma pack kind.");
3183 }
3184}
3185
3186bool PragmaPackStack::pop(IdentifierInfo *Name) {
3187 if (Stack.empty())
3188 return false;
3189
3190 // If name is empty just pop top.
3191 if (!Name) {
3192 Alignment = Stack.back().first;
3193 Stack.pop_back();
3194 return true;
3195 }
3196
3197 // Otherwise, find the named record.
3198 for (unsigned i = Stack.size(); i != 0; ) {
3199 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003200 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003201 // Found it, pop up to and including this record.
3202 Alignment = Stack[i].first;
3203 Stack.erase(Stack.begin() + i, Stack.end());
3204 return true;
3205 }
3206 }
3207
3208 return false;
3209}