blob: 48073694a32c3254ff9a9aeb7c15558c9f7f3f32 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6953a072008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallSet.h"
Daniel Dunbar81c7d472008-10-14 05:35:18 +000028#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000031Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S,
32 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000033 DeclContext *DC = 0;
34 if (SS) {
35 if (SS->isInvalid())
36 return 0;
37 DC = static_cast<DeclContext*>(SS->getScopeRep());
38 }
39 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroff6384a012008-04-02 14:35:35 +000040
Douglas Gregor1d661552008-04-13 21:07:44 +000041 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
42 isa<ObjCInterfaceDecl>(IIDecl) ||
43 isa<TagDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000044 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000045 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000046}
47
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000048DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000049 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000050 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000051 if (MD->isOutOfLineDefinition())
52 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000053
54 // A C++ inline method is parsed *after* the topmost class it was declared in
55 // is fully parsed (it's "complete").
56 // The parsing of a C++ inline method happens at the declaration context of
57 // the topmost (non-nested) class it is declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000058 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
59 DC = MD->getParent();
60 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
61 DC = RD;
62
63 // Return the declaration context of the topmost class the inline method is
64 // declared in.
65 return DC;
66 }
67
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000068 if (isa<ObjCMethodDecl>(DC))
69 return Context.getTranslationUnitDecl();
70
71 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
72 return SD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000073
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000074 return DC->getParent();
75}
76
Chris Lattneref87a202008-04-22 18:39:57 +000077void Sema::PushDeclContext(DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000078 assert(getContainingDC(DC) == CurContext &&
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000079 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000080 CurContext = DC;
Chris Lattnereee57c02008-04-04 06:12:32 +000081}
82
Chris Lattnerf3874bc2008-04-06 04:47:34 +000083void Sema::PopDeclContext() {
84 assert(CurContext && "DeclContext imbalance!");
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000085 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +000086}
87
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000088/// Add this decl to the scope shadowed decl chains.
89void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000090 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000091
92 // C++ [basic.scope]p4:
93 // -- exactly one declaration shall declare a class name or
94 // enumeration name that is not a typedef name and the other
95 // declarations shall all refer to the same object or
96 // enumerator, or all refer to functions and function templates;
97 // in this case the class name or enumeration name is hidden.
98 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
99 // We are pushing the name of a tag (enum or class).
Argiris Kirtzidis94805232008-07-17 17:49:50 +0000100 IdentifierResolver::iterator
101 I = IdResolver.begin(TD->getIdentifier(),
102 TD->getDeclContext(), false/*LookInParentCtx*/);
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000103 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000104 // There is already a declaration with the same name in the same
105 // scope. It must be found before we find the new declaration,
106 // so swap the order on the shadowed declaration chain.
107
Argiris Kirtzidis94805232008-07-17 17:49:50 +0000108 IdResolver.AddShadowedDecl(TD, *I);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000109 return;
110 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000111 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
112 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000113 // We are pushing the name of a function, which might be an
114 // overloaded name.
115 IdentifierResolver::iterator
116 I = IdResolver.begin(FD->getIdentifier(),
117 FD->getDeclContext(), false/*LookInParentCtx*/);
118 if (I != IdResolver.end() &&
119 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
120 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
121 // There is already a declaration with the same name in the same
122 // scope. It must be a function or an overloaded function.
123 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
124 if (!Ovl) {
125 // We haven't yet overloaded this function. Take the existing
126 // FunctionDecl and put it into an OverloadedFunctionDecl.
127 Ovl = OverloadedFunctionDecl::Create(Context,
128 FD->getDeclContext(),
129 FD->getIdentifier());
130 Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
131
132 // Remove the name binding to the existing FunctionDecl...
133 IdResolver.RemoveDecl(*I);
134
135 // ... and put the OverloadedFunctionDecl in its place.
136 IdResolver.AddDecl(Ovl);
137 }
138
139 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
140 // to its list of overloads.
141 Ovl->addOverload(FD);
142
143 return;
144 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000145 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000146
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000147 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000148}
149
Steve Naroff9637a9b2007-10-09 22:01:59 +0000150void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000151 if (S->decl_empty()) return;
152 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000153
Chris Lattner4b009652007-07-25 00:24:17 +0000154 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
155 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000156 Decl *TmpD = static_cast<Decl*>(*I);
157 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000158
159 if (isa<CXXFieldDecl>(TmpD)) continue;
160
161 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
162 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000163
Chris Lattner4b009652007-07-25 00:24:17 +0000164 IdentifierInfo *II = D->getIdentifier();
165 if (!II) continue;
166
Ted Kremenek40e70e72008-09-03 18:03:35 +0000167 // We only want to remove the decls from the identifier decl chains for
168 // local scopes, when inside a function/method.
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000169 if (S->getFnParent() != 0)
170 IdResolver.RemoveDecl(D);
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000171
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000172 // Chain this decl to the containing DeclContext.
173 D->setNext(CurContext->getDeclChain());
174 CurContext->setDeclChain(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000175 }
176}
177
Steve Naroffe57c21a2008-04-01 23:04:06 +0000178/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
179/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000180ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000181 // The third "scope" argument is 0 since we aren't enabling lazy built-in
182 // creation from this context.
183 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000184
Steve Naroff6384a012008-04-02 14:35:35 +0000185 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000186}
187
Steve Naroffe57c21a2008-04-01 23:04:06 +0000188/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000189/// namespace.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000190Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI, Scope *S,
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000191 const DeclContext *LookupCtx,
192 bool enableLazyBuiltinCreation) {
Chris Lattner4b009652007-07-25 00:24:17 +0000193 if (II == 0) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000194 unsigned NS = NSI;
195 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
196 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000197
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000198 IdentifierResolver::iterator
199 I = LookupCtx ? IdResolver.begin(II, LookupCtx, false/*LookInParentCtx*/) :
200 IdResolver.begin(II, CurContext, true/*LookInParentCtx*/);
Chris Lattner4b009652007-07-25 00:24:17 +0000201 // Scan up the scope chain looking for a decl that matches this identifier
202 // that is in the appropriate namespace. This search should not take long, as
203 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000204 for (; I != IdResolver.end(); ++I)
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000205 if ((*I)->getIdentifierNamespace() & NS)
206 return *I;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000207
Chris Lattner4b009652007-07-25 00:24:17 +0000208 // If we didn't find a use of this identifier, and if the identifier
209 // corresponds to a compiler builtin, create the decl object for the builtin
210 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000211 if (NS & Decl::IDNS_Ordinary) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000212 if (enableLazyBuiltinCreation &&
213 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroff6384a012008-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 }
Steve Naroffe57c21a2008-04-01 23:04:06 +0000218 if (getLangOptions().ObjC1) {
219 // @interface and @compatibility_alias introduce typedef-like names.
220 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000221 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000222 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000223 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
224 if (IDI != ObjCInterfaceDecls.end())
225 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000226 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
227 if (I != ObjCAliasDecls.end())
228 return I->second->getClassInterface();
229 }
Chris Lattner4b009652007-07-25 00:24:17 +0000230 }
231 return 0;
232}
233
Chris Lattnera9c87f22008-05-05 22:18:14 +0000234void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000235 if (!Context.getBuiltinVaListType().isNull())
236 return;
237
238 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000239 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000240 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000241 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
242}
243
Chris Lattner4b009652007-07-25 00:24:17 +0000244/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
245/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000246ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
247 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000248 Builtin::ID BID = (Builtin::ID)bid;
249
Chris Lattnerb23469f2008-09-28 05:54:29 +0000250 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000251 InitBuiltinVaListType();
252
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000253 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000254 FunctionDecl *New = FunctionDecl::Create(Context,
255 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000256 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000257 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000258
Chris Lattnera9c87f22008-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 Lattner2a1e2ed2008-04-11 07:00:53 +0000272 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000273 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000274 return New;
275}
276
Sebastian Redlb93b49c2008-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
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffe57c21a2008-04-01 23:04:06 +0000293TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff453a8782008-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 }
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnerbef8d622008-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 Friedman324d5032008-06-11 06:20:39 +0000334 if (getLangOptions().Microsoft) return New;
335
Steve Naroffa9eae582008-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 Dunbar4dbd8572008-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 Friedman324d5032008-06-11 06:20:39 +0000348
Ted Kremenek64845ce2008-05-23 21:28:18 +0000349 Diag(New->getLocation(), diag::err_redefinition, New->getName());
350 Diag(Old->getLocation(), diag::err_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000351 return New;
352}
353
Chris Lattner6953a072008-06-26 18:38:35 +0000354/// DeclhasAttr - returns true if decl Declaration already has the target
355/// attribute.
Chris Lattner402b3372008-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 Lattner402b3372008-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 Lopes77654342008-06-01 22:53:53 +0000379
380 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000381}
382
Chris Lattner3e254fb2008-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 Gregord2baafd2008-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 Gregor42214c52008-04-21 02:02:58 +0000393FunctionDecl *
394Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000395 assert(!isa<OverloadedFunctionDecl>(OldD) &&
396 "Cannot merge with an overloaded function declaration");
397
Douglas Gregor42214c52008-04-21 02:02:58 +0000398 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +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 Gregord2baafd2008-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 Lattner3e254fb2008-04-08 04:40:51 +0000417
Chris Lattner42a21742008-04-06 23:10:54 +0000418 QualType OldQType = Context.getCanonicalType(Old->getType());
419 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000420
Douglas Gregord2baafd2008-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 Gregor42214c52008-04-21 02:02:58 +0000460 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000461
462 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000463 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000464 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000465 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000466 MergeAttributes(New, Old);
467 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000468 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000469 }
Chris Lattner1470b072007-11-06 06:07:26 +0000470
Steve Naroff6c9e7922008-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 Naroff6c9e7922008-01-16 15:01:34 +0000473
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroff6c9e7922008-01-16 15:01:34 +0000477 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
478 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000479 return New;
480}
481
Steve Naroffb5e78152008-08-08 17:50:35 +0000482/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000483static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-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 Naroff4b6bd3c2008-08-10 15:20:13 +0000495 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-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) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000501 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000502 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
503
Steve Naroff4b6bd3c2008-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 Naroffb5e78152008-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
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffb5e78152008-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.
Chris Lattner4b009652007-07-25 00:24:17 +0000536///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000537VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner402b3372008-03-03 03:28:21 +0000546
547 MergeAttributes(New, Old);
548
Chris Lattner4b009652007-07-25 00:24:17 +0000549 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000550 QualType OldCType = Context.getCanonicalType(Old->getType());
551 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000552 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000553 Diag(New->getLocation(), diag::err_redefinition, New->getName());
554 Diag(Old->getLocation(), diag::err_previous_definition);
555 return New;
556 }
Steve Naroffb00247f2008-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 Naroff2f3c4432008-09-17 14:05:40 +0000572 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
573 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000574 Diag(New->getLocation(), diag::err_redefinition, New->getName());
575 Diag(Old->getLocation(), diag::err_previous_definition);
576 }
577 return New;
578}
579
Chris Lattner3e254fb2008-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
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffedafc0b2007-11-17 21:37:36 +0000612 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000613}
614
Steve Narofff0b23542008-01-10 22:15:12 +0000615bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000616 // Get the type before calling CheckSingleAssignmentConstraints(), since
617 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000618 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000619
Chris Lattner005ed752008-01-04 18:04:52 +0000620 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
621 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
622 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000623}
624
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000625bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000626 const ArrayType *AT = Context.getAsArrayType(DeclT);
627
628 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-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 Friedman8ff07782008-02-15 18:16:39 +0000634 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000635 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000636 } else {
637 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000638 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000639 // FIXME: Avoid truncation for 64-bit length strings.
640 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000641 Diag(strLiteral->getSourceRange().getBegin(),
642 diag::warn_initializer_string_for_char_array_too_long,
643 strLiteral->getSourceRange());
Steve Naroff0d4e6ad2008-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 Lattnera1923f62008-08-04 07:31:14 +0000652 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +0000653 if (AT && AT->getElementType()->isCharType()) {
654 return dyn_cast<StringLiteral>(Init);
655 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000656 return 0;
657}
658
Douglas Gregor6428e762008-11-05 15:29:30 +0000659bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
660 SourceLocation InitLoc,
661 std::string InitEntity) {
Douglas Gregor81c29152008-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 Naroff8e9337f2008-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 Lattnera1923f62008-08-04 07:31:14 +0000671 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Douglas Gregor6428e762008-11-05 15:29:30 +0000672 return Diag(InitLoc,
Steve Naroff8e9337f2008-01-21 23:53:58 +0000673 diag::err_variable_object_no_init,
674 VAT->getSizeExpr()->getSourceRange());
675
Steve Naroffcb69fb72007-12-10 22:44:33 +0000676 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
677 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000678 // FIXME: Handle wide strings
679 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
680 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000681
Douglas Gregor6428e762008-11-05 15:29:30 +0000682 // C++ [dcl.init]p14:
683 // -- If the destination type is a (possibly cv-qualified) class
684 // type:
685 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
686 QualType DeclTypeC = Context.getCanonicalType(DeclType);
687 QualType InitTypeC = Context.getCanonicalType(Init->getType());
688
689 // -- If the initialization is direct-initialization, or if it is
690 // copy-initialization where the cv-unqualified version of the
691 // source type is the same class as, or a derived class of, the
692 // class of the destination, constructors are considered.
693 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
694 IsDerivedFrom(InitTypeC, DeclTypeC)) {
695 CXXConstructorDecl *Constructor
696 = PerformInitializationByConstructor(DeclType, &Init, 1,
697 InitLoc, Init->getSourceRange(),
698 InitEntity, IK_Copy);
699 return Constructor == 0;
700 }
701
702 // -- Otherwise (i.e., for the remaining copy-initialization
703 // cases), user-defined conversion sequences that can
704 // convert from the source type to the destination type or
705 // (when a conversion function is used) to a derived class
706 // thereof are enumerated as described in 13.3.1.4, and the
707 // best one is chosen through overload resolution
708 // (13.3). If the conversion cannot be done or is
709 // ambiguous, the initialization is ill-formed. The
710 // function selected is called with the initializer
711 // expression as its argument; if the function is a
712 // constructor, the call initializes a temporary of the
713 // destination type.
714 // FIXME: We're pretending to do copy elision here; return to
715 // this when we have ASTs for such things.
716 if (PerformImplicitConversion(Init, DeclType))
717 return Diag(InitLoc,
718 diag::err_typecheck_convert_incompatible,
719 DeclType.getAsString(), InitEntity,
720 "initializing",
721 Init->getSourceRange());
722 else
723 return false;
724 }
725
Steve Naroffb2f72412008-09-29 20:07:05 +0000726 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +0000727 if (DeclType->isArrayType())
728 return Diag(Init->getLocStart(),
729 diag::err_array_init_list_required,
730 Init->getSourceRange());
731
Steve Narofff0b23542008-01-10 22:15:12 +0000732 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor15e04622008-11-05 16:20:31 +0000733 } else if (getLangOptions().CPlusPlus) {
734 // C++ [dcl.init]p14:
735 // [...] If the class is an aggregate (8.5.1), and the initializer
736 // is a brace-enclosed list, see 8.5.1.
737 //
738 // Note: 8.5.1 is handled below; here, we diagnose the case where
739 // we have an initializer list and a destination type that is not
740 // an aggregate.
741 // FIXME: In C++0x, this is yet another form of initialization.
742 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
743 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
744 if (!ClassDecl->isAggregate())
745 return Diag(InitLoc,
746 diag::err_init_non_aggr_init_list,
747 DeclType.getAsString(),
748 Init->getSourceRange());
749 }
Steve Naroffcb69fb72007-12-10 22:44:33 +0000750 }
Eli Friedman38b7a912008-06-06 19:40:52 +0000751
Steve Naroffc4d4a482008-05-01 22:18:59 +0000752 InitListChecker CheckInitList(this, InitList, DeclType);
753 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +0000754}
755
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000756Sema::DeclTy *
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000757Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000758 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000759 IdentifierInfo *II = D.getIdentifier();
760
761 // All of these full declarators require an identifier. If it doesn't have
762 // one, the ParsedFreeStandingDeclSpec action should be used.
763 if (II == 0) {
Chris Lattnercd61d592008-11-11 06:13:16 +0000764 if (!D.getInvalidType()) // Reject this if we think it is valid.
765 Diag(D.getDeclSpec().getSourceRange().getBegin(),
766 diag::err_declarator_need_ident,
767 D.getDeclSpec().getSourceRange(), D.getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000768 return 0;
769 }
770
Chris Lattnera7549902007-08-26 06:24:45 +0000771 // The scope passed in may not be a decl scope. Zip up the scope tree until
772 // we find one that is.
773 while ((S->getFlags() & Scope::DeclScope) == 0)
774 S = S->getParent();
775
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000776 DeclContext *DC;
777 Decl *PrevDecl;
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000778 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000779 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000780
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000781 // See if this is a redefinition of a variable in the same scope.
782 if (!D.getCXXScopeSpec().isSet()) {
783 DC = CurContext;
784 PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
785 } else { // Something like "int foo::x;"
786 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
787 PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S, DC);
788
789 // C++ 7.3.1.2p2:
790 // Members (including explicit specializations of templates) of a named
791 // namespace can also be defined outside that namespace by explicit
792 // qualification of the name being defined, provided that the entity being
793 // defined was already declared in the namespace and the definition appears
794 // after the point of declaration in a namespace that encloses the
795 // declarations namespace.
796 //
797 if (PrevDecl == 0) {
798 // No previous declaration in the qualifying scope.
799 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member,
800 II->getName(), D.getCXXScopeSpec().getRange());
801 } else if (!CurContext->Encloses(DC)) {
802 // The qualifying scope doesn't enclose the original declaration.
803 // Emit diagnostic based on current scope.
804 SourceLocation L = D.getIdentifierLoc();
805 SourceRange R = D.getCXXScopeSpec().getRange();
806 if (isa<FunctionDecl>(CurContext)) {
807 Diag(L, diag::err_invalid_declarator_in_function, II->getName(), R);
808 } else {
809 Diag(L, diag::err_invalid_declarator_scope, II->getName(),
810 cast<NamedDecl>(DC)->getName(), R);
811 }
812 }
813 }
814
Douglas Gregor1d661552008-04-13 21:07:44 +0000815 // In C++, the previous declaration we find might be a tag type
816 // (class or enum). In this case, the new declaration will hide the
817 // tag type.
818 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
819 PrevDecl = 0;
820
Chris Lattner82bb4792007-11-14 06:34:38 +0000821 QualType R = GetTypeForDeclarator(D, S);
822 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
823
Chris Lattner4b009652007-07-25 00:24:17 +0000824 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000825 // Check that there are no default arguments (C++ only).
826 if (getLangOptions().CPlusPlus)
827 CheckExtraCXXDefaultArguments(D);
828
Chris Lattner82bb4792007-11-14 06:34:38 +0000829 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000830 if (!NewTD) return 0;
831
832 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000833 ProcessDeclAttributes(NewTD, D);
Steve Narofff8a09432008-01-09 23:34:55 +0000834 // Merge the decl with the existing one if appropriate. If the decl is
835 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000836 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000837 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
838 if (NewTD == 0) return 0;
839 }
840 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000841 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000842 // C99 6.7.7p2: If a typedef name specifies a variably modified type
843 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000844 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
845 // FIXME: Diagnostic needs to be fixed.
846 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000847 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000848 }
849 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000850 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000851 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000852 switch (D.getDeclSpec().getStorageClassSpec()) {
853 default: assert(0 && "Unknown storage class!");
854 case DeclSpec::SCS_auto:
855 case DeclSpec::SCS_register:
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000856 case DeclSpec::SCS_mutable:
Chris Lattner4b009652007-07-25 00:24:17 +0000857 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
858 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000859 InvalidDecl = true;
860 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000861 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
862 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
863 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000864 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000865 }
866
Chris Lattner4c7802b2008-03-15 21:24:04 +0000867 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000868 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000869 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
870
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000871 FunctionDecl *NewFD;
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000872 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000873 // This is a C++ constructor declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000874 assert(DC->isCXXRecord() &&
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000875 "Constructors can only be declared in a member context");
876
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000877 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000878
879 // Create the new declaration
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000880 QualType ClassType = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
881 ClassType = Context.getCanonicalType(ClassType);
882 DeclarationName ConName
883 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000884 NewFD = CXXConstructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000885 cast<CXXRecordDecl>(DC),
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000886 D.getIdentifierLoc(), ConName, R,
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000887 isExplicit, isInline,
888 /*isImplicitlyDeclared=*/false);
889
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000890 if (isInvalidDecl)
891 NewFD->setInvalidDecl();
892 } else if (D.getKind() == Declarator::DK_Destructor) {
893 // This is a C++ destructor declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000894 if (DC->isCXXRecord()) {
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000895 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000896
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000897 QualType ClassType = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
898 ClassType = Context.getCanonicalType(ClassType);
899 DeclarationName DesName
900 = Context.DeclarationNames.getCXXDestructorName(ClassType);
901
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000902 NewFD = CXXDestructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000903 cast<CXXRecordDecl>(DC),
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000904 D.getIdentifierLoc(), DesName, R,
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000905 isInline,
906 /*isImplicitlyDeclared=*/false);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000907
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000908 if (isInvalidDecl)
909 NewFD->setInvalidDecl();
910 } else {
911 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
912 // Create a FunctionDecl to satisfy the function definition parsing
913 // code path.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000914 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000915 II, R, SC, isInline, LastDeclarator,
916 // FIXME: Move to DeclGroup...
917 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000918 NewFD->setInvalidDecl();
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000919 }
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000920 } else if (D.getKind() == Declarator::DK_Conversion) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000921 if (!DC->isCXXRecord()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000922 Diag(D.getIdentifierLoc(),
923 diag::err_conv_function_not_member);
924 return 0;
925 } else {
926 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
927
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000928 QualType ConvType = R->getAsFunctionType()->getResultType();
929 ConvType = Context.getCanonicalType(ConvType);
930 DeclarationName ConvName
931 = Context.DeclarationNames.getCXXConversionFunctionName(ConvType);
932
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000933 NewFD = CXXConversionDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000934 cast<CXXRecordDecl>(DC),
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000935 D.getIdentifierLoc(), ConvName, R,
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000936 isInline, isExplicit);
937
938 if (isInvalidDecl)
939 NewFD->setInvalidDecl();
940 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000941 } else if (DC->isCXXRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000942 // This is a C++ method declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000943 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000944 D.getIdentifierLoc(), II, R,
945 (SC == FunctionDecl::Static), isInline,
946 LastDeclarator);
947 } else {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000948 NewFD = FunctionDecl::Create(Context, DC,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000949 D.getIdentifierLoc(),
Steve Naroff71cd7762008-10-03 00:02:03 +0000950 II, R, SC, isInline, LastDeclarator,
951 // FIXME: Move to DeclGroup...
952 D.getDeclSpec().getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000953 }
Ted Kremenek117f1862008-02-27 22:18:07 +0000954 // Handle attributes.
Chris Lattner9b384ca2008-06-29 00:02:00 +0000955 ProcessDeclAttributes(NewFD, D);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000956
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000957 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000958 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000959 // The parser guarantees this is a string.
960 StringLiteral *SE = cast<StringLiteral>(E);
961 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
962 SE->getByteLength())));
963 }
964
Chris Lattner3e254fb2008-04-08 04:40:51 +0000965 // Copy the parameter declarations from the declarator D to
966 // the function declaration NewFD, if they are available.
Eli Friedman769e7302008-08-25 21:31:01 +0000967 if (D.getNumTypeObjects() > 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000968 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
969
970 // Create Decl objects for each parameter, adding them to the
971 // FunctionDecl.
972 llvm::SmallVector<ParmVarDecl*, 16> Params;
973
974 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
975 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +0000976 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +0000977 // We let through "const void" here because Sema::GetTypeForDeclarator
978 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000979 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
980 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +0000981 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
982 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +0000983 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
984
Chris Lattnerda7b5f02008-04-10 02:26:16 +0000985 // In C++, the empty parameter-type-list must be spelled "void"; a
986 // typedef of void is not permitted.
987 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +0000988 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +0000989 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
990 }
Eli Friedman769e7302008-08-25 21:31:01 +0000991 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000992 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
993 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
994 }
995
996 NewFD->setParams(&Params[0], Params.size());
Douglas Gregorba3e8b72008-10-24 18:09:54 +0000997 } else if (R->getAsTypedefType()) {
998 // When we're declaring a function with a typedef, as in the
999 // following example, we'll need to synthesize (unnamed)
1000 // parameters for use in the declaration.
1001 //
1002 // @code
1003 // typedef void fn(int);
1004 // fn f;
1005 // @endcode
1006 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1007 if (!FT) {
1008 // This is a typedef of a function with no prototype, so we
1009 // don't need to do anything.
1010 } else if ((FT->getNumArgs() == 0) ||
1011 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1012 FT->getArgType(0)->isVoidType())) {
1013 // This is a zero-argument function. We don't need to do anything.
1014 } else {
1015 // Synthesize a parameter for each argument type.
1016 llvm::SmallVector<ParmVarDecl*, 16> Params;
1017 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1018 ArgType != FT->arg_type_end(); ++ArgType) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001019 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregorba3e8b72008-10-24 18:09:54 +00001020 SourceLocation(), 0,
1021 *ArgType, VarDecl::None,
1022 0, 0));
1023 }
1024
1025 NewFD->setParams(&Params[0], Params.size());
1026 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001027 }
1028
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001029 // C++ constructors and destructors are handled by separate
1030 // routines, since they don't require any declaration merging (C++
1031 // [class.mfct]p2) and they aren't ever pushed into scope, because
1032 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1033 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1034 return ActOnConstructorDeclarator(Constructor);
1035 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1036 return ActOnDestructorDeclarator(Destructor);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001037 else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1038 return ActOnConversionDeclarator(Conversion);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001039
Douglas Gregore60e5d32008-11-06 22:13:31 +00001040 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1041 if (NewFD->isOverloadedOperator() &&
1042 CheckOverloadedOperatorDeclaration(NewFD))
1043 NewFD->setInvalidDecl();
1044
Steve Narofff8a09432008-01-09 23:34:55 +00001045 // Merge the decl with the existing one if appropriate. Since C functions
1046 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001047 if (PrevDecl &&
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001048 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregor42214c52008-04-21 02:02:58 +00001049 bool Redeclaration = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001050
1051 // If C++, determine whether NewFD is an overload of PrevDecl or
1052 // a declaration that requires merging. If it's an overload,
1053 // there's no more work to do here; we'll just add the new
1054 // function to the scope.
1055 OverloadedFunctionDecl::function_iterator MatchedDecl;
1056 if (!getLangOptions().CPlusPlus ||
1057 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1058 Decl *OldDecl = PrevDecl;
1059
1060 // If PrevDecl was an overloaded function, extract the
1061 // FunctionDecl that matched.
1062 if (isa<OverloadedFunctionDecl>(PrevDecl))
1063 OldDecl = *MatchedDecl;
1064
1065 // NewFD and PrevDecl represent declarations that need to be
1066 // merged.
1067 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1068
1069 if (NewFD == 0) return 0;
1070 if (Redeclaration) {
1071 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1072
1073 if (OldDecl == PrevDecl) {
1074 // Remove the name binding for the previous
1075 // declaration. We'll add the binding back later, but then
1076 // it will refer to the new declaration (which will
1077 // contain more information).
1078 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1079 } else {
1080 // We need to update the OverloadedFunctionDecl with the
1081 // latest declaration of this function, so that name
1082 // lookup will always refer to the latest declaration of
1083 // this function.
1084 *MatchedDecl = NewFD;
1085
1086 // Add the redeclaration to the current scope, since we'll
1087 // be skipping PushOnScopeChains.
1088 S->AddDecl(NewFD);
1089
1090 return NewFD;
1091 }
1092 }
Douglas Gregor42214c52008-04-21 02:02:58 +00001093 }
Chris Lattner4b009652007-07-25 00:24:17 +00001094 }
1095 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001096
1097 // In C++, check default arguments now that we have merged decls.
1098 if (getLangOptions().CPlusPlus)
1099 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +00001100 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001101 // Check that there are no default arguments (C++ only).
1102 if (getLangOptions().CPlusPlus)
1103 CheckExtraCXXDefaultArguments(D);
1104
Ted Kremenek42730c52008-01-07 19:49:32 +00001105 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001106 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
1107 D.getIdentifier()->getName());
1108 InvalidDecl = true;
1109 }
Chris Lattner4b009652007-07-25 00:24:17 +00001110
1111 VarDecl *NewVD;
1112 VarDecl::StorageClass SC;
1113 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +00001114 default: assert(0 && "Unknown storage class!");
1115 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1116 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1117 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1118 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1119 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1120 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001121 case DeclSpec::SCS_mutable:
1122 // mutable can only appear on non-static class members, so it's always
1123 // an error here
1124 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1125 InvalidDecl = true;
1126 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001127 if (DC->isCXXRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001128 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1129 // This is a static data member for a C++ class.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001130 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001131 D.getIdentifierLoc(), II,
1132 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +00001133 } else {
Daniel Dunbar5eea5622008-09-08 20:05:47 +00001134 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001135 if (S->getFnParent() == 0) {
1136 // C99 6.9p2: The storage-class specifiers auto and register shall not
1137 // appear in the declaration specifiers in an external declaration.
1138 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1139 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
1140 R.getAsString());
1141 InvalidDecl = true;
1142 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001143 }
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001144 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1145 II, R, SC, LastDeclarator,
1146 // FIXME: Move to DeclGroup...
1147 D.getDeclSpec().getSourceRange().getBegin());
1148 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroffcae537d2007-08-28 18:45:29 +00001149 }
Chris Lattner4b009652007-07-25 00:24:17 +00001150 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +00001151 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +00001152
Daniel Dunbarced89142008-08-06 00:03:29 +00001153 // Handle GNU asm-label extension (encoded as an attribute).
1154 if (Expr *E = (Expr*) D.getAsmLabel()) {
1155 // The parser guarantees this is a string.
1156 StringLiteral *SE = cast<StringLiteral>(E);
1157 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1158 SE->getByteLength())));
1159 }
1160
Nate Begemanea583262008-03-14 18:07:10 +00001161 // Emit an error if an address space was applied to decl with local storage.
1162 // This includes arrays of objects with address space qualifiers, but not
1163 // automatic variables that point to other address spaces.
1164 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +00001165 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1166 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1167 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +00001168 }
Steve Narofff8a09432008-01-09 23:34:55 +00001169 // Merge the decl with the existing one if appropriate. If the decl is
1170 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001171 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001172 NewVD = MergeVarDecl(NewVD, PrevDecl);
1173 if (NewVD == 0) return 0;
1174 }
Chris Lattner4b009652007-07-25 00:24:17 +00001175 New = NewVD;
1176 }
1177
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001178 // Set the lexical context. If the declarator has a C++ scope specifier, the
1179 // lexical context will be different from the semantic context.
1180 New->setLexicalDeclContext(CurContext);
1181
Chris Lattner4b009652007-07-25 00:24:17 +00001182 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001183 if (II)
1184 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001185 // If any semantic error occurred, mark the decl as invalid.
1186 if (D.getInvalidType() || InvalidDecl)
1187 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001188
1189 return New;
1190}
1191
Steve Narofffc08f5e2008-10-27 11:34:16 +00001192void Sema::InitializerElementNotConstant(const Expr *Init) {
1193 Diag(Init->getExprLoc(),
1194 diag::err_init_element_not_constant, Init->getSourceRange());
1195}
1196
Eli Friedman02c22ce2008-05-20 13:48:25 +00001197bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1198 switch (Init->getStmtClass()) {
1199 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001200 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001201 return true;
1202 case Expr::ParenExprClass: {
1203 const ParenExpr* PE = cast<ParenExpr>(Init);
1204 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1205 }
1206 case Expr::CompoundLiteralExprClass:
1207 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1208 case Expr::DeclRefExprClass: {
1209 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001210 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1211 if (VD->hasGlobalStorage())
1212 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001213 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001214 return true;
1215 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001216 if (isa<FunctionDecl>(D))
1217 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001218 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001219 return true;
1220 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001221 case Expr::MemberExprClass: {
1222 const MemberExpr *M = cast<MemberExpr>(Init);
1223 if (M->isArrow())
1224 return CheckAddressConstantExpression(M->getBase());
1225 return CheckAddressConstantExpressionLValue(M->getBase());
1226 }
1227 case Expr::ArraySubscriptExprClass: {
1228 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1229 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1230 return CheckAddressConstantExpression(ASE->getBase()) ||
1231 CheckArithmeticConstantExpression(ASE->getIdx());
1232 }
1233 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001234 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001235 return false;
1236 case Expr::UnaryOperatorClass: {
1237 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1238
1239 // C99 6.6p9
1240 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001241 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001242
Steve Narofffc08f5e2008-10-27 11:34:16 +00001243 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001244 return true;
1245 }
1246 }
1247}
1248
1249bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1250 switch (Init->getStmtClass()) {
1251 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001252 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001253 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001254 case Expr::ParenExprClass:
1255 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001256 case Expr::StringLiteralClass:
1257 case Expr::ObjCStringLiteralClass:
1258 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001259 case Expr::CallExprClass:
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001260 case Expr::CXXOperatorCallExprClass:
Chris Lattner0903cba2008-10-06 07:26:43 +00001261 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1262 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1263 Builtin::BI__builtin___CFStringMakeConstantString)
1264 return false;
1265
Steve Narofffc08f5e2008-10-27 11:34:16 +00001266 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001267 return true;
1268
Eli Friedman02c22ce2008-05-20 13:48:25 +00001269 case Expr::UnaryOperatorClass: {
1270 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1271
1272 // C99 6.6p9
1273 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1274 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1275
1276 if (Exp->getOpcode() == UnaryOperator::Extension)
1277 return CheckAddressConstantExpression(Exp->getSubExpr());
1278
Steve Narofffc08f5e2008-10-27 11:34:16 +00001279 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001280 return true;
1281 }
1282 case Expr::BinaryOperatorClass: {
1283 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1284 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1285
1286 Expr *PExp = Exp->getLHS();
1287 Expr *IExp = Exp->getRHS();
1288 if (IExp->getType()->isPointerType())
1289 std::swap(PExp, IExp);
1290
1291 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1292 return CheckAddressConstantExpression(PExp) ||
1293 CheckArithmeticConstantExpression(IExp);
1294 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001295 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001296 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001297 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001298 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1299 // Check for implicit promotion
1300 if (SubExpr->getType()->isFunctionType() ||
1301 SubExpr->getType()->isArrayType())
1302 return CheckAddressConstantExpressionLValue(SubExpr);
1303 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001304
1305 // Check for pointer->pointer cast
1306 if (SubExpr->getType()->isPointerType())
1307 return CheckAddressConstantExpression(SubExpr);
1308
Eli Friedman1fad3c62008-08-25 20:46:57 +00001309 if (SubExpr->getType()->isIntegralType()) {
1310 // Check for the special-case of a pointer->int->pointer cast;
1311 // this isn't standard, but some code requires it. See
1312 // PR2720 for an example.
1313 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1314 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1315 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1316 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1317 if (IntWidth >= PointerWidth) {
1318 return CheckAddressConstantExpression(SubCast->getSubExpr());
1319 }
1320 }
1321 }
1322 }
1323 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001324 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001325 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001326
Steve Narofffc08f5e2008-10-27 11:34:16 +00001327 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001328 return true;
1329 }
1330 case Expr::ConditionalOperatorClass: {
1331 // FIXME: Should we pedwarn here?
1332 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1333 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001334 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001335 return true;
1336 }
1337 if (CheckArithmeticConstantExpression(Exp->getCond()))
1338 return true;
1339 if (Exp->getLHS() &&
1340 CheckAddressConstantExpression(Exp->getLHS()))
1341 return true;
1342 return CheckAddressConstantExpression(Exp->getRHS());
1343 }
1344 case Expr::AddrLabelExprClass:
1345 return false;
1346 }
1347}
1348
Eli Friedman998dffb2008-06-09 05:05:07 +00001349static const Expr* FindExpressionBaseAddress(const Expr* E);
1350
1351static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1352 switch (E->getStmtClass()) {
1353 default:
1354 return E;
1355 case Expr::ParenExprClass: {
1356 const ParenExpr* PE = cast<ParenExpr>(E);
1357 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1358 }
1359 case Expr::MemberExprClass: {
1360 const MemberExpr *M = cast<MemberExpr>(E);
1361 if (M->isArrow())
1362 return FindExpressionBaseAddress(M->getBase());
1363 return FindExpressionBaseAddressLValue(M->getBase());
1364 }
1365 case Expr::ArraySubscriptExprClass: {
1366 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1367 return FindExpressionBaseAddress(ASE->getBase());
1368 }
1369 case Expr::UnaryOperatorClass: {
1370 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1371
1372 if (Exp->getOpcode() == UnaryOperator::Deref)
1373 return FindExpressionBaseAddress(Exp->getSubExpr());
1374
1375 return E;
1376 }
1377 }
1378}
1379
1380static const Expr* FindExpressionBaseAddress(const Expr* E) {
1381 switch (E->getStmtClass()) {
1382 default:
1383 return E;
1384 case Expr::ParenExprClass: {
1385 const ParenExpr* PE = cast<ParenExpr>(E);
1386 return FindExpressionBaseAddress(PE->getSubExpr());
1387 }
1388 case Expr::UnaryOperatorClass: {
1389 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1390
1391 // C99 6.6p9
1392 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1393 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1394
1395 if (Exp->getOpcode() == UnaryOperator::Extension)
1396 return FindExpressionBaseAddress(Exp->getSubExpr());
1397
1398 return E;
1399 }
1400 case Expr::BinaryOperatorClass: {
1401 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1402
1403 Expr *PExp = Exp->getLHS();
1404 Expr *IExp = Exp->getRHS();
1405 if (IExp->getType()->isPointerType())
1406 std::swap(PExp, IExp);
1407
1408 return FindExpressionBaseAddress(PExp);
1409 }
1410 case Expr::ImplicitCastExprClass: {
1411 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1412
1413 // Check for implicit promotion
1414 if (SubExpr->getType()->isFunctionType() ||
1415 SubExpr->getType()->isArrayType())
1416 return FindExpressionBaseAddressLValue(SubExpr);
1417
1418 // Check for pointer->pointer cast
1419 if (SubExpr->getType()->isPointerType())
1420 return FindExpressionBaseAddress(SubExpr);
1421
1422 // We assume that we have an arithmetic expression here;
1423 // if we don't, we'll figure it out later
1424 return 0;
1425 }
Douglas Gregor035d0882008-10-28 15:36:24 +00001426 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001427 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1428
1429 // Check for pointer->pointer cast
1430 if (SubExpr->getType()->isPointerType())
1431 return FindExpressionBaseAddress(SubExpr);
1432
1433 // We assume that we have an arithmetic expression here;
1434 // if we don't, we'll figure it out later
1435 return 0;
1436 }
1437 }
1438}
1439
Eli Friedman02c22ce2008-05-20 13:48:25 +00001440bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1441 switch (Init->getStmtClass()) {
1442 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001443 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001444 return true;
1445 case Expr::ParenExprClass: {
1446 const ParenExpr* PE = cast<ParenExpr>(Init);
1447 return CheckArithmeticConstantExpression(PE->getSubExpr());
1448 }
1449 case Expr::FloatingLiteralClass:
1450 case Expr::IntegerLiteralClass:
1451 case Expr::CharacterLiteralClass:
1452 case Expr::ImaginaryLiteralClass:
1453 case Expr::TypesCompatibleExprClass:
1454 case Expr::CXXBoolLiteralExprClass:
1455 return false;
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001456 case Expr::CallExprClass:
1457 case Expr::CXXOperatorCallExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001458 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001459
1460 // Allow any constant foldable calls to builtins.
1461 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001462 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001463
Steve Narofffc08f5e2008-10-27 11:34:16 +00001464 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001465 return true;
1466 }
1467 case Expr::DeclRefExprClass: {
1468 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1469 if (isa<EnumConstantDecl>(D))
1470 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001471 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001472 return true;
1473 }
1474 case Expr::CompoundLiteralExprClass:
1475 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1476 // but vectors are allowed to be magic.
1477 if (Init->getType()->isVectorType())
1478 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001479 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001480 return true;
1481 case Expr::UnaryOperatorClass: {
1482 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1483
1484 switch (Exp->getOpcode()) {
1485 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1486 // See C99 6.6p3.
1487 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001488 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001489 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001490 case UnaryOperator::OffsetOf:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001491 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1492 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001493 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001494 return true;
1495 case UnaryOperator::Extension:
1496 case UnaryOperator::LNot:
1497 case UnaryOperator::Plus:
1498 case UnaryOperator::Minus:
1499 case UnaryOperator::Not:
1500 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1501 }
1502 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001503 case Expr::SizeOfAlignOfExprClass: {
1504 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001505 // Special check for void types, which are allowed as an extension
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001506 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedman02c22ce2008-05-20 13:48:25 +00001507 return false;
1508 // alignof always evaluates to a constant.
1509 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001510 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001511 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001512 return true;
1513 }
1514 return false;
1515 }
1516 case Expr::BinaryOperatorClass: {
1517 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1518
1519 if (Exp->getLHS()->getType()->isArithmeticType() &&
1520 Exp->getRHS()->getType()->isArithmeticType()) {
1521 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1522 CheckArithmeticConstantExpression(Exp->getRHS());
1523 }
1524
Eli Friedman998dffb2008-06-09 05:05:07 +00001525 if (Exp->getLHS()->getType()->isPointerType() &&
1526 Exp->getRHS()->getType()->isPointerType()) {
1527 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1528 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1529
1530 // Only allow a null (constant integer) base; we could
1531 // allow some additional cases if necessary, but this
1532 // is sufficient to cover offsetof-like constructs.
1533 if (!LHSBase && !RHSBase) {
1534 return CheckAddressConstantExpression(Exp->getLHS()) ||
1535 CheckAddressConstantExpression(Exp->getRHS());
1536 }
1537 }
1538
Steve Narofffc08f5e2008-10-27 11:34:16 +00001539 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001540 return true;
1541 }
1542 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001543 case Expr::CStyleCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001544 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00001545 if (SubExpr->getType()->isArithmeticType())
1546 return CheckArithmeticConstantExpression(SubExpr);
1547
Eli Friedman266df142008-09-02 09:37:00 +00001548 if (SubExpr->getType()->isPointerType()) {
1549 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1550 // If the pointer has a null base, this is an offsetof-like construct
1551 if (!Base)
1552 return CheckAddressConstantExpression(SubExpr);
1553 }
1554
Steve Narofffc08f5e2008-10-27 11:34:16 +00001555 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00001556 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001557 }
1558 case Expr::ConditionalOperatorClass: {
1559 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00001560
1561 // If GNU extensions are disabled, we require all operands to be arithmetic
1562 // constant expressions.
1563 if (getLangOptions().NoExtensions) {
1564 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1565 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1566 CheckArithmeticConstantExpression(Exp->getRHS());
1567 }
1568
1569 // Otherwise, we have to emulate some of the behavior of fold here.
1570 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1571 // because it can constant fold things away. To retain compatibility with
1572 // GCC code, we see if we can fold the condition to a constant (which we
1573 // should always be able to do in theory). If so, we only require the
1574 // specified arm of the conditional to be a constant. This is a horrible
1575 // hack, but is require by real world code that uses __builtin_constant_p.
1576 APValue Val;
Chris Lattneref069662008-11-16 21:24:15 +00001577 if (!Exp->getCond()->Evaluate(Val, Context)) {
1578 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner94d45412008-10-06 05:42:39 +00001579 // won't be able to either. Use it to emit the diagnostic though.
1580 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattneref069662008-11-16 21:24:15 +00001581 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner94d45412008-10-06 05:42:39 +00001582 return Res;
1583 }
1584
1585 // Verify that the side following the condition is also a constant.
1586 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1587 if (Val.getInt() == 0)
1588 std::swap(TrueSide, FalseSide);
1589
1590 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001591 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00001592
1593 // Okay, the evaluated side evaluates to a constant, so we accept this.
1594 // Check to see if the other side is obviously not a constant. If so,
1595 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001596 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00001597 Diag(Init->getExprLoc(),
1598 diag::ext_typecheck_expression_not_constant_but_accepted,
1599 FalseSide->getSourceRange());
1600 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001601 }
1602 }
1603}
1604
1605bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopese7280452008-07-07 16:46:50 +00001606 Init = Init->IgnoreParens();
1607
Eli Friedman02c22ce2008-05-20 13:48:25 +00001608 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1609 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1610 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1611
Nuno Lopese7280452008-07-07 16:46:50 +00001612 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1613 return CheckForConstantInitializer(e->getInitializer(), DclT);
1614
Eli Friedman02c22ce2008-05-20 13:48:25 +00001615 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1616 unsigned numInits = Exp->getNumInits();
1617 for (unsigned i = 0; i < numInits; i++) {
1618 // FIXME: Need to get the type of the declaration for C++,
1619 // because it could be a reference?
1620 if (CheckForConstantInitializer(Exp->getInit(i),
1621 Exp->getInit(i)->getType()))
1622 return true;
1623 }
1624 return false;
1625 }
1626
1627 if (Init->isNullPointerConstant(Context))
1628 return false;
1629 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001630 QualType InitTy = Context.getCanonicalType(Init->getType())
1631 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00001632 if (InitTy == Context.BoolTy) {
1633 // Special handling for pointers implicitly cast to bool;
1634 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1635 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1636 Expr* SubE = ICE->getSubExpr();
1637 if (SubE->getType()->isPointerType() ||
1638 SubE->getType()->isArrayType() ||
1639 SubE->getType()->isFunctionType()) {
1640 return CheckAddressConstantExpression(Init);
1641 }
1642 }
1643 } else if (InitTy->isIntegralType()) {
1644 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001645 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00001646 SubE = CE->getSubExpr();
1647 // Special check for pointer cast to int; we allow as an extension
1648 // an address constant cast to an integer if the integer
1649 // is of an appropriate width (this sort of code is apparently used
1650 // in some places).
1651 // FIXME: Add pedwarn?
1652 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1653 if (SubE && (SubE->getType()->isPointerType() ||
1654 SubE->getType()->isArrayType() ||
1655 SubE->getType()->isFunctionType())) {
1656 unsigned IntWidth = Context.getTypeSize(Init->getType());
1657 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1658 if (IntWidth >= PointerWidth)
1659 return CheckAddressConstantExpression(Init);
1660 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001661 }
1662
1663 return CheckArithmeticConstantExpression(Init);
1664 }
1665
1666 if (Init->getType()->isPointerType())
1667 return CheckAddressConstantExpression(Init);
1668
Eli Friedman25086f02008-05-30 18:14:48 +00001669 // An array type at the top level that isn't an init-list must
1670 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00001671 if (Init->getType()->isArrayType())
1672 return false;
1673
Nuno Lopes1dc26762008-09-01 18:42:41 +00001674 if (Init->getType()->isFunctionType())
1675 return false;
1676
Steve Naroffdff3fb22008-10-02 17:12:56 +00001677 // Allow block exprs at top level.
1678 if (Init->getType()->isBlockPointerType())
1679 return false;
1680
Steve Narofffc08f5e2008-10-27 11:34:16 +00001681 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001682 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00001683}
1684
Steve Naroff6a0e2092007-09-12 14:07:44 +00001685void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001686 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001687 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001688 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001689
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001690 // If there is no declaration, there was an error parsing it. Just ignore
1691 // the initializer.
1692 if (RealDecl == 0) {
1693 delete Init;
1694 return;
1695 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001696
Steve Naroff420d0f52007-09-12 20:13:48 +00001697 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1698 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001699 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1700 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001701 RealDecl->setInvalidDecl();
1702 return;
1703 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001704 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001705 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001706 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001707 if (VDecl->isBlockVarDecl()) {
1708 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001709 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001710 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001711 VDecl->setInvalidDecl();
1712 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001713 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1714 VDecl->getName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001715 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00001716
1717 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1718 if (!getLangOptions().CPlusPlus) {
1719 if (SC == VarDecl::Static) // C99 6.7.8p4.
1720 CheckForConstantInitializer(Init, DclT);
1721 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001722 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001723 } else if (VDecl->isFileVarDecl()) {
1724 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001725 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001726 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00001727 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1728 VDecl->getName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001729 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001730
Anders Carlssonea7140a2008-08-22 05:00:02 +00001731 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1732 if (!getLangOptions().CPlusPlus) {
1733 // C99 6.7.8p4. All file scoped initializers need to be constant.
1734 CheckForConstantInitializer(Init, DclT);
1735 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001736 }
1737 // If the type changed, it means we had an incomplete type that was
1738 // completed by the initializer. For example:
1739 // int ary[] = { 1, 3, 5 };
1740 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001741 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001742 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001743 Init->setType(DclT);
1744 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001745
1746 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001747 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001748 return;
1749}
1750
Douglas Gregor81c29152008-10-29 00:13:59 +00001751void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1752 Decl *RealDecl = static_cast<Decl *>(dcl);
1753
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00001754 // If there is no declaration, there was an error parsing it. Just ignore it.
1755 if (RealDecl == 0)
1756 return;
1757
Douglas Gregor81c29152008-10-29 00:13:59 +00001758 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1759 QualType Type = Var->getType();
1760 // C++ [dcl.init.ref]p3:
1761 // The initializer can be omitted for a reference only in a
1762 // parameter declaration (8.3.5), in the declaration of a
1763 // function return type, in the declaration of a class member
1764 // within its class declaration (9.2), and where the extern
1765 // specifier is explicitly used.
Douglas Gregor5870a952008-11-03 20:45:27 +00001766 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001767 Diag(Var->getLocation(),
1768 diag::err_reference_var_requires_init,
1769 Var->getName(),
1770 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor5870a952008-11-03 20:45:27 +00001771 Var->setInvalidDecl();
1772 return;
1773 }
1774
1775 // C++ [dcl.init]p9:
1776 //
1777 // If no initializer is specified for an object, and the object
1778 // is of (possibly cv-qualified) non-POD class type (or array
1779 // thereof), the object shall be default-initialized; if the
1780 // object is of const-qualified type, the underlying class type
1781 // shall have a user-declared default constructor.
1782 if (getLangOptions().CPlusPlus) {
1783 QualType InitType = Type;
1784 if (const ArrayType *Array = Context.getAsArrayType(Type))
1785 InitType = Array->getElementType();
1786 if (InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001787 const CXXConstructorDecl *Constructor
1788 = PerformInitializationByConstructor(InitType, 0, 0,
1789 Var->getLocation(),
1790 SourceRange(Var->getLocation(),
1791 Var->getLocation()),
1792 Var->getName(),
1793 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00001794 if (!Constructor)
1795 Var->setInvalidDecl();
1796 }
1797 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001798
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001799#if 0
1800 // FIXME: Temporarily disabled because we are not properly parsing
1801 // linkage specifications on declarations, e.g.,
1802 //
1803 // extern "C" const CGPoint CGPointerZero;
1804 //
Douglas Gregor81c29152008-10-29 00:13:59 +00001805 // C++ [dcl.init]p9:
1806 //
1807 // If no initializer is specified for an object, and the
1808 // object is of (possibly cv-qualified) non-POD class type (or
1809 // array thereof), the object shall be default-initialized; if
1810 // the object is of const-qualified type, the underlying class
1811 // type shall have a user-declared default
1812 // constructor. Otherwise, if no initializer is specified for
1813 // an object, the object and its subobjects, if any, have an
1814 // indeterminate initial value; if the object or any of its
1815 // subobjects are of const-qualified type, the program is
1816 // ill-formed.
1817 //
1818 // This isn't technically an error in C, so we don't diagnose it.
1819 //
1820 // FIXME: Actually perform the POD/user-defined default
1821 // constructor check.
1822 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001823 Context.getCanonicalType(Type).isConstQualified() &&
1824 Var->getStorageClass() != VarDecl::Extern)
Douglas Gregor81c29152008-10-29 00:13:59 +00001825 Diag(Var->getLocation(),
1826 diag::err_const_var_requires_init,
1827 Var->getName(),
1828 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001829#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00001830 }
1831}
1832
Chris Lattner4b009652007-07-25 00:24:17 +00001833/// The declarators are chained together backwards, reverse the list.
1834Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1835 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001836 Decl *GroupDecl = static_cast<Decl*>(group);
1837 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00001838 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00001839
1840 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1841 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001842 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00001843 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001844 else { // reverse the list.
1845 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001846 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001847 Group->setNextDeclarator(NewGroup);
1848 NewGroup = Group;
1849 Group = Next;
1850 }
1851 }
1852 // Perform semantic analysis that depends on having fully processed both
1853 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001854 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001855 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1856 if (!IDecl)
1857 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001858 QualType T = IDecl->getType();
1859
1860 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1861 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001862 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1863 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001864 if (T->isVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001865 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1866 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001867 }
1868 }
1869 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1870 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001871 if (IDecl->isBlockVarDecl() &&
1872 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001873 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001874 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1875 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001876 IDecl->setInvalidDecl();
1877 }
1878 }
1879 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1880 // object that has file scope without an initializer, and without a
1881 // storage-class specifier or with the storage-class specifier "static",
1882 // constitutes a tentative definition. Note: A tentative definition with
1883 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00001884 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001885 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001886 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1887 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001888 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001889 // C99 6.9.2p3: If the declaration of an identifier for an object is
1890 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1891 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001892 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1893 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001894 IDecl->setInvalidDecl();
1895 }
1896 }
Steve Naroffb5e78152008-08-08 17:50:35 +00001897 if (IDecl->isFileVarDecl())
1898 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001899 }
1900 return NewGroup;
1901}
Steve Naroff91b03f72007-08-28 03:03:08 +00001902
Chris Lattner3e254fb2008-04-08 04:40:51 +00001903/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1904/// to introduce parameters into function prototype scope.
1905Sema::DeclTy *
1906Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001907 // FIXME: disallow CXXScopeSpec for param declarators.
Chris Lattner5e77ade2008-06-26 06:49:43 +00001908 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001909
1910 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001911 VarDecl::StorageClass StorageClass = VarDecl::None;
1912 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1913 StorageClass = VarDecl::Register;
1914 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001915 Diag(DS.getStorageClassSpecLoc(),
1916 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001917 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001918 }
1919 if (DS.isThreadSpecified()) {
1920 Diag(DS.getThreadSpecLoc(),
1921 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001922 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001923 }
1924
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001925 // Check that there are no default arguments inside the type of this
1926 // parameter (C++ only).
1927 if (getLangOptions().CPlusPlus)
1928 CheckExtraCXXDefaultArguments(D);
1929
Chris Lattner3e254fb2008-04-08 04:40:51 +00001930 // In this context, we *do not* check D.getInvalidType(). If the declarator
1931 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1932 // though it will not reflect the user specified type.
1933 QualType parmDeclType = GetTypeForDeclarator(D, S);
1934
1935 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1936
Chris Lattner4b009652007-07-25 00:24:17 +00001937 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1938 // Can this happen for params? We already checked that they don't conflict
1939 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001940 IdentifierInfo *II = D.getIdentifier();
1941 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1942 if (S->isDeclScope(PrevDecl)) {
1943 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1944 dyn_cast<NamedDecl>(PrevDecl)->getName());
1945
1946 // Recover by removing the name
1947 II = 0;
1948 D.SetIdentifier(0, D.getIdentifierLoc());
1949 }
Chris Lattner4b009652007-07-25 00:24:17 +00001950 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001951
1952 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1953 // Doing the promotion here has a win and a loss. The win is the type for
1954 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1955 // code generator). The loss is the orginal type isn't preserved. For example:
1956 //
1957 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1958 // int blockvardecl[5];
1959 // sizeof(parmvardecl); // size == 4
1960 // sizeof(blockvardecl); // size == 20
1961 // }
1962 //
1963 // For expressions, all implicit conversions are captured using the
1964 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1965 //
1966 // FIXME: If a source translation tool needs to see the original type, then
1967 // we need to consider storing both types (in ParmVarDecl)...
1968 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00001969 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00001970 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00001971 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00001972 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001973 parmDeclType = Context.getPointerType(parmDeclType);
1974
Chris Lattner3e254fb2008-04-08 04:40:51 +00001975 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1976 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001977 parmDeclType, StorageClass,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001978 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00001979
Chris Lattner3e254fb2008-04-08 04:40:51 +00001980 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00001981 New->setInvalidDecl();
1982
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001983 if (II)
1984 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00001985
Chris Lattner9b384ca2008-06-29 00:02:00 +00001986 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00001987 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001988
Chris Lattner4b009652007-07-25 00:24:17 +00001989}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001990
Chris Lattnerea148702007-10-09 17:14:05 +00001991Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001992 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00001993 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1994 "Not a function declarator!");
1995 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001996
Chris Lattner4b009652007-07-25 00:24:17 +00001997 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1998 // for a K&R function.
1999 if (!FTI.hasPrototype) {
2000 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002001 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00002002 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
2003 FTI.ArgInfo[i].Ident->getName());
2004 // Implicitly declare the argument as type 'int' for lack of a better
2005 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002006 DeclSpec DS;
2007 const char* PrevSpec; // unused
2008 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2009 PrevSpec);
2010 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2011 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2012 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00002013 }
2014 }
Chris Lattner4b009652007-07-25 00:24:17 +00002015 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002016 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00002017 }
2018
2019 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00002020
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002021 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002022 ActOnDeclarator(GlobalScope, D, 0));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002023}
2024
2025Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2026 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002027 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002028
2029 // See if this is a redefinition.
2030 const FunctionDecl *Definition;
2031 if (FD->getBody(Definition)) {
2032 Diag(FD->getLocation(), diag::err_redefinition,
2033 FD->getName());
2034 Diag(Definition->getLocation(), diag::err_previous_definition);
2035 }
2036
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002037 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00002038
2039 // Check the validity of our function parameters
2040 CheckParmsForFunctionDef(FD);
2041
2042 // Introduce our parameters into the function scope
2043 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2044 ParmVarDecl *Param = FD->getParamDecl(p);
2045 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002046 if (Param->getIdentifier())
2047 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002048 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002049
Chris Lattner4b009652007-07-25 00:24:17 +00002050 return FD;
2051}
2052
Steve Naroff99ee4302007-11-11 23:20:51 +00002053Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
2054 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002055 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002056 FD->setBody((Stmt*)Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002057 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002058 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002059 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002060 } else
2061 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002062 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002063 // Verify and clean out per-function state.
2064
2065 // Check goto/label use.
2066 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2067 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2068 // Verify that we have no forward references left. If so, there was a goto
2069 // or address of a label taken, but no definition of it. Label fwd
2070 // definitions are indicated with a null substmt.
2071 if (I->second->getSubStmt() == 0) {
2072 LabelStmt *L = I->second;
2073 // Emit error.
2074 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
2075
2076 // At this point, we have gotos that use the bogus label. Stitch it into
2077 // the function body so that they aren't leaked and that the AST is well
2078 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002079 if (Body) {
2080 L->setSubStmt(new NullStmt(L->getIdentLoc()));
2081 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2082 } else {
2083 // The whole function wasn't parsed correctly, just delete this.
2084 delete L;
2085 }
Chris Lattner4b009652007-07-25 00:24:17 +00002086 }
2087 }
2088 LabelMap.clear();
2089
Steve Naroff99ee4302007-11-11 23:20:51 +00002090 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002091}
2092
Chris Lattner4b009652007-07-25 00:24:17 +00002093/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2094/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00002095ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2096 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002097 // Extension in C99. Legal in C90, but warn about it.
2098 if (getLangOptions().C99)
Chris Lattner4b009652007-07-25 00:24:17 +00002099 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002100 else
Chris Lattner4b009652007-07-25 00:24:17 +00002101 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
2102
2103 // FIXME: handle stuff like:
2104 // void foo() { extern float X(); }
2105 // void bar() { X(); } <-- implicit decl for X in another scope.
2106
2107 // Set a Declarator for the implicit definition: int foo();
2108 const char *Dummy;
2109 DeclSpec DS;
2110 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2111 Error = Error; // Silence warning.
2112 assert(!Error && "Error setting up implicit decl!");
2113 Declarator D(DS, Declarator::BlockContext);
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00002114 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Chris Lattner4b009652007-07-25 00:24:17 +00002115 D.SetIdentifier(&II, Loc);
2116
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002117 // Insert this function into translation-unit scope.
2118
2119 DeclContext *PrevDC = CurContext;
2120 CurContext = Context.getTranslationUnitDecl();
2121
Steve Naroff9104f3c2008-04-04 14:32:09 +00002122 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002123 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002124 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002125
2126 CurContext = PrevDC;
2127
Steve Naroff9104f3c2008-04-04 14:32:09 +00002128 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002129}
2130
2131
Chris Lattner82bb4792007-11-14 06:34:38 +00002132TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00002133 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002134 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002135 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002136
2137 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002138 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2139 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002140 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00002141 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002142 if (D.getInvalidType())
2143 NewTD->setInvalidDecl();
2144 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002145}
2146
Steve Naroff0acc9c92007-09-15 18:49:24 +00002147/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002148/// former case, Name will be non-null. In the later case, Name will be null.
2149/// TagType indicates what kind of tag this is. TK indicates whether this is a
2150/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002151Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002152 SourceLocation KWLoc, const CXXScopeSpec &SS,
2153 IdentifierInfo *Name, SourceLocation NameLoc,
2154 AttributeList *Attr) {
Chris Lattner4b009652007-07-25 00:24:17 +00002155 // If this is a use of an existing tag, it must have a name.
2156 assert((Name != 0 || TK == TK_Definition) &&
2157 "Nameless record must be a definition!");
2158
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002159 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00002160 switch (TagType) {
2161 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002162 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2163 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2164 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2165 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002166 }
2167
Ted Kremenek46a837c2008-09-05 17:16:31 +00002168 // Two code paths: a new one for structs/unions/classes where we create
2169 // separate decls for forward declarations, and an old (eventually to
2170 // be removed) code path for enums.
2171 if (Kind != TagDecl::TK_enum)
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002172 return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr);
Ted Kremenek46a837c2008-09-05 17:16:31 +00002173
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002174 DeclContext *DC = CurContext;
2175 ScopedDecl *PrevDecl = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002176
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002177 if (Name && SS.isNotEmpty()) {
2178 // We have a nested-name tag ('struct foo::bar').
2179
2180 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002181 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002182 Name = 0;
2183 goto CreateNewDecl;
2184 }
2185
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002186 DC = static_cast<DeclContext*>(SS.getScopeRep());
2187 // Look-up name inside 'foo::'.
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002188 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2189
2190 // A tag 'foo::bar' must already exist.
2191 if (PrevDecl == 0) {
2192 Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(),
2193 SS.getRange());
2194 Name = 0;
2195 goto CreateNewDecl;
2196 }
2197 } else {
2198 // If this is a named struct, check to see if there was a previous forward
2199 // declaration or definition.
2200 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2201 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2202 }
2203
Ted Kremenekd4434152008-09-02 21:26:19 +00002204 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002205 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2206 "unexpected Decl type");
2207 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002208 // If this is a use of a previous tag, or if the tag is already declared
2209 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002210 // rementions the tag), reuse the decl.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002211 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002212 // Make sure that this wasn't declared as an enum and now used as a
2213 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002214 if (PrevTagDecl->getTagKind() != Kind) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002215 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2216 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002217 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002218 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002219 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002220 } else {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002221 // If this is a use or a forward declaration, we're good.
2222 if (TK != TK_Definition)
2223 return PrevDecl;
2224
2225 // Diagnose attempts to redefine a tag.
2226 if (PrevTagDecl->isDefinition()) {
2227 Diag(NameLoc, diag::err_redefinition, Name->getName());
2228 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2229 // If this is a redefinition, recover by making this struct be
2230 // anonymous, which will make any later references get the previous
2231 // definition.
2232 Name = 0;
2233 } else {
2234 // Okay, this is definition of a previously declared or referenced
2235 // tag. Move the location of the decl to be the definition site.
2236 PrevDecl->setLocation(NameLoc);
2237 return PrevDecl;
2238 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002239 }
Chris Lattner4b009652007-07-25 00:24:17 +00002240 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002241 // If we get here, this is a definition of a new struct type in a nested
2242 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2243 // type.
2244 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002245 // PrevDecl is a namespace.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002246 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002247 // The tag name clashes with a namespace name, issue an error and
2248 // recover by making this tag be anonymous.
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002249 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2250 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2251 Name = 0;
2252 }
Chris Lattner4b009652007-07-25 00:24:17 +00002253 }
Chris Lattner4b009652007-07-25 00:24:17 +00002254 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002255
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002256 CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00002257
2258 // If there is an identifier, use the location of the identifier as the
2259 // location of the decl, otherwise use the location of the struct/union
2260 // keyword.
2261 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2262
2263 // Otherwise, if this is the first time we've seen this tag, create the decl.
2264 TagDecl *New;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002265 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00002266 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2267 // enum X { A, B, C } D; D should chain to X.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002268 New = EnumDecl::Create(Context, DC, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002269 // If this is an undefined enum, warn.
2270 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002271 } else {
2272 // struct/union/class
2273
Chris Lattner4b009652007-07-25 00:24:17 +00002274 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2275 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002276 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002277 // FIXME: Look for a way to use RecordDecl for simple structs.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002278 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002279 else
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002280 New = RecordDecl::Create(Context, Kind, DC, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002281 }
Chris Lattner4b009652007-07-25 00:24:17 +00002282
2283 // If this has an identifier, add it to the scope stack.
2284 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00002285 // The scope passed in may not be a decl scope. Zip up the scope tree until
2286 // we find one that is.
2287 while ((S->getFlags() & Scope::DeclScope) == 0)
2288 S = S->getParent();
2289
2290 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002291 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002292 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00002293
Chris Lattnerd7e83d82008-06-28 23:58:55 +00002294 if (Attr)
2295 ProcessDeclAttributeList(New, Attr);
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00002296
2297 // Set the lexical context. If the tag has a C++ scope specifier, the
2298 // lexical context will be different from the semantic context.
2299 New->setLexicalDeclContext(CurContext);
2300
Chris Lattner4b009652007-07-25 00:24:17 +00002301 return New;
2302}
2303
Ted Kremenek46a837c2008-09-05 17:16:31 +00002304/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2305/// the logic for enums, we create separate decls for forward declarations.
2306/// This is called by ActOnTag, but eventually will replace its logic.
2307Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002308 SourceLocation KWLoc, const CXXScopeSpec &SS,
2309 IdentifierInfo *Name, SourceLocation NameLoc,
2310 AttributeList *Attr) {
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002311 DeclContext *DC = CurContext;
2312 ScopedDecl *PrevDecl = 0;
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002313
2314 if (Name && SS.isNotEmpty()) {
2315 // We have a nested-name tag ('struct foo::bar').
2316
2317 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002318 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002319 Name = 0;
2320 goto CreateNewDecl;
2321 }
2322
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002323 DC = static_cast<DeclContext*>(SS.getScopeRep());
2324 // Look-up name inside 'foo::'.
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002325 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2326
2327 // A tag 'foo::bar' must already exist.
2328 if (PrevDecl == 0) {
2329 Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(),
2330 SS.getRange());
2331 Name = 0;
2332 goto CreateNewDecl;
2333 }
2334 } else {
2335 // If this is a named struct, check to see if there was a previous forward
2336 // declaration or definition.
2337 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2338 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2339 }
Ted Kremenek46a837c2008-09-05 17:16:31 +00002340
2341 if (PrevDecl) {
2342 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2343 "unexpected Decl type");
2344
2345 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2346 // If this is a use of a previous tag, or if the tag is already declared
2347 // in the same scope (so that the definition/declaration completes or
2348 // rementions the tag), reuse the decl.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002349 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002350 // Make sure that this wasn't declared as an enum and now used as a
2351 // struct or something similar.
2352 if (PrevTagDecl->getTagKind() != Kind) {
2353 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2354 Diag(PrevDecl->getLocation(), diag::err_previous_use);
2355 // Recover by making this an anonymous redefinition.
2356 Name = 0;
2357 PrevDecl = 0;
2358 } else {
2359 // If this is a use, return the original decl.
2360
2361 // FIXME: In the future, return a variant or some other clue
2362 // for the consumer of this Decl to know it doesn't own it.
2363 // For our current ASTs this shouldn't be a problem, but will
2364 // need to be changed with DeclGroups.
2365 if (TK == TK_Reference)
2366 return PrevDecl;
2367
2368 // The new decl is a definition?
2369 if (TK == TK_Definition) {
2370 // Diagnose attempts to redefine a tag.
2371 if (RecordDecl* DefRecord =
2372 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
2373 Diag(NameLoc, diag::err_redefinition, Name->getName());
2374 Diag(DefRecord->getLocation(), diag::err_previous_definition);
2375 // If this is a redefinition, recover by making this struct be
2376 // anonymous, which will make any later references get the previous
2377 // definition.
2378 Name = 0;
2379 PrevDecl = 0;
2380 }
2381 // Okay, this is definition of a previously declared or referenced
2382 // tag. We're going to create a new Decl.
2383 }
2384 }
2385 // If we get here we have (another) forward declaration. Just create
2386 // a new decl.
2387 }
2388 else {
2389 // If we get here, this is a definition of a new struct type in a nested
2390 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2391 // new decl/type. We set PrevDecl to NULL so that the Records
2392 // have distinct types.
2393 PrevDecl = 0;
2394 }
2395 } else {
2396 // PrevDecl is a namespace.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002397 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002398 // The tag name clashes with a namespace name, issue an error and
2399 // recover by making this tag be anonymous.
2400 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2401 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2402 Name = 0;
2403 }
2404 }
2405 }
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002406
2407 CreateNewDecl:
2408
Ted Kremenek46a837c2008-09-05 17:16:31 +00002409 // If there is an identifier, use the location of the identifier as the
2410 // location of the decl, otherwise use the location of the struct/union
2411 // keyword.
2412 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2413
2414 // Otherwise, if this is the first time we've seen this tag, create the decl.
2415 TagDecl *New;
2416
2417 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2418 // struct X { int A; } D; D should chain to X.
2419 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002420 // FIXME: Look for a way to use RecordDecl for simple structs.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002421 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek46a837c2008-09-05 17:16:31 +00002422 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2423 else
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002424 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek46a837c2008-09-05 17:16:31 +00002425 dyn_cast_or_null<RecordDecl>(PrevDecl));
2426
2427 // If this has an identifier, add it to the scope stack.
2428 if ((TK == TK_Definition || !PrevDecl) && Name) {
2429 // The scope passed in may not be a decl scope. Zip up the scope tree until
2430 // we find one that is.
2431 while ((S->getFlags() & Scope::DeclScope) == 0)
2432 S = S->getParent();
2433
2434 // Add it to the decl chain.
2435 PushOnScopeChains(New, S);
2436 }
Daniel Dunbar2cb762f2008-10-16 02:34:03 +00002437
2438 // Handle #pragma pack: if the #pragma pack stack has non-default
2439 // alignment, make up a packed attribute for this decl. These
2440 // attributes are checked when the ASTContext lays out the
2441 // structure.
2442 //
2443 // It is important for implementing the correct semantics that this
2444 // happen here (in act on tag decl). The #pragma pack stack is
2445 // maintained as a result of parser callbacks which can occur at
2446 // many points during the parsing of a struct declaration (because
2447 // the #pragma tokens are effectively skipped over during the
2448 // parsing of the struct).
2449 if (unsigned Alignment = PackContext.getAlignment())
2450 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek46a837c2008-09-05 17:16:31 +00002451
2452 if (Attr)
2453 ProcessDeclAttributeList(New, Attr);
2454
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00002455 // Set the lexical context. If the tag has a C++ scope specifier, the
2456 // lexical context will be different from the semantic context.
2457 New->setLexicalDeclContext(CurContext);
2458
Ted Kremenek46a837c2008-09-05 17:16:31 +00002459 return New;
2460}
2461
2462
Chris Lattner1bf58f62008-06-21 19:39:06 +00002463/// Collect the instance variables declared in an Objective-C object. Used in
2464/// the creation of structures from objects using the @defs directive.
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002465static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattnere705e5e2008-07-21 22:17:28 +00002466 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00002467 if (Class->getSuperClass())
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002468 CollectIvars(Class->getSuperClass(), Ctx, ivars);
2469
2470 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremenek40e70e72008-09-03 18:03:35 +00002471 for (ObjCInterfaceDecl::ivar_iterator
2472 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2473
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002474 ObjCIvarDecl* ID = *I;
2475 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2476 ID->getIdentifier(),
2477 ID->getType(),
2478 ID->getBitWidth()));
2479 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002480}
2481
2482/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2483/// instance variables of ClassName into Decls.
2484void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2485 IdentifierInfo *ClassName,
Chris Lattnere705e5e2008-07-21 22:17:28 +00002486 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00002487 // Check that ClassName is a valid class
2488 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2489 if (!Class) {
2490 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
2491 return;
2492 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002493 // Collect the instance variables
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002494 CollectIvars(Class, Context, Decls);
Chris Lattner1bf58f62008-06-21 19:39:06 +00002495}
2496
Chris Lattnera73e2202008-11-12 21:17:48 +00002497/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2498/// types into constant array types in certain situations which would otherwise
2499/// be errors (for GCC compatibility).
2500static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2501 ASTContext &Context) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002502 // This method tries to turn a variable array into a constant
2503 // array even when the size isn't an ICE. This is necessary
2504 // for compatibility with code that depends on gcc's buggy
2505 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002506 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2507 if (!VLATy) return QualType();
2508
2509 APValue Result;
2510 if (!VLATy->getSizeExpr() ||
Chris Lattneref069662008-11-16 21:24:15 +00002511 !VLATy->getSizeExpr()->Evaluate(Result, Context))
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002512 return QualType();
2513
2514 assert(Result.isInt() && "Size expressions must be integers!");
2515 llvm::APSInt &Res = Result.getInt();
2516 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2517 return Context.getConstantArrayType(VLATy->getElementType(),
2518 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002519 return QualType();
2520}
2521
Steve Naroff0acc9c92007-09-15 18:49:24 +00002522/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00002523/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002524Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00002525 SourceLocation DeclStart,
2526 Declarator &D, ExprTy *BitfieldWidth) {
2527 IdentifierInfo *II = D.getIdentifier();
2528 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00002529 SourceLocation Loc = DeclStart;
2530 if (II) Loc = D.getIdentifierLoc();
2531
2532 // FIXME: Unnamed fields can be handled in various different ways, for
2533 // example, unnamed unions inject all members into the struct namespace!
Ted Kremenek40e70e72008-09-03 18:03:35 +00002534
Chris Lattner4b009652007-07-25 00:24:17 +00002535 if (BitWidth) {
2536 // TODO: Validate.
2537 //printf("WARNING: BITFIELDS IGNORED!\n");
2538
2539 // 6.7.2.1p3
2540 // 6.7.2.1p4
2541
2542 } else {
2543 // Not a bitfield.
2544
2545 // validate II.
2546
2547 }
2548
2549 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002550 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2551 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00002552
Chris Lattner4b009652007-07-25 00:24:17 +00002553 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2554 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00002555 if (T->isVariablyModifiedType()) {
Chris Lattnera73e2202008-11-12 21:17:48 +00002556 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002557 if (!FixedTy.isNull()) {
Chris Lattner86be8572008-11-13 18:49:38 +00002558 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002559 T = FixedTy;
2560 } else {
Chris Lattner86be8572008-11-13 18:49:38 +00002561 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner2a884752008-11-12 19:45:49 +00002562 T = Context.IntTy;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002563 InvalidDecl = true;
2564 }
Chris Lattner4b009652007-07-25 00:24:17 +00002565 }
Chris Lattner4b009652007-07-25 00:24:17 +00002566 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002567 FieldDecl *NewFD;
2568
2569 if (getLangOptions().CPlusPlus) {
2570 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2571 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2572 Loc, II, T, BitWidth);
2573 if (II)
2574 PushOnScopeChains(NewFD, S);
2575 }
2576 else
2577 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00002578
Chris Lattner9b384ca2008-06-29 00:02:00 +00002579 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002580
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002581 if (D.getInvalidType() || InvalidDecl)
2582 NewFD->setInvalidDecl();
2583 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00002584}
2585
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002586/// TranslateIvarVisibility - Translate visibility from a token ID to an
2587/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00002588static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002589TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00002590 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00002591 default: assert(0 && "Unknown visitibility kind");
2592 case tok::objc_private: return ObjCIvarDecl::Private;
2593 case tok::objc_public: return ObjCIvarDecl::Public;
2594 case tok::objc_protected: return ObjCIvarDecl::Protected;
2595 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00002596 }
2597}
2598
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002599/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2600/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002601Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002602 SourceLocation DeclStart,
2603 Declarator &D, ExprTy *BitfieldWidth,
2604 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002605 IdentifierInfo *II = D.getIdentifier();
2606 Expr *BitWidth = (Expr*)BitfieldWidth;
2607 SourceLocation Loc = DeclStart;
2608 if (II) Loc = D.getIdentifierLoc();
2609
2610 // FIXME: Unnamed fields can be handled in various different ways, for
2611 // example, unnamed unions inject all members into the struct namespace!
2612
2613
2614 if (BitWidth) {
2615 // TODO: Validate.
2616 //printf("WARNING: BITFIELDS IGNORED!\n");
2617
2618 // 6.7.2.1p3
2619 // 6.7.2.1p4
2620
2621 } else {
2622 // Not a bitfield.
2623
2624 // validate II.
2625
2626 }
2627
2628 QualType T = GetTypeForDeclarator(D, S);
2629 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2630 bool InvalidDecl = false;
2631
2632 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2633 // than a variably modified type.
2634 if (T->isVariablyModifiedType()) {
2635 // FIXME: This diagnostic needs work
2636 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2637 InvalidDecl = true;
2638 }
2639
Ted Kremenek173dd312008-07-23 18:04:17 +00002640 // Get the visibility (access control) for this ivar.
2641 ObjCIvarDecl::AccessControl ac =
2642 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2643 : ObjCIvarDecl::None;
2644
2645 // Construct the decl.
2646 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00002647 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002648
Ted Kremenek173dd312008-07-23 18:04:17 +00002649 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00002650 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002651
2652 if (D.getInvalidType() || InvalidDecl)
2653 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00002654
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002655 return NewID;
2656}
2657
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00002658void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002659 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00002660 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00002661 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00002662 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002663 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2664 assert(EnclosingDecl && "missing record or interface decl");
2665 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2666
Ted Kremenek46a837c2008-09-05 17:16:31 +00002667 if (Record)
2668 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2669 // Diagnose code like:
2670 // struct S { struct S {} X; };
2671 // We discover this when we complete the outer S. Reject and ignore the
2672 // outer S.
2673 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2674 DefRecord->getKindName());
2675 Diag(RecLoc, diag::err_previous_definition);
2676 Record->setInvalidDecl();
2677 return;
2678 }
2679
Chris Lattner4b009652007-07-25 00:24:17 +00002680 // Verify that all the fields are okay.
2681 unsigned NumNamedMembers = 0;
2682 llvm::SmallVector<FieldDecl*, 32> RecFields;
2683 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00002684
Chris Lattner4b009652007-07-25 00:24:17 +00002685 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002686
Steve Naroff9bb759f2007-09-14 22:20:54 +00002687 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2688 assert(FD && "missing field decl");
2689
2690 // Remember all fields.
2691 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00002692
2693 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00002694 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00002695
Chris Lattner4b009652007-07-25 00:24:17 +00002696 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00002697 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002698 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00002699 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002700 FD->setInvalidDecl();
2701 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002702 continue;
2703 }
Chris Lattner4b009652007-07-25 00:24:17 +00002704 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2705 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002706 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002707 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002708 FD->setInvalidDecl();
2709 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002710 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002711 }
Chris Lattner4b009652007-07-25 00:24:17 +00002712 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002713 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002714 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00002715 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002716 FD->setInvalidDecl();
2717 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002718 continue;
2719 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002720 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00002721 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2722 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002723 FD->setInvalidDecl();
2724 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002725 continue;
2726 }
Chris Lattner4b009652007-07-25 00:24:17 +00002727 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002728 if (Record)
2729 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002730 }
Chris Lattner4b009652007-07-25 00:24:17 +00002731 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2732 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002733 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002734 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2735 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002736 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002737 Record->setHasFlexibleArrayMember(true);
2738 } else {
2739 // If this is a struct/class and this is not the last element, reject
2740 // it. Note that GCC supports variable sized arrays in the middle of
2741 // structures.
2742 if (i != NumFields-1) {
2743 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2744 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002745 FD->setInvalidDecl();
2746 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002747 continue;
2748 }
Chris Lattner4b009652007-07-25 00:24:17 +00002749 // We support flexible arrays at the end of structs in other structs
2750 // as an extension.
2751 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2752 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002753 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002754 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002755 }
2756 }
2757 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002758 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00002759 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002760 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2761 FD->getName());
2762 FD->setInvalidDecl();
2763 EnclosingDecl->setInvalidDecl();
2764 continue;
2765 }
Chris Lattner4b009652007-07-25 00:24:17 +00002766 // Keep track of the number of named members.
2767 if (IdentifierInfo *II = FD->getIdentifier()) {
2768 // Detect duplicate member names.
2769 if (!FieldIDs.insert(II)) {
2770 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2771 // Find the previous decl.
2772 SourceLocation PrevLoc;
Chris Lattner504c5432008-10-12 00:28:42 +00002773 for (unsigned i = 0; ; ++i) {
2774 assert(i != RecFields.size() && "Didn't find previous def!");
Chris Lattner4b009652007-07-25 00:24:17 +00002775 if (RecFields[i]->getIdentifier() == II) {
2776 PrevLoc = RecFields[i]->getLocation();
2777 break;
2778 }
2779 }
2780 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002781 FD->setInvalidDecl();
2782 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002783 continue;
2784 }
2785 ++NumNamedMembers;
2786 }
Chris Lattner4b009652007-07-25 00:24:17 +00002787 }
2788
Chris Lattner4b009652007-07-25 00:24:17 +00002789 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00002790 if (Record) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002791 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +00002792 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2793 // Sema::ActOnFinishCXXClassDef.
2794 if (!isa<CXXRecordDecl>(Record))
2795 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002796 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00002797 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2798 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2799 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2800 else if (ObjCImplementationDecl *IMPDecl =
2801 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002802 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2803 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00002804 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00002805 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00002806 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00002807
2808 if (Attr)
2809 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002810}
2811
Steve Naroff0acc9c92007-09-15 18:49:24 +00002812Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00002813 DeclTy *lastEnumConst,
2814 SourceLocation IdLoc, IdentifierInfo *Id,
2815 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00002816 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002817 EnumConstantDecl *LastEnumConst =
2818 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2819 Expr *Val = static_cast<Expr*>(val);
2820
Chris Lattnera7549902007-08-26 06:24:45 +00002821 // The scope passed in may not be a decl scope. Zip up the scope tree until
2822 // we find one that is.
2823 while ((S->getFlags() & Scope::DeclScope) == 0)
2824 S = S->getParent();
2825
Chris Lattner4b009652007-07-25 00:24:17 +00002826 // Verify that there isn't already something declared with this name in this
2827 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00002828 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00002829 // When in C++, we may get a TagDecl with the same name; in this case the
2830 // enum constant will 'hide' the tag.
2831 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2832 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002833 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002834 if (isa<EnumConstantDecl>(PrevDecl))
2835 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2836 else
2837 Diag(IdLoc, diag::err_redefinition, Id->getName());
2838 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002839 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00002840 return 0;
2841 }
2842 }
2843
2844 llvm::APSInt EnumVal(32);
2845 QualType EltTy;
2846 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00002847 // Make sure to promote the operand type to int.
2848 UsualUnaryConversions(Val);
2849
Chris Lattner4b009652007-07-25 00:24:17 +00002850 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2851 SourceLocation ExpLoc;
2852 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2853 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2854 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002855 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00002856 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00002857 } else {
2858 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002859 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00002860 }
2861
2862 if (!Val) {
2863 if (LastEnumConst) {
2864 // Assign the last value + 1.
2865 EnumVal = LastEnumConst->getInitVal();
2866 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00002867
2868 // Check for overflow on increment.
2869 if (EnumVal < LastEnumConst->getInitVal())
2870 Diag(IdLoc, diag::warn_enum_value_overflow);
2871
Chris Lattnere7f53a42007-08-27 17:37:24 +00002872 EltTy = LastEnumConst->getType();
2873 } else {
2874 // First value, set to zero.
2875 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002876 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00002877 }
Chris Lattner4b009652007-07-25 00:24:17 +00002878 }
2879
Chris Lattnere4650482008-03-15 06:12:44 +00002880 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00002881 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2882 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00002883 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00002884
2885 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002886 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002887 return New;
2888}
2889
Steve Naroffb0726b82008-08-07 14:08:16 +00002890// FIXME: For consistency with ActOnFields(), we should have the parser
2891// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002892void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00002893 DeclTy **Elements, unsigned NumElements) {
2894 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Chris Lattner4b009652007-07-25 00:24:17 +00002895
Steve Naroffb0726b82008-08-07 14:08:16 +00002896 if (Enum && Enum->isDefinition()) {
2897 // Diagnose code like:
2898 // enum e0 {
2899 // E0 = sizeof(enum e0 { E1 })
2900 // };
2901 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2902 Enum->getName());
2903 Diag(EnumLoc, diag::err_previous_definition);
2904 Enum->setInvalidDecl();
2905 return;
2906 }
Chris Lattner435c3fd2007-08-28 05:10:31 +00002907 // TODO: If the result value doesn't fit in an int, it must be a long or long
2908 // long value. ISO C does not support this, but GCC does as an extension,
2909 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002910 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00002911
Chris Lattner206754a2007-08-28 06:15:15 +00002912 // Verify that all the values are okay, compute the size of the values, and
2913 // reverse the list.
2914 unsigned NumNegativeBits = 0;
2915 unsigned NumPositiveBits = 0;
2916
2917 // Keep track of whether all elements have type int.
2918 bool AllElementsInt = true;
2919
Chris Lattner4b009652007-07-25 00:24:17 +00002920 EnumConstantDecl *EltList = 0;
2921 for (unsigned i = 0; i != NumElements; ++i) {
2922 EnumConstantDecl *ECD =
2923 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2924 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002925
2926 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002927 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002928 assert(InitVal.getBitWidth() >= IntWidth &&
2929 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00002930 if (InitVal.getBitWidth() > IntWidth) {
2931 llvm::APSInt V(InitVal);
2932 V.trunc(IntWidth);
2933 V.extend(InitVal.getBitWidth());
2934 if (V != InitVal)
2935 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattneread053a2008-08-17 07:19:51 +00002936 InitVal.toString(10));
Chris Lattnercb33ae12007-08-28 05:27:00 +00002937 }
Chris Lattner206754a2007-08-28 06:15:15 +00002938
2939 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002940 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00002941 NumPositiveBits = std::max(NumPositiveBits,
2942 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00002943 else
Chris Lattneraff63f02008-01-14 21:47:29 +00002944 NumNegativeBits = std::max(NumNegativeBits,
2945 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00002946
Chris Lattner206754a2007-08-28 06:15:15 +00002947 // Keep track of whether every enum element has type int (very commmon).
2948 if (AllElementsInt)
2949 AllElementsInt = ECD->getType() == Context.IntTy;
2950
Chris Lattner4b009652007-07-25 00:24:17 +00002951 ECD->setNextDeclarator(EltList);
2952 EltList = ECD;
2953 }
2954
Chris Lattner206754a2007-08-28 06:15:15 +00002955 // Figure out the type that should be used for this enum.
2956 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2957 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002958 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00002959
2960 if (NumNegativeBits) {
2961 // If there is a negative value, figure out the smallest integer type (of
2962 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002963 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002964 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002965 BestWidth = IntWidth;
2966 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002967 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002968
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002969 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002970 BestType = Context.LongTy;
2971 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002972 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002973
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002974 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002975 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2976 BestType = Context.LongLongTy;
2977 }
2978 }
2979 } else {
2980 // If there is no negative value, figure out which of uint, ulong, ulonglong
2981 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002982 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002983 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002984 BestWidth = IntWidth;
2985 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00002986 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00002987 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002988 } else {
2989 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002990 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00002991 "How could an initializer get larger than ULL?");
2992 BestType = Context.UnsignedLongLongTy;
2993 }
2994 }
2995
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002996 // Loop over all of the enumerator constants, changing their types to match
2997 // the type of the enum if needed.
2998 for (unsigned i = 0; i != NumElements; ++i) {
2999 EnumConstantDecl *ECD =
3000 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3001 if (!ECD) continue; // Already issued a diagnostic.
3002
3003 // Standard C says the enumerators have int type, but we allow, as an
3004 // extension, the enumerators to be larger than int size. If each
3005 // enumerator value fits in an int, type it as an int, otherwise type it the
3006 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3007 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003008 if (ECD->getType() == Context.IntTy) {
3009 // Make sure the init value is signed.
3010 llvm::APSInt IV = ECD->getInitVal();
3011 IV.setIsSigned(true);
3012 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003013 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003014 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003015
3016 // Determine whether the value fits into an int.
3017 llvm::APSInt InitVal = ECD->getInitVal();
3018 bool FitsInInt;
3019 if (InitVal.isUnsigned() || !InitVal.isNegative())
3020 FitsInInt = InitVal.getActiveBits() < IntWidth;
3021 else
3022 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3023
3024 // If it fits into an integer type, force it. Otherwise force it to match
3025 // the enum decl type.
3026 QualType NewTy;
3027 unsigned NewWidth;
3028 bool NewSign;
3029 if (FitsInInt) {
3030 NewTy = Context.IntTy;
3031 NewWidth = IntWidth;
3032 NewSign = true;
3033 } else if (ECD->getType() == BestType) {
3034 // Already the right type!
3035 continue;
3036 } else {
3037 NewTy = BestType;
3038 NewWidth = BestWidth;
3039 NewSign = BestType->isSignedIntegerType();
3040 }
3041
3042 // Adjust the APSInt value.
3043 InitVal.extOrTrunc(NewWidth);
3044 InitVal.setIsSigned(NewSign);
3045 ECD->setInitVal(InitVal);
3046
3047 // Adjust the Expr initializer and type.
Douglas Gregor70d26122008-11-12 17:17:38 +00003048 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3049 /*isLvalue=*/false));
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003050 ECD->setType(NewTy);
3051 }
Chris Lattner206754a2007-08-28 06:15:15 +00003052
Chris Lattner90a018d2007-08-28 18:24:31 +00003053 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003054 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003055}
3056
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003057Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3058 ExprTy *expr) {
3059 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
3060
Chris Lattner81db64a2008-03-16 00:16:02 +00003061 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003062}
3063
Chris Lattner806a5f52008-01-12 07:05:38 +00003064Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00003065 SourceLocation LBrace,
3066 SourceLocation RBrace,
3067 const char *Lang,
3068 unsigned StrSize,
3069 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00003070 LinkageSpecDecl::LanguageIDs Language;
3071 Decl *dcl = static_cast<Decl *>(D);
3072 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3073 Language = LinkageSpecDecl::lang_c;
3074 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3075 Language = LinkageSpecDecl::lang_cxx;
3076 else {
3077 Diag(Loc, diag::err_bad_language);
3078 return 0;
3079 }
3080
3081 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00003082 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00003083}
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003084
3085void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3086 ExprTy *alignment, SourceLocation PragmaLoc,
3087 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3088 Expr *Alignment = static_cast<Expr *>(alignment);
3089
3090 // If specified then alignment must be a "small" power of two.
3091 unsigned AlignmentVal = 0;
3092 if (Alignment) {
3093 llvm::APSInt Val;
3094 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3095 !Val.isPowerOf2() ||
3096 Val.getZExtValue() > 16) {
3097 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3098 delete Alignment;
3099 return; // Ignore
3100 }
3101
3102 AlignmentVal = (unsigned) Val.getZExtValue();
3103 }
3104
3105 switch (Kind) {
3106 case Action::PPK_Default: // pack([n])
3107 PackContext.setAlignment(AlignmentVal);
3108 break;
3109
3110 case Action::PPK_Show: // pack(show)
3111 // Show the current alignment, making sure to show the right value
3112 // for the default.
3113 AlignmentVal = PackContext.getAlignment();
3114 // FIXME: This should come from the target.
3115 if (AlignmentVal == 0)
3116 AlignmentVal = 8;
3117 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal));
3118 break;
3119
3120 case Action::PPK_Push: // pack(push [, id] [, [n])
3121 PackContext.push(Name);
3122 // Set the new alignment if specified.
3123 if (Alignment)
3124 PackContext.setAlignment(AlignmentVal);
3125 break;
3126
3127 case Action::PPK_Pop: // pack(pop [, id] [, n])
3128 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3129 // "#pragma pack(pop, identifier, n) is undefined"
3130 if (Alignment && Name)
3131 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3132
3133 // Do the pop.
3134 if (!PackContext.pop(Name)) {
3135 // If a name was specified then failure indicates the name
3136 // wasn't found. Otherwise failure indicates the stack was
3137 // empty.
3138 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
3139 Name ? "no record matching name" : "stack empty");
3140
3141 // FIXME: Warn about popping named records as MSVC does.
3142 } else {
3143 // Pop succeeded, set the new alignment if specified.
3144 if (Alignment)
3145 PackContext.setAlignment(AlignmentVal);
3146 }
3147 break;
3148
3149 default:
3150 assert(0 && "Invalid #pragma pack kind.");
3151 }
3152}
3153
3154bool PragmaPackStack::pop(IdentifierInfo *Name) {
3155 if (Stack.empty())
3156 return false;
3157
3158 // If name is empty just pop top.
3159 if (!Name) {
3160 Alignment = Stack.back().first;
3161 Stack.pop_back();
3162 return true;
3163 }
3164
3165 // Otherwise, find the named record.
3166 for (unsigned i = Stack.size(); i != 0; ) {
3167 --i;
3168 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) {
3169 // Found it, pop up to and including this record.
3170 Alignment = Stack[i].first;
3171 Stack.erase(Stack.begin() + i, Stack.end());
3172 return true;
3173 }
3174 }
3175
3176 return false;
3177}