blob: fc412a605edfe7df38880035ad0861740e8e7498 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
Daniel Dunbar4cde9272008-10-14 05:35:18 +000028#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000031Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S,
32 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-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 Naroffb327ce02008-04-02 14:35:35 +000040
Douglas Gregor2ce52f32008-04-13 21:07:44 +000041 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
42 isa<ObjCInterfaceDecl>(IIDecl) ||
43 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000044 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000045 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000046}
47
Douglas Gregor2f1bc522008-11-07 20:08:42 +000048std::string Sema::getTypeAsString(TypeTy *Type) {
49 QualType Ty = QualType::getFromOpaquePtr(Type);
50 return Ty.getAsString();
51}
52
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000053DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000054 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000055 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000056 if (MD->isOutOfLineDefinition())
57 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000058
59 // A C++ inline method is parsed *after* the topmost class it was declared in
60 // is fully parsed (it's "complete").
61 // The parsing of a C++ inline method happens at the declaration context of
62 // the topmost (non-nested) class it is declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000063 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
64 DC = MD->getParent();
65 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
66 DC = RD;
67
68 // Return the declaration context of the topmost class the inline method is
69 // declared in.
70 return DC;
71 }
72
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000073 if (isa<ObjCMethodDecl>(DC))
74 return Context.getTranslationUnitDecl();
75
76 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
77 return SD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000078
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000079 return DC->getParent();
80}
81
Chris Lattner9fdf9c62008-04-22 18:39:57 +000082void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000083 assert(getContainingDC(DC) == CurContext &&
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000084 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000085 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000086}
87
Chris Lattnerb048c982008-04-06 04:47:34 +000088void Sema::PopDeclContext() {
89 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000090 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000091}
92
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000093/// Add this decl to the scope shadowed decl chains.
94void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000095 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000096
97 // C++ [basic.scope]p4:
98 // -- exactly one declaration shall declare a class name or
99 // enumeration name that is not a typedef name and the other
100 // declarations shall all refer to the same object or
101 // enumerator, or all refer to functions and function templates;
102 // in this case the class name or enumeration name is hidden.
103 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
104 // We are pushing the name of a tag (enum or class).
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000105 IdentifierResolver::iterator
106 I = IdResolver.begin(TD->getIdentifier(),
107 TD->getDeclContext(), false/*LookInParentCtx*/);
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000108 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000109 // There is already a declaration with the same name in the same
110 // scope. It must be found before we find the new declaration,
111 // so swap the order on the shadowed declaration chain.
112
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000113 IdResolver.AddShadowedDecl(TD, *I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000114 return;
115 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000116 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
117 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000118 // We are pushing the name of a function, which might be an
119 // overloaded name.
120 IdentifierResolver::iterator
121 I = IdResolver.begin(FD->getIdentifier(),
122 FD->getDeclContext(), false/*LookInParentCtx*/);
123 if (I != IdResolver.end() &&
124 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
125 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
126 // There is already a declaration with the same name in the same
127 // scope. It must be a function or an overloaded function.
128 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
129 if (!Ovl) {
130 // We haven't yet overloaded this function. Take the existing
131 // FunctionDecl and put it into an OverloadedFunctionDecl.
132 Ovl = OverloadedFunctionDecl::Create(Context,
133 FD->getDeclContext(),
134 FD->getIdentifier());
135 Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
136
137 // Remove the name binding to the existing FunctionDecl...
138 IdResolver.RemoveDecl(*I);
139
140 // ... and put the OverloadedFunctionDecl in its place.
141 IdResolver.AddDecl(Ovl);
142 }
143
144 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
145 // to its list of overloads.
146 Ovl->addOverload(FD);
147
148 return;
149 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000150 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000151
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000152 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000153}
154
Steve Naroffb216c882007-10-09 22:01:59 +0000155void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000156 if (S->decl_empty()) return;
157 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000158
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
160 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000161 Decl *TmpD = static_cast<Decl*>(*I);
162 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000163
164 if (isa<CXXFieldDecl>(TmpD)) continue;
165
166 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
167 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000168
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 IdentifierInfo *II = D->getIdentifier();
170 if (!II) continue;
171
Ted Kremeneka89d1972008-09-03 18:03:35 +0000172 // We only want to remove the decls from the identifier decl chains for
173 // local scopes, when inside a function/method.
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000174 if (S->getFnParent() != 0)
175 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000176
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000177 // Chain this decl to the containing DeclContext.
178 D->setNext(CurContext->getDeclChain());
179 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000180 }
181}
182
Steve Naroffe8043c32008-04-01 23:04:06 +0000183/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
184/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000185ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000186 // The third "scope" argument is 0 since we aren't enabling lazy built-in
187 // creation from this context.
188 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000189
Steve Naroffb327ce02008-04-02 14:35:35 +0000190 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000191}
192
Steve Naroffe8043c32008-04-01 23:04:06 +0000193/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000194/// namespace.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000195Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000196 const DeclContext *LookupCtx,
197 bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000199 unsigned NS = NSI;
200 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
201 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000202
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000203 IdentifierResolver::iterator
204 I = LookupCtx ? IdResolver.begin(II, LookupCtx, false/*LookInParentCtx*/) :
205 IdResolver.begin(II, CurContext, true/*LookInParentCtx*/);
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 // Scan up the scope chain looking for a decl that matches this identifier
207 // that is in the appropriate namespace. This search should not take long, as
208 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000209 for (; I != IdResolver.end(); ++I)
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000210 if ((*I)->getIdentifierNamespace() & NS)
211 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000212
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 // If we didn't find a use of this identifier, and if the identifier
214 // corresponds to a compiler builtin, create the decl object for the builtin
215 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000216 if (NS & Decl::IDNS_Ordinary) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000217 if (enableLazyBuiltinCreation &&
218 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000219 // If this is a builtin on this (or all) targets, create the decl.
220 if (unsigned BuiltinID = II->getBuiltinID())
221 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
222 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000223 if (getLangOptions().ObjC1) {
224 // @interface and @compatibility_alias introduce typedef-like names.
225 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000226 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000227 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000228 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
229 if (IDI != ObjCInterfaceDecls.end())
230 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000231 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
232 if (I != ObjCAliasDecls.end())
233 return I->second->getClassInterface();
234 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 }
236 return 0;
237}
238
Chris Lattner95e2c712008-05-05 22:18:14 +0000239void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000240 if (!Context.getBuiltinVaListType().isNull())
241 return;
242
243 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000244 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000245 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000246 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
247}
248
Reid Spencer5f016e22007-07-11 17:01:13 +0000249/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
250/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000251ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
252 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000253 Builtin::ID BID = (Builtin::ID)bid;
254
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000255 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000256 InitBuiltinVaListType();
257
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000258 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000259 FunctionDecl *New = FunctionDecl::Create(Context,
260 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000261 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000262 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000263
Chris Lattner95e2c712008-05-05 22:18:14 +0000264 // Create Decl objects for each parameter, adding them to the
265 // FunctionDecl.
266 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
267 llvm::SmallVector<ParmVarDecl*, 16> Params;
268 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
269 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
270 FT->getArgType(i), VarDecl::None, 0,
271 0));
272 New->setParams(&Params[0], Params.size());
273 }
274
275
276
Chris Lattner7f925cc2008-04-11 07:00:53 +0000277 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000278 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 return New;
280}
281
Sebastian Redlc42e1182008-11-11 11:37:55 +0000282/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
283/// everything from the standard library is defined.
284NamespaceDecl *Sema::GetStdNamespace() {
285 if (!StdNamespace) {
286 DeclContext *Global = Context.getTranslationUnitDecl();
287 Decl *Std = LookupDecl(Ident_StdNs, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
288 0, Global, /*enableLazyBuiltinCreation=*/false);
289 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
290 }
291 return StdNamespace;
292}
293
Reid Spencer5f016e22007-07-11 17:01:13 +0000294/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
295/// and scope as a previous declaration 'Old'. Figure out how to resolve this
296/// situation, merging decls or emitting diagnostics as appropriate.
297///
Steve Naroffe8043c32008-04-01 23:04:06 +0000298TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000299 // Allow multiple definitions for ObjC built-in typedefs.
300 // FIXME: Verify the underlying types are equivalent!
301 if (getLangOptions().ObjC1) {
302 const IdentifierInfo *typeIdent = New->getIdentifier();
303 if (typeIdent == Ident_id) {
304 Context.setObjCIdType(New);
305 return New;
306 } else if (typeIdent == Ident_Class) {
307 Context.setObjCClassType(New);
308 return New;
309 } else if (typeIdent == Ident_SEL) {
310 Context.setObjCSelType(New);
311 return New;
312 } else if (typeIdent == Ident_Protocol) {
313 Context.setObjCProtoType(New->getUnderlyingType());
314 return New;
315 }
316 // Fall through - the typedef name was not a builtin type.
317 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000318 // Verify the old decl was also a typedef.
319 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
320 if (!Old) {
321 Diag(New->getLocation(), diag::err_redefinition_different_kind,
322 New->getName());
323 Diag(OldD->getLocation(), diag::err_previous_definition);
324 return New;
325 }
326
Chris Lattner99cb9972008-07-25 18:44:27 +0000327 // If the typedef types are not identical, reject them in all languages and
328 // with any extensions enabled.
329 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
330 Context.getCanonicalType(Old->getUnderlyingType()) !=
331 Context.getCanonicalType(New->getUnderlyingType())) {
332 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
333 New->getUnderlyingType().getAsString(),
334 Old->getUnderlyingType().getAsString());
335 Diag(Old->getLocation(), diag::err_previous_definition);
336 return Old;
337 }
338
Eli Friedman54ecfce2008-06-11 06:20:39 +0000339 if (getLangOptions().Microsoft) return New;
340
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000341 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
342 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
343 // *either* declaration is in a system header. The code below implements
344 // this adhoc compatibility rule. FIXME: The following code will not
345 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000346 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
347 SourceManager &SrcMgr = Context.getSourceManager();
348 if (SrcMgr.isInSystemHeader(Old->getLocation()))
349 return New;
350 if (SrcMgr.isInSystemHeader(New->getLocation()))
351 return New;
352 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000353
Ted Kremenek2d05c082008-05-23 21:28:18 +0000354 Diag(New->getLocation(), diag::err_redefinition, New->getName());
355 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 return New;
357}
358
Chris Lattner6b6b5372008-06-26 18:38:35 +0000359/// DeclhasAttr - returns true if decl Declaration already has the target
360/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000361static bool DeclHasAttr(const Decl *decl, const Attr *target) {
362 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
363 if (attr->getKind() == target->getKind())
364 return true;
365
366 return false;
367}
368
369/// MergeAttributes - append attributes from the Old decl to the New one.
370static void MergeAttributes(Decl *New, Decl *Old) {
371 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
372
Chris Lattnerddee4232008-03-03 03:28:21 +0000373 while (attr) {
374 tmp = attr;
375 attr = attr->getNext();
376
377 if (!DeclHasAttr(New, tmp)) {
378 New->addAttr(tmp);
379 } else {
380 tmp->setNext(0);
381 delete(tmp);
382 }
383 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000384
385 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000386}
387
Chris Lattner04421082008-04-08 04:40:51 +0000388/// MergeFunctionDecl - We just parsed a function 'New' from
389/// declarator D which has the same name and scope as a previous
390/// declaration 'Old'. Figure out how to resolve this situation,
391/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000392/// Redeclaration will be set true if this New is a redeclaration OldD.
393///
394/// In C++, New and Old must be declarations that are not
395/// overloaded. Use IsOverload to determine whether New and Old are
396/// overloaded, and to select the Old declaration that New should be
397/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000398FunctionDecl *
399Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000400 assert(!isa<OverloadedFunctionDecl>(OldD) &&
401 "Cannot merge with an overloaded function declaration");
402
Douglas Gregorf0097952008-04-21 02:02:58 +0000403 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 // Verify the old decl was also a function.
405 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
406 if (!Old) {
407 Diag(New->getLocation(), diag::err_redefinition_different_kind,
408 New->getName());
409 Diag(OldD->getLocation(), diag::err_previous_definition);
410 return New;
411 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000412
413 // Determine whether the previous declaration was a definition,
414 // implicit declaration, or a declaration.
415 diag::kind PrevDiag;
416 if (Old->isThisDeclarationADefinition())
417 PrevDiag = diag::err_previous_definition;
418 else if (Old->isImplicit())
419 PrevDiag = diag::err_previous_implicit_declaration;
420 else
421 PrevDiag = diag::err_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000422
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000423 QualType OldQType = Context.getCanonicalType(Old->getType());
424 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000425
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000426 if (getLangOptions().CPlusPlus) {
427 // (C++98 13.1p2):
428 // Certain function declarations cannot be overloaded:
429 // -- Function declarations that differ only in the return type
430 // cannot be overloaded.
431 QualType OldReturnType
432 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
433 QualType NewReturnType
434 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
435 if (OldReturnType != NewReturnType) {
436 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
437 Diag(Old->getLocation(), PrevDiag);
438 return New;
439 }
440
441 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
442 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
443 if (OldMethod && NewMethod) {
444 // -- Member function declarations with the same name and the
445 // same parameter types cannot be overloaded if any of them
446 // is a static member function declaration.
447 if (OldMethod->isStatic() || NewMethod->isStatic()) {
448 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
449 Diag(Old->getLocation(), PrevDiag);
450 return New;
451 }
452 }
453
454 // (C++98 8.3.5p3):
455 // All declarations for a function shall agree exactly in both the
456 // return type and the parameter-type-list.
457 if (OldQType == NewQType) {
458 // We have a redeclaration.
459 MergeAttributes(New, Old);
460 Redeclaration = true;
461 return MergeCXXFunctionDecl(New, Old);
462 }
463
464 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000465 }
Chris Lattner04421082008-04-08 04:40:51 +0000466
467 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000468 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000469 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000470 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000471 MergeAttributes(New, Old);
472 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000473 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000474 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000475
Steve Naroff837618c2008-01-16 15:01:34 +0000476 // A function that has already been declared has been redeclared or defined
477 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000478
Reid Spencer5f016e22007-07-11 17:01:13 +0000479 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
480 // TODO: This is totally simplistic. It should handle merging functions
481 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000482 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
483 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 return New;
485}
486
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000487/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000488static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000489 if (VD->isFileVarDecl())
490 return (!VD->getInit() &&
491 (VD->getStorageClass() == VarDecl::None ||
492 VD->getStorageClass() == VarDecl::Static));
493 return false;
494}
495
496/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
497/// when dealing with C "tentative" external object definitions (C99 6.9.2).
498void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
499 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000500 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000501
502 for (IdentifierResolver::iterator
503 I = IdResolver.begin(VD->getIdentifier(),
504 VD->getDeclContext(), false/*LookInParentCtx*/),
505 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000506 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000507 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
508
Steve Narofff855e6f2008-08-10 15:20:13 +0000509 // Handle the following case:
510 // int a[10];
511 // int a[]; - the code below makes sure we set the correct type.
512 // int a[11]; - this is an error, size isn't 10.
513 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
514 OldDecl->getType()->isConstantArrayType())
515 VD->setType(OldDecl->getType());
516
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000517 // Check for "tentative" definitions. We can't accomplish this in
518 // MergeVarDecl since the initializer hasn't been attached.
519 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
520 continue;
521
522 // Handle __private_extern__ just like extern.
523 if (OldDecl->getStorageClass() != VarDecl::Extern &&
524 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
525 VD->getStorageClass() != VarDecl::Extern &&
526 VD->getStorageClass() != VarDecl::PrivateExtern) {
527 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
528 Diag(OldDecl->getLocation(), diag::err_previous_definition);
529 }
530 }
531 }
532}
533
Reid Spencer5f016e22007-07-11 17:01:13 +0000534/// MergeVarDecl - We just parsed a variable 'New' which has the same name
535/// and scope as a previous declaration 'Old'. Figure out how to resolve this
536/// situation, merging decls or emitting diagnostics as appropriate.
537///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000538/// Tentative definition rules (C99 6.9.2p2) are checked by
539/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
540/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000541///
Steve Naroffe8043c32008-04-01 23:04:06 +0000542VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 // Verify the old decl was also a variable.
544 VarDecl *Old = dyn_cast<VarDecl>(OldD);
545 if (!Old) {
546 Diag(New->getLocation(), diag::err_redefinition_different_kind,
547 New->getName());
548 Diag(OldD->getLocation(), diag::err_previous_definition);
549 return New;
550 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000551
552 MergeAttributes(New, Old);
553
Reid Spencer5f016e22007-07-11 17:01:13 +0000554 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000555 QualType OldCType = Context.getCanonicalType(Old->getType());
556 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000557 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000558 Diag(New->getLocation(), diag::err_redefinition, New->getName());
559 Diag(Old->getLocation(), diag::err_previous_definition);
560 return New;
561 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000562 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
563 if (New->getStorageClass() == VarDecl::Static &&
564 (Old->getStorageClass() == VarDecl::None ||
565 Old->getStorageClass() == VarDecl::Extern)) {
566 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
567 Diag(Old->getLocation(), diag::err_previous_definition);
568 return New;
569 }
570 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
571 if (New->getStorageClass() != VarDecl::Static &&
572 Old->getStorageClass() == VarDecl::Static) {
573 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
574 Diag(Old->getLocation(), diag::err_previous_definition);
575 return New;
576 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000577 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
578 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 Diag(New->getLocation(), diag::err_redefinition, New->getName());
580 Diag(Old->getLocation(), diag::err_previous_definition);
581 }
582 return New;
583}
584
Chris Lattner04421082008-04-08 04:40:51 +0000585/// CheckParmsForFunctionDef - Check that the parameters of the given
586/// function are appropriate for the definition of a function. This
587/// takes care of any checks that cannot be performed on the
588/// declaration itself, e.g., that the types of each of the function
589/// parameters are complete.
590bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
591 bool HasInvalidParm = false;
592 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
593 ParmVarDecl *Param = FD->getParamDecl(p);
594
595 // C99 6.7.5.3p4: the parameters in a parameter type list in a
596 // function declarator that is part of a function definition of
597 // that function shall not have incomplete type.
598 if (Param->getType()->isIncompleteType() &&
599 !Param->isInvalidDecl()) {
600 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
601 Param->getType().getAsString());
602 Param->setInvalidDecl();
603 HasInvalidParm = true;
604 }
605 }
606
607 return HasInvalidParm;
608}
609
Reid Spencer5f016e22007-07-11 17:01:13 +0000610/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
611/// no declarator (e.g. "struct foo;") is parsed.
612Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
613 // TODO: emit error on 'int;' or 'const enum foo;'.
614 // TODO: emit error on 'typedef int;'
615 // if (!DS.isMissingDeclaratorOk()) Diag(...);
616
Steve Naroff92199282007-11-17 21:37:36 +0000617 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000618}
619
Steve Naroffd0091aa2008-01-10 22:15:12 +0000620bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000621 // Get the type before calling CheckSingleAssignmentConstraints(), since
622 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000623 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000624
Chris Lattner5cf216b2008-01-04 18:04:52 +0000625 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
626 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
627 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000628}
629
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000630bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000631 const ArrayType *AT = Context.getAsArrayType(DeclT);
632
633 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000634 // C99 6.7.8p14. We have an array of character type with unknown size
635 // being initialized to a string literal.
636 llvm::APSInt ConstVal(32);
637 ConstVal = strLiteral->getByteLength() + 1;
638 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000639 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000640 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000641 } else {
642 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000643 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000644 // FIXME: Avoid truncation for 64-bit length strings.
645 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000646 Diag(strLiteral->getSourceRange().getBegin(),
647 diag::warn_initializer_string_for_char_array_too_long,
648 strLiteral->getSourceRange());
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000649 }
650 // Set type from "char *" to "constant array of char".
651 strLiteral->setType(DeclT);
652 // For now, we always return false (meaning success).
653 return false;
654}
655
656StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000657 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000658 if (AT && AT->getElementType()->isCharType()) {
659 return dyn_cast<StringLiteral>(Init);
660 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000661 return 0;
662}
663
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000664bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
665 SourceLocation InitLoc,
666 std::string InitEntity) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000667 // C++ [dcl.init.ref]p1:
668 // A variable declared to be a T&, that is “reference to type T”
669 // (8.3.2), shall be initialized by an object, or function, of
670 // type T or by an object that can be converted into a T.
671 if (DeclType->isReferenceType())
672 return CheckReferenceInit(Init, DeclType);
673
Steve Naroffca107302008-01-21 23:53:58 +0000674 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
675 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000676 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000677 return Diag(InitLoc,
Steve Naroffca107302008-01-21 23:53:58 +0000678 diag::err_variable_object_no_init,
679 VAT->getSizeExpr()->getSourceRange());
680
Steve Naroff2fdc3742007-12-10 22:44:33 +0000681 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
682 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000683 // FIXME: Handle wide strings
684 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
685 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000686
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000687 // C++ [dcl.init]p14:
688 // -- If the destination type is a (possibly cv-qualified) class
689 // type:
690 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
691 QualType DeclTypeC = Context.getCanonicalType(DeclType);
692 QualType InitTypeC = Context.getCanonicalType(Init->getType());
693
694 // -- If the initialization is direct-initialization, or if it is
695 // copy-initialization where the cv-unqualified version of the
696 // source type is the same class as, or a derived class of, the
697 // class of the destination, constructors are considered.
698 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
699 IsDerivedFrom(InitTypeC, DeclTypeC)) {
700 CXXConstructorDecl *Constructor
701 = PerformInitializationByConstructor(DeclType, &Init, 1,
702 InitLoc, Init->getSourceRange(),
703 InitEntity, IK_Copy);
704 return Constructor == 0;
705 }
706
707 // -- Otherwise (i.e., for the remaining copy-initialization
708 // cases), user-defined conversion sequences that can
709 // convert from the source type to the destination type or
710 // (when a conversion function is used) to a derived class
711 // thereof are enumerated as described in 13.3.1.4, and the
712 // best one is chosen through overload resolution
713 // (13.3). If the conversion cannot be done or is
714 // ambiguous, the initialization is ill-formed. The
715 // function selected is called with the initializer
716 // expression as its argument; if the function is a
717 // constructor, the call initializes a temporary of the
718 // destination type.
719 // FIXME: We're pretending to do copy elision here; return to
720 // this when we have ASTs for such things.
721 if (PerformImplicitConversion(Init, DeclType))
722 return Diag(InitLoc,
723 diag::err_typecheck_convert_incompatible,
724 DeclType.getAsString(), InitEntity,
725 "initializing",
726 Init->getSourceRange());
727 else
728 return false;
729 }
730
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000731 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000732 if (DeclType->isArrayType())
733 return Diag(Init->getLocStart(),
734 diag::err_array_init_list_required,
735 Init->getSourceRange());
736
Steve Naroffd0091aa2008-01-10 22:15:12 +0000737 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000738 } else if (getLangOptions().CPlusPlus) {
739 // C++ [dcl.init]p14:
740 // [...] If the class is an aggregate (8.5.1), and the initializer
741 // is a brace-enclosed list, see 8.5.1.
742 //
743 // Note: 8.5.1 is handled below; here, we diagnose the case where
744 // we have an initializer list and a destination type that is not
745 // an aggregate.
746 // FIXME: In C++0x, this is yet another form of initialization.
747 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
748 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
749 if (!ClassDecl->isAggregate())
750 return Diag(InitLoc,
751 diag::err_init_non_aggr_init_list,
752 DeclType.getAsString(),
753 Init->getSourceRange());
754 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000755 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000756
Steve Naroff0cca7492008-05-01 22:18:59 +0000757 InitListChecker CheckInitList(this, InitList, DeclType);
758 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000759}
760
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000761Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000762Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000763 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 IdentifierInfo *II = D.getIdentifier();
765
Chris Lattnere80a59c2007-07-25 00:24:17 +0000766 // All of these full declarators require an identifier. If it doesn't have
767 // one, the ParsedFreeStandingDeclSpec action should be used.
768 if (II == 0) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +0000769 if (!D.getInvalidType()) // Reject this if we think it is valid.
770 Diag(D.getDeclSpec().getSourceRange().getBegin(),
771 diag::err_declarator_need_ident,
772 D.getDeclSpec().getSourceRange(), D.getSourceRange());
Chris Lattnere80a59c2007-07-25 00:24:17 +0000773 return 0;
774 }
775
Chris Lattner31e05722007-08-26 06:24:45 +0000776 // The scope passed in may not be a decl scope. Zip up the scope tree until
777 // we find one that is.
778 while ((S->getFlags() & Scope::DeclScope) == 0)
779 S = S->getParent();
780
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000781 DeclContext *DC;
782 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +0000783 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000784 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000785
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000786 // See if this is a redefinition of a variable in the same scope.
787 if (!D.getCXXScopeSpec().isSet()) {
788 DC = CurContext;
789 PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
790 } else { // Something like "int foo::x;"
791 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
792 PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S, DC);
793
794 // C++ 7.3.1.2p2:
795 // Members (including explicit specializations of templates) of a named
796 // namespace can also be defined outside that namespace by explicit
797 // qualification of the name being defined, provided that the entity being
798 // defined was already declared in the namespace and the definition appears
799 // after the point of declaration in a namespace that encloses the
800 // declarations namespace.
801 //
802 if (PrevDecl == 0) {
803 // No previous declaration in the qualifying scope.
804 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member,
805 II->getName(), D.getCXXScopeSpec().getRange());
806 } else if (!CurContext->Encloses(DC)) {
807 // The qualifying scope doesn't enclose the original declaration.
808 // Emit diagnostic based on current scope.
809 SourceLocation L = D.getIdentifierLoc();
810 SourceRange R = D.getCXXScopeSpec().getRange();
811 if (isa<FunctionDecl>(CurContext)) {
812 Diag(L, diag::err_invalid_declarator_in_function, II->getName(), R);
813 } else {
814 Diag(L, diag::err_invalid_declarator_scope, II->getName(),
815 cast<NamedDecl>(DC)->getName(), R);
816 }
817 }
818 }
819
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000820 // In C++, the previous declaration we find might be a tag type
821 // (class or enum). In this case, the new declaration will hide the
822 // tag type.
823 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
824 PrevDecl = 0;
825
Chris Lattner41af0932007-11-14 06:34:38 +0000826 QualType R = GetTypeForDeclarator(D, S);
827 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
828
Reid Spencer5f016e22007-07-11 17:01:13 +0000829 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000830 // Check that there are no default arguments (C++ only).
831 if (getLangOptions().CPlusPlus)
832 CheckExtraCXXDefaultArguments(D);
833
Chris Lattner41af0932007-11-14 06:34:38 +0000834 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000835 if (!NewTD) return 0;
836
837 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000838 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000839 // Merge the decl with the existing one if appropriate. If the decl is
840 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000841 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000842 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
843 if (NewTD == 0) return 0;
844 }
845 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000846 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000847 // C99 6.7.7p2: If a typedef name specifies a variably modified type
848 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000849 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
850 // FIXME: Diagnostic needs to be fixed.
851 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000852 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000853 }
854 }
Chris Lattner41af0932007-11-14 06:34:38 +0000855 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000856 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000857 switch (D.getDeclSpec().getStorageClassSpec()) {
858 default: assert(0 && "Unknown storage class!");
859 case DeclSpec::SCS_auto:
860 case DeclSpec::SCS_register:
861 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
862 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000863 InvalidDecl = true;
864 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000865 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
866 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
867 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000868 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000869 }
870
Chris Lattnera98e58d2008-03-15 21:24:04 +0000871 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +0000872 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +0000873 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
874
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000875 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +0000876 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +0000877 // This is a C++ constructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000878 assert(DC->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +0000879 "Constructors can only be declared in a member context");
880
Douglas Gregor42a552f2008-11-05 20:51:48 +0000881 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +0000882
883 // Create the new declaration
884 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000885 cast<CXXRecordDecl>(DC),
Douglas Gregorb48fe382008-10-31 09:07:45 +0000886 D.getIdentifierLoc(), II, R,
887 isExplicit, isInline,
888 /*isImplicitlyDeclared=*/false);
889
Douglas Gregor42a552f2008-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.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000894 if (DC->isCXXRecord()) {
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000895 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000896
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000897 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000898 cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000899 D.getIdentifierLoc(), II, R,
900 isInline,
901 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000902
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000903 if (isInvalidDecl)
904 NewFD->setInvalidDecl();
905 } else {
906 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
907 // Create a FunctionDecl to satisfy the function definition parsing
908 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000909 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000910 II, R, SC, isInline, LastDeclarator,
911 // FIXME: Move to DeclGroup...
912 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000913 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000914 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000915 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000916 if (!DC->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000917 Diag(D.getIdentifierLoc(),
918 diag::err_conv_function_not_member);
919 return 0;
920 } else {
921 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
922
923 NewFD = CXXConversionDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000924 cast<CXXRecordDecl>(DC),
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000925 D.getIdentifierLoc(), II, R,
926 isInline, isExplicit);
927
928 if (isInvalidDecl)
929 NewFD->setInvalidDecl();
930 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000931 } else if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000932 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000933 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000934 D.getIdentifierLoc(), II, R,
935 (SC == FunctionDecl::Static), isInline,
936 LastDeclarator);
937 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000938 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000939 D.getIdentifierLoc(),
Steve Naroff0eb07bf2008-10-03 00:02:03 +0000940 II, R, SC, isInline, LastDeclarator,
941 // FIXME: Move to DeclGroup...
942 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000943 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000944 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000945 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000946
Daniel Dunbara80f8742008-08-05 01:35:17 +0000947 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +0000948 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +0000949 // The parser guarantees this is a string.
950 StringLiteral *SE = cast<StringLiteral>(E);
951 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
952 SE->getByteLength())));
953 }
954
Chris Lattner04421082008-04-08 04:40:51 +0000955 // Copy the parameter declarations from the declarator D to
956 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000957 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000958 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
959
960 // Create Decl objects for each parameter, adding them to the
961 // FunctionDecl.
962 llvm::SmallVector<ParmVarDecl*, 16> Params;
963
964 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
965 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000966 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000967 // We let through "const void" here because Sema::GetTypeForDeclarator
968 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000969 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
970 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000971 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
972 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000973 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
974
Chris Lattnerdef026a2008-04-10 02:26:16 +0000975 // In C++, the empty parameter-type-list must be spelled "void"; a
976 // typedef of void is not permitted.
977 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000978 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000979 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
980 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000981 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000982 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
983 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
984 }
985
986 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +0000987 } else if (R->getAsTypedefType()) {
988 // When we're declaring a function with a typedef, as in the
989 // following example, we'll need to synthesize (unnamed)
990 // parameters for use in the declaration.
991 //
992 // @code
993 // typedef void fn(int);
994 // fn f;
995 // @endcode
996 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
997 if (!FT) {
998 // This is a typedef of a function with no prototype, so we
999 // don't need to do anything.
1000 } else if ((FT->getNumArgs() == 0) ||
1001 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1002 FT->getArgType(0)->isVoidType())) {
1003 // This is a zero-argument function. We don't need to do anything.
1004 } else {
1005 // Synthesize a parameter for each argument type.
1006 llvm::SmallVector<ParmVarDecl*, 16> Params;
1007 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1008 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001009 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001010 SourceLocation(), 0,
1011 *ArgType, VarDecl::None,
1012 0, 0));
1013 }
1014
1015 NewFD->setParams(&Params[0], Params.size());
1016 }
Chris Lattner04421082008-04-08 04:40:51 +00001017 }
1018
Douglas Gregor42a552f2008-11-05 20:51:48 +00001019 // C++ constructors and destructors are handled by separate
1020 // routines, since they don't require any declaration merging (C++
1021 // [class.mfct]p2) and they aren't ever pushed into scope, because
1022 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1023 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1024 return ActOnConstructorDeclarator(Constructor);
1025 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1026 return ActOnDestructorDeclarator(Destructor);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001027 else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1028 return ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001029
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001030 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1031 if (NewFD->isOverloadedOperator() &&
1032 CheckOverloadedOperatorDeclaration(NewFD))
1033 NewFD->setInvalidDecl();
1034
Steve Naroffffce4d52008-01-09 23:34:55 +00001035 // Merge the decl with the existing one if appropriate. Since C functions
1036 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001037 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001038 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001039 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001040
1041 // If C++, determine whether NewFD is an overload of PrevDecl or
1042 // a declaration that requires merging. If it's an overload,
1043 // there's no more work to do here; we'll just add the new
1044 // function to the scope.
1045 OverloadedFunctionDecl::function_iterator MatchedDecl;
1046 if (!getLangOptions().CPlusPlus ||
1047 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1048 Decl *OldDecl = PrevDecl;
1049
1050 // If PrevDecl was an overloaded function, extract the
1051 // FunctionDecl that matched.
1052 if (isa<OverloadedFunctionDecl>(PrevDecl))
1053 OldDecl = *MatchedDecl;
1054
1055 // NewFD and PrevDecl represent declarations that need to be
1056 // merged.
1057 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1058
1059 if (NewFD == 0) return 0;
1060 if (Redeclaration) {
1061 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1062
1063 if (OldDecl == PrevDecl) {
1064 // Remove the name binding for the previous
1065 // declaration. We'll add the binding back later, but then
1066 // it will refer to the new declaration (which will
1067 // contain more information).
1068 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1069 } else {
1070 // We need to update the OverloadedFunctionDecl with the
1071 // latest declaration of this function, so that name
1072 // lookup will always refer to the latest declaration of
1073 // this function.
1074 *MatchedDecl = NewFD;
1075
1076 // Add the redeclaration to the current scope, since we'll
1077 // be skipping PushOnScopeChains.
1078 S->AddDecl(NewFD);
1079
1080 return NewFD;
1081 }
1082 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001083 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001084 }
1085 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001086
1087 // In C++, check default arguments now that we have merged decls.
1088 if (getLangOptions().CPlusPlus)
1089 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001090 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001091 // Check that there are no default arguments (C++ only).
1092 if (getLangOptions().CPlusPlus)
1093 CheckExtraCXXDefaultArguments(D);
1094
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001095 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001096 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
1097 D.getIdentifier()->getName());
1098 InvalidDecl = true;
1099 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001100
1101 VarDecl *NewVD;
1102 VarDecl::StorageClass SC;
1103 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001104 default: assert(0 && "Unknown storage class!");
1105 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1106 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1107 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1108 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1109 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1110 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001111 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001112 if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001113 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1114 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001115 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001116 D.getIdentifierLoc(), II,
1117 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001118 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001119 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001120 if (S->getFnParent() == 0) {
1121 // C99 6.9p2: The storage-class specifiers auto and register shall not
1122 // appear in the declaration specifiers in an external declaration.
1123 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1124 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
1125 R.getAsString());
1126 InvalidDecl = true;
1127 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001128 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001129 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001130 II, R, SC, LastDeclarator,
1131 // FIXME: Move to DeclGroup...
1132 D.getDeclSpec().getSourceRange().getBegin());
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001133 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001134 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001135 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001136 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001137
Daniel Dunbara735ad82008-08-06 00:03:29 +00001138 // Handle GNU asm-label extension (encoded as an attribute).
1139 if (Expr *E = (Expr*) D.getAsmLabel()) {
1140 // The parser guarantees this is a string.
1141 StringLiteral *SE = cast<StringLiteral>(E);
1142 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1143 SE->getByteLength())));
1144 }
1145
Nate Begemanc8e89a82008-03-14 18:07:10 +00001146 // Emit an error if an address space was applied to decl with local storage.
1147 // This includes arrays of objects with address space qualifiers, but not
1148 // automatic variables that point to other address spaces.
1149 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001150 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1151 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1152 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001153 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001154 // Merge the decl with the existing one if appropriate. If the decl is
1155 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001156 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001157 NewVD = MergeVarDecl(NewVD, PrevDecl);
1158 if (NewVD == 0) return 0;
1159 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001160 New = NewVD;
1161 }
1162
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001163 // Set the lexical context. If the declarator has a C++ scope specifier, the
1164 // lexical context will be different from the semantic context.
1165 New->setLexicalDeclContext(CurContext);
1166
Reid Spencer5f016e22007-07-11 17:01:13 +00001167 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001168 if (II)
1169 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001170 // If any semantic error occurred, mark the decl as invalid.
1171 if (D.getInvalidType() || InvalidDecl)
1172 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001173
1174 return New;
1175}
1176
Steve Naroff6594a702008-10-27 11:34:16 +00001177void Sema::InitializerElementNotConstant(const Expr *Init) {
1178 Diag(Init->getExprLoc(),
1179 diag::err_init_element_not_constant, Init->getSourceRange());
1180}
1181
Eli Friedmanc594b322008-05-20 13:48:25 +00001182bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1183 switch (Init->getStmtClass()) {
1184 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001185 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001186 return true;
1187 case Expr::ParenExprClass: {
1188 const ParenExpr* PE = cast<ParenExpr>(Init);
1189 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1190 }
1191 case Expr::CompoundLiteralExprClass:
1192 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1193 case Expr::DeclRefExprClass: {
1194 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001195 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1196 if (VD->hasGlobalStorage())
1197 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001198 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001199 return true;
1200 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001201 if (isa<FunctionDecl>(D))
1202 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001203 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001204 return true;
1205 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001206 case Expr::MemberExprClass: {
1207 const MemberExpr *M = cast<MemberExpr>(Init);
1208 if (M->isArrow())
1209 return CheckAddressConstantExpression(M->getBase());
1210 return CheckAddressConstantExpressionLValue(M->getBase());
1211 }
1212 case Expr::ArraySubscriptExprClass: {
1213 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1214 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1215 return CheckAddressConstantExpression(ASE->getBase()) ||
1216 CheckArithmeticConstantExpression(ASE->getIdx());
1217 }
1218 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001219 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001220 return false;
1221 case Expr::UnaryOperatorClass: {
1222 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1223
1224 // C99 6.6p9
1225 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001226 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001227
Steve Naroff6594a702008-10-27 11:34:16 +00001228 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001229 return true;
1230 }
1231 }
1232}
1233
1234bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1235 switch (Init->getStmtClass()) {
1236 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001237 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001238 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001239 case Expr::ParenExprClass:
1240 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001241 case Expr::StringLiteralClass:
1242 case Expr::ObjCStringLiteralClass:
1243 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001244 case Expr::CallExprClass:
1245 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1246 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1247 Builtin::BI__builtin___CFStringMakeConstantString)
1248 return false;
1249
Steve Naroff6594a702008-10-27 11:34:16 +00001250 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001251 return true;
1252
Eli Friedmanc594b322008-05-20 13:48:25 +00001253 case Expr::UnaryOperatorClass: {
1254 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1255
1256 // C99 6.6p9
1257 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1258 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1259
1260 if (Exp->getOpcode() == UnaryOperator::Extension)
1261 return CheckAddressConstantExpression(Exp->getSubExpr());
1262
Steve Naroff6594a702008-10-27 11:34:16 +00001263 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001264 return true;
1265 }
1266 case Expr::BinaryOperatorClass: {
1267 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1268 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1269
1270 Expr *PExp = Exp->getLHS();
1271 Expr *IExp = Exp->getRHS();
1272 if (IExp->getType()->isPointerType())
1273 std::swap(PExp, IExp);
1274
1275 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1276 return CheckAddressConstantExpression(PExp) ||
1277 CheckArithmeticConstantExpression(IExp);
1278 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001279 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001280 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001281 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001282 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1283 // Check for implicit promotion
1284 if (SubExpr->getType()->isFunctionType() ||
1285 SubExpr->getType()->isArrayType())
1286 return CheckAddressConstantExpressionLValue(SubExpr);
1287 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001288
1289 // Check for pointer->pointer cast
1290 if (SubExpr->getType()->isPointerType())
1291 return CheckAddressConstantExpression(SubExpr);
1292
Eli Friedmanc3f07642008-08-25 20:46:57 +00001293 if (SubExpr->getType()->isIntegralType()) {
1294 // Check for the special-case of a pointer->int->pointer cast;
1295 // this isn't standard, but some code requires it. See
1296 // PR2720 for an example.
1297 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1298 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1299 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1300 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1301 if (IntWidth >= PointerWidth) {
1302 return CheckAddressConstantExpression(SubCast->getSubExpr());
1303 }
1304 }
1305 }
1306 }
1307 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001308 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001309 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001310
Steve Naroff6594a702008-10-27 11:34:16 +00001311 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001312 return true;
1313 }
1314 case Expr::ConditionalOperatorClass: {
1315 // FIXME: Should we pedwarn here?
1316 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1317 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001318 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001319 return true;
1320 }
1321 if (CheckArithmeticConstantExpression(Exp->getCond()))
1322 return true;
1323 if (Exp->getLHS() &&
1324 CheckAddressConstantExpression(Exp->getLHS()))
1325 return true;
1326 return CheckAddressConstantExpression(Exp->getRHS());
1327 }
1328 case Expr::AddrLabelExprClass:
1329 return false;
1330 }
1331}
1332
Eli Friedman4caf0552008-06-09 05:05:07 +00001333static const Expr* FindExpressionBaseAddress(const Expr* E);
1334
1335static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1336 switch (E->getStmtClass()) {
1337 default:
1338 return E;
1339 case Expr::ParenExprClass: {
1340 const ParenExpr* PE = cast<ParenExpr>(E);
1341 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1342 }
1343 case Expr::MemberExprClass: {
1344 const MemberExpr *M = cast<MemberExpr>(E);
1345 if (M->isArrow())
1346 return FindExpressionBaseAddress(M->getBase());
1347 return FindExpressionBaseAddressLValue(M->getBase());
1348 }
1349 case Expr::ArraySubscriptExprClass: {
1350 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1351 return FindExpressionBaseAddress(ASE->getBase());
1352 }
1353 case Expr::UnaryOperatorClass: {
1354 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1355
1356 if (Exp->getOpcode() == UnaryOperator::Deref)
1357 return FindExpressionBaseAddress(Exp->getSubExpr());
1358
1359 return E;
1360 }
1361 }
1362}
1363
1364static const Expr* FindExpressionBaseAddress(const Expr* E) {
1365 switch (E->getStmtClass()) {
1366 default:
1367 return E;
1368 case Expr::ParenExprClass: {
1369 const ParenExpr* PE = cast<ParenExpr>(E);
1370 return FindExpressionBaseAddress(PE->getSubExpr());
1371 }
1372 case Expr::UnaryOperatorClass: {
1373 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1374
1375 // C99 6.6p9
1376 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1377 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1378
1379 if (Exp->getOpcode() == UnaryOperator::Extension)
1380 return FindExpressionBaseAddress(Exp->getSubExpr());
1381
1382 return E;
1383 }
1384 case Expr::BinaryOperatorClass: {
1385 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1386
1387 Expr *PExp = Exp->getLHS();
1388 Expr *IExp = Exp->getRHS();
1389 if (IExp->getType()->isPointerType())
1390 std::swap(PExp, IExp);
1391
1392 return FindExpressionBaseAddress(PExp);
1393 }
1394 case Expr::ImplicitCastExprClass: {
1395 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1396
1397 // Check for implicit promotion
1398 if (SubExpr->getType()->isFunctionType() ||
1399 SubExpr->getType()->isArrayType())
1400 return FindExpressionBaseAddressLValue(SubExpr);
1401
1402 // Check for pointer->pointer cast
1403 if (SubExpr->getType()->isPointerType())
1404 return FindExpressionBaseAddress(SubExpr);
1405
1406 // We assume that we have an arithmetic expression here;
1407 // if we don't, we'll figure it out later
1408 return 0;
1409 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001410 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001411 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1412
1413 // Check for pointer->pointer cast
1414 if (SubExpr->getType()->isPointerType())
1415 return FindExpressionBaseAddress(SubExpr);
1416
1417 // We assume that we have an arithmetic expression here;
1418 // if we don't, we'll figure it out later
1419 return 0;
1420 }
1421 }
1422}
1423
Eli Friedmanc594b322008-05-20 13:48:25 +00001424bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1425 switch (Init->getStmtClass()) {
1426 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001427 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001428 return true;
1429 case Expr::ParenExprClass: {
1430 const ParenExpr* PE = cast<ParenExpr>(Init);
1431 return CheckArithmeticConstantExpression(PE->getSubExpr());
1432 }
1433 case Expr::FloatingLiteralClass:
1434 case Expr::IntegerLiteralClass:
1435 case Expr::CharacterLiteralClass:
1436 case Expr::ImaginaryLiteralClass:
1437 case Expr::TypesCompatibleExprClass:
1438 case Expr::CXXBoolLiteralExprClass:
1439 return false;
1440 case Expr::CallExprClass: {
1441 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001442
1443 // Allow any constant foldable calls to builtins.
1444 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001445 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001446
Steve Naroff6594a702008-10-27 11:34:16 +00001447 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001448 return true;
1449 }
1450 case Expr::DeclRefExprClass: {
1451 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1452 if (isa<EnumConstantDecl>(D))
1453 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001454 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001455 return true;
1456 }
1457 case Expr::CompoundLiteralExprClass:
1458 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1459 // but vectors are allowed to be magic.
1460 if (Init->getType()->isVectorType())
1461 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001462 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001463 return true;
1464 case Expr::UnaryOperatorClass: {
1465 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1466
1467 switch (Exp->getOpcode()) {
1468 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1469 // See C99 6.6p3.
1470 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001471 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001472 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001473 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00001474 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1475 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001476 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001477 return true;
1478 case UnaryOperator::Extension:
1479 case UnaryOperator::LNot:
1480 case UnaryOperator::Plus:
1481 case UnaryOperator::Minus:
1482 case UnaryOperator::Not:
1483 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1484 }
1485 }
Sebastian Redl05189992008-11-11 17:56:53 +00001486 case Expr::SizeOfAlignOfExprClass: {
1487 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001488 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00001489 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00001490 return false;
1491 // alignof always evaluates to a constant.
1492 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00001493 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001494 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001495 return true;
1496 }
1497 return false;
1498 }
1499 case Expr::BinaryOperatorClass: {
1500 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1501
1502 if (Exp->getLHS()->getType()->isArithmeticType() &&
1503 Exp->getRHS()->getType()->isArithmeticType()) {
1504 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1505 CheckArithmeticConstantExpression(Exp->getRHS());
1506 }
1507
Eli Friedman4caf0552008-06-09 05:05:07 +00001508 if (Exp->getLHS()->getType()->isPointerType() &&
1509 Exp->getRHS()->getType()->isPointerType()) {
1510 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1511 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1512
1513 // Only allow a null (constant integer) base; we could
1514 // allow some additional cases if necessary, but this
1515 // is sufficient to cover offsetof-like constructs.
1516 if (!LHSBase && !RHSBase) {
1517 return CheckAddressConstantExpression(Exp->getLHS()) ||
1518 CheckAddressConstantExpression(Exp->getRHS());
1519 }
1520 }
1521
Steve Naroff6594a702008-10-27 11:34:16 +00001522 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001523 return true;
1524 }
1525 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001526 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001527 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001528 if (SubExpr->getType()->isArithmeticType())
1529 return CheckArithmeticConstantExpression(SubExpr);
1530
Eli Friedmanb529d832008-09-02 09:37:00 +00001531 if (SubExpr->getType()->isPointerType()) {
1532 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1533 // If the pointer has a null base, this is an offsetof-like construct
1534 if (!Base)
1535 return CheckAddressConstantExpression(SubExpr);
1536 }
1537
Steve Naroff6594a702008-10-27 11:34:16 +00001538 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001539 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001540 }
1541 case Expr::ConditionalOperatorClass: {
1542 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001543
1544 // If GNU extensions are disabled, we require all operands to be arithmetic
1545 // constant expressions.
1546 if (getLangOptions().NoExtensions) {
1547 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1548 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1549 CheckArithmeticConstantExpression(Exp->getRHS());
1550 }
1551
1552 // Otherwise, we have to emulate some of the behavior of fold here.
1553 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1554 // because it can constant fold things away. To retain compatibility with
1555 // GCC code, we see if we can fold the condition to a constant (which we
1556 // should always be able to do in theory). If so, we only require the
1557 // specified arm of the conditional to be a constant. This is a horrible
1558 // hack, but is require by real world code that uses __builtin_constant_p.
1559 APValue Val;
1560 if (!Exp->getCond()->tryEvaluate(Val, Context)) {
1561 // If the tryEvaluate couldn't fold it, CheckArithmeticConstantExpression
1562 // won't be able to either. Use it to emit the diagnostic though.
1563 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
1564 assert(Res && "tryEvaluate couldn't evaluate this constant?");
1565 return Res;
1566 }
1567
1568 // Verify that the side following the condition is also a constant.
1569 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1570 if (Val.getInt() == 0)
1571 std::swap(TrueSide, FalseSide);
1572
1573 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001574 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001575
1576 // Okay, the evaluated side evaluates to a constant, so we accept this.
1577 // Check to see if the other side is obviously not a constant. If so,
1578 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001579 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001580 Diag(Init->getExprLoc(),
1581 diag::ext_typecheck_expression_not_constant_but_accepted,
1582 FalseSide->getSourceRange());
1583 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001584 }
1585 }
1586}
1587
1588bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes9a979c32008-07-07 16:46:50 +00001589 Init = Init->IgnoreParens();
1590
Eli Friedmanc594b322008-05-20 13:48:25 +00001591 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1592 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1593 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1594
Nuno Lopes9a979c32008-07-07 16:46:50 +00001595 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1596 return CheckForConstantInitializer(e->getInitializer(), DclT);
1597
Eli Friedmanc594b322008-05-20 13:48:25 +00001598 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1599 unsigned numInits = Exp->getNumInits();
1600 for (unsigned i = 0; i < numInits; i++) {
1601 // FIXME: Need to get the type of the declaration for C++,
1602 // because it could be a reference?
1603 if (CheckForConstantInitializer(Exp->getInit(i),
1604 Exp->getInit(i)->getType()))
1605 return true;
1606 }
1607 return false;
1608 }
1609
1610 if (Init->isNullPointerConstant(Context))
1611 return false;
1612 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001613 QualType InitTy = Context.getCanonicalType(Init->getType())
1614 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001615 if (InitTy == Context.BoolTy) {
1616 // Special handling for pointers implicitly cast to bool;
1617 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1618 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1619 Expr* SubE = ICE->getSubExpr();
1620 if (SubE->getType()->isPointerType() ||
1621 SubE->getType()->isArrayType() ||
1622 SubE->getType()->isFunctionType()) {
1623 return CheckAddressConstantExpression(Init);
1624 }
1625 }
1626 } else if (InitTy->isIntegralType()) {
1627 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001628 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001629 SubE = CE->getSubExpr();
1630 // Special check for pointer cast to int; we allow as an extension
1631 // an address constant cast to an integer if the integer
1632 // is of an appropriate width (this sort of code is apparently used
1633 // in some places).
1634 // FIXME: Add pedwarn?
1635 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1636 if (SubE && (SubE->getType()->isPointerType() ||
1637 SubE->getType()->isArrayType() ||
1638 SubE->getType()->isFunctionType())) {
1639 unsigned IntWidth = Context.getTypeSize(Init->getType());
1640 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1641 if (IntWidth >= PointerWidth)
1642 return CheckAddressConstantExpression(Init);
1643 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001644 }
1645
1646 return CheckArithmeticConstantExpression(Init);
1647 }
1648
1649 if (Init->getType()->isPointerType())
1650 return CheckAddressConstantExpression(Init);
1651
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001652 // An array type at the top level that isn't an init-list must
1653 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001654 if (Init->getType()->isArrayType())
1655 return false;
1656
Nuno Lopes73419bf2008-09-01 18:42:41 +00001657 if (Init->getType()->isFunctionType())
1658 return false;
1659
Steve Naroff8af6a452008-10-02 17:12:56 +00001660 // Allow block exprs at top level.
1661 if (Init->getType()->isBlockPointerType())
1662 return false;
1663
Steve Naroff6594a702008-10-27 11:34:16 +00001664 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001665 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001666}
1667
Steve Naroffbb204692007-09-12 14:07:44 +00001668void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001669 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001670 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001671 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001672
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001673 // If there is no declaration, there was an error parsing it. Just ignore
1674 // the initializer.
1675 if (RealDecl == 0) {
1676 delete Init;
1677 return;
1678 }
Steve Naroffbb204692007-09-12 14:07:44 +00001679
Steve Naroff410e3e22007-09-12 20:13:48 +00001680 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1681 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001682 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1683 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001684 RealDecl->setInvalidDecl();
1685 return;
1686 }
Steve Naroffbb204692007-09-12 14:07:44 +00001687 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001688 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001689 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001690 if (VDecl->isBlockVarDecl()) {
1691 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001692 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001693 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001694 VDecl->setInvalidDecl();
1695 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001696 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1697 VDecl->getName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001698 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001699
1700 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1701 if (!getLangOptions().CPlusPlus) {
1702 if (SC == VarDecl::Static) // C99 6.7.8p4.
1703 CheckForConstantInitializer(Init, DclT);
1704 }
Steve Naroffbb204692007-09-12 14:07:44 +00001705 }
Steve Naroff248a7532008-04-15 22:42:06 +00001706 } else if (VDecl->isFileVarDecl()) {
1707 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001708 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001709 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001710 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1711 VDecl->getName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001712 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001713
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001714 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1715 if (!getLangOptions().CPlusPlus) {
1716 // C99 6.7.8p4. All file scoped initializers need to be constant.
1717 CheckForConstantInitializer(Init, DclT);
1718 }
Steve Naroffbb204692007-09-12 14:07:44 +00001719 }
1720 // If the type changed, it means we had an incomplete type that was
1721 // completed by the initializer. For example:
1722 // int ary[] = { 1, 3, 5 };
1723 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001724 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001725 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001726 Init->setType(DclT);
1727 }
Steve Naroffbb204692007-09-12 14:07:44 +00001728
1729 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001730 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001731 return;
1732}
1733
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001734void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1735 Decl *RealDecl = static_cast<Decl *>(dcl);
1736
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00001737 // If there is no declaration, there was an error parsing it. Just ignore it.
1738 if (RealDecl == 0)
1739 return;
1740
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001741 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1742 QualType Type = Var->getType();
1743 // C++ [dcl.init.ref]p3:
1744 // The initializer can be omitted for a reference only in a
1745 // parameter declaration (8.3.5), in the declaration of a
1746 // function return type, in the declaration of a class member
1747 // within its class declaration (9.2), and where the extern
1748 // specifier is explicitly used.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001749 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001750 Diag(Var->getLocation(),
1751 diag::err_reference_var_requires_init,
1752 Var->getName(),
1753 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor18fe5682008-11-03 20:45:27 +00001754 Var->setInvalidDecl();
1755 return;
1756 }
1757
1758 // C++ [dcl.init]p9:
1759 //
1760 // If no initializer is specified for an object, and the object
1761 // is of (possibly cv-qualified) non-POD class type (or array
1762 // thereof), the object shall be default-initialized; if the
1763 // object is of const-qualified type, the underlying class type
1764 // shall have a user-declared default constructor.
1765 if (getLangOptions().CPlusPlus) {
1766 QualType InitType = Type;
1767 if (const ArrayType *Array = Context.getAsArrayType(Type))
1768 InitType = Array->getElementType();
1769 if (InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001770 const CXXConstructorDecl *Constructor
1771 = PerformInitializationByConstructor(InitType, 0, 0,
1772 Var->getLocation(),
1773 SourceRange(Var->getLocation(),
1774 Var->getLocation()),
1775 Var->getName(),
1776 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001777 if (!Constructor)
1778 Var->setInvalidDecl();
1779 }
1780 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001781
Douglas Gregor818ce482008-10-29 13:50:18 +00001782#if 0
1783 // FIXME: Temporarily disabled because we are not properly parsing
1784 // linkage specifications on declarations, e.g.,
1785 //
1786 // extern "C" const CGPoint CGPointerZero;
1787 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001788 // C++ [dcl.init]p9:
1789 //
1790 // If no initializer is specified for an object, and the
1791 // object is of (possibly cv-qualified) non-POD class type (or
1792 // array thereof), the object shall be default-initialized; if
1793 // the object is of const-qualified type, the underlying class
1794 // type shall have a user-declared default
1795 // constructor. Otherwise, if no initializer is specified for
1796 // an object, the object and its subobjects, if any, have an
1797 // indeterminate initial value; if the object or any of its
1798 // subobjects are of const-qualified type, the program is
1799 // ill-formed.
1800 //
1801 // This isn't technically an error in C, so we don't diagnose it.
1802 //
1803 // FIXME: Actually perform the POD/user-defined default
1804 // constructor check.
1805 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00001806 Context.getCanonicalType(Type).isConstQualified() &&
1807 Var->getStorageClass() != VarDecl::Extern)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001808 Diag(Var->getLocation(),
1809 diag::err_const_var_requires_init,
1810 Var->getName(),
1811 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor818ce482008-10-29 13:50:18 +00001812#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001813 }
1814}
1815
Reid Spencer5f016e22007-07-11 17:01:13 +00001816/// The declarators are chained together backwards, reverse the list.
1817Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1818 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001819 Decl *GroupDecl = static_cast<Decl*>(group);
1820 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001821 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001822
1823 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1824 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001825 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001826 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001827 else { // reverse the list.
1828 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001829 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001830 Group->setNextDeclarator(NewGroup);
1831 NewGroup = Group;
1832 Group = Next;
1833 }
1834 }
1835 // Perform semantic analysis that depends on having fully processed both
1836 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001837 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001838 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1839 if (!IDecl)
1840 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001841 QualType T = IDecl->getType();
1842
1843 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1844 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001845 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1846 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001847 if (T->isVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001848 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1849 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001850 }
1851 }
1852 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1853 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001854 if (IDecl->isBlockVarDecl() &&
1855 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001856 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001857 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1858 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001859 IDecl->setInvalidDecl();
1860 }
1861 }
1862 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1863 // object that has file scope without an initializer, and without a
1864 // storage-class specifier or with the storage-class specifier "static",
1865 // constitutes a tentative definition. Note: A tentative definition with
1866 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001867 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001868 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001869 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1870 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001871 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001872 // C99 6.9.2p3: If the declaration of an identifier for an object is
1873 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1874 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001875 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1876 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001877 IDecl->setInvalidDecl();
1878 }
1879 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001880 if (IDecl->isFileVarDecl())
1881 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001882 }
1883 return NewGroup;
1884}
Steve Naroffe1223f72007-08-28 03:03:08 +00001885
Chris Lattner04421082008-04-08 04:40:51 +00001886/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1887/// to introduce parameters into function prototype scope.
1888Sema::DeclTy *
1889Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001890 // FIXME: disallow CXXScopeSpec for param declarators.
Chris Lattner985abd92008-06-26 06:49:43 +00001891 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001892
1893 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001894 VarDecl::StorageClass StorageClass = VarDecl::None;
1895 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1896 StorageClass = VarDecl::Register;
1897 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00001898 Diag(DS.getStorageClassSpecLoc(),
1899 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001900 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001901 }
1902 if (DS.isThreadSpecified()) {
1903 Diag(DS.getThreadSpecLoc(),
1904 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001905 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001906 }
1907
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001908 // Check that there are no default arguments inside the type of this
1909 // parameter (C++ only).
1910 if (getLangOptions().CPlusPlus)
1911 CheckExtraCXXDefaultArguments(D);
1912
Chris Lattner04421082008-04-08 04:40:51 +00001913 // In this context, we *do not* check D.getInvalidType(). If the declarator
1914 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1915 // though it will not reflect the user specified type.
1916 QualType parmDeclType = GetTypeForDeclarator(D, S);
1917
1918 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1919
Reid Spencer5f016e22007-07-11 17:01:13 +00001920 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1921 // Can this happen for params? We already checked that they don't conflict
1922 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001923 IdentifierInfo *II = D.getIdentifier();
1924 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1925 if (S->isDeclScope(PrevDecl)) {
1926 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1927 dyn_cast<NamedDecl>(PrevDecl)->getName());
1928
1929 // Recover by removing the name
1930 II = 0;
1931 D.SetIdentifier(0, D.getIdentifierLoc());
1932 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001933 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001934
1935 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1936 // Doing the promotion here has a win and a loss. The win is the type for
1937 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1938 // code generator). The loss is the orginal type isn't preserved. For example:
1939 //
1940 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1941 // int blockvardecl[5];
1942 // sizeof(parmvardecl); // size == 4
1943 // sizeof(blockvardecl); // size == 20
1944 // }
1945 //
1946 // For expressions, all implicit conversions are captured using the
1947 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1948 //
1949 // FIXME: If a source translation tool needs to see the original type, then
1950 // we need to consider storing both types (in ParmVarDecl)...
1951 //
Chris Lattnere6327742008-04-02 05:18:44 +00001952 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001953 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001954 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001955 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001956 parmDeclType = Context.getPointerType(parmDeclType);
1957
Chris Lattner04421082008-04-08 04:40:51 +00001958 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1959 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001960 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00001961 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001962
Chris Lattner04421082008-04-08 04:40:51 +00001963 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001964 New->setInvalidDecl();
1965
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001966 if (II)
1967 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001968
Chris Lattner3ff30c82008-06-29 00:02:00 +00001969 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001970 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001971
Reid Spencer5f016e22007-07-11 17:01:13 +00001972}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001973
Chris Lattnerb652cea2007-10-09 17:14:05 +00001974Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001975 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00001976 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1977 "Not a function declarator!");
1978 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001979
Reid Spencer5f016e22007-07-11 17:01:13 +00001980 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1981 // for a K&R function.
1982 if (!FTI.hasPrototype) {
1983 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001984 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001985 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1986 FTI.ArgInfo[i].Ident->getName());
1987 // Implicitly declare the argument as type 'int' for lack of a better
1988 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001989 DeclSpec DS;
1990 const char* PrevSpec; // unused
1991 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1992 PrevSpec);
1993 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1994 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1995 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001996 }
1997 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001998 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001999 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002000 }
2001
2002 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002003
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002004 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00002005 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002006}
2007
2008Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2009 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002010 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002011
2012 // See if this is a redefinition.
2013 const FunctionDecl *Definition;
2014 if (FD->getBody(Definition)) {
2015 Diag(FD->getLocation(), diag::err_redefinition,
2016 FD->getName());
2017 Diag(Definition->getLocation(), diag::err_previous_definition);
2018 }
2019
Chris Lattnerb048c982008-04-06 04:47:34 +00002020 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00002021
2022 // Check the validity of our function parameters
2023 CheckParmsForFunctionDef(FD);
2024
2025 // Introduce our parameters into the function scope
2026 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2027 ParmVarDecl *Param = FD->getParamDecl(p);
2028 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002029 if (Param->getIdentifier())
2030 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002031 }
Chris Lattner04421082008-04-08 04:40:51 +00002032
Reid Spencer5f016e22007-07-11 17:01:13 +00002033 return FD;
2034}
2035
Steve Naroffd6d054d2007-11-11 23:20:51 +00002036Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
2037 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00002038 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002039 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002040 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002041 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002042 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002043 } else
2044 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002045 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002046 // Verify and clean out per-function state.
2047
2048 // Check goto/label use.
2049 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2050 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2051 // Verify that we have no forward references left. If so, there was a goto
2052 // or address of a label taken, but no definition of it. Label fwd
2053 // definitions are indicated with a null substmt.
2054 if (I->second->getSubStmt() == 0) {
2055 LabelStmt *L = I->second;
2056 // Emit error.
2057 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
2058
2059 // At this point, we have gotos that use the bogus label. Stitch it into
2060 // the function body so that they aren't leaked and that the AST is well
2061 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002062 if (Body) {
2063 L->setSubStmt(new NullStmt(L->getIdentLoc()));
2064 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2065 } else {
2066 // The whole function wasn't parsed correctly, just delete this.
2067 delete L;
2068 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002069 }
2070 }
2071 LabelMap.clear();
2072
Steve Naroffd6d054d2007-11-11 23:20:51 +00002073 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002074}
2075
Reid Spencer5f016e22007-07-11 17:01:13 +00002076/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2077/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002078ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2079 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002080 // Extension in C99. Legal in C90, but warn about it.
2081 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00002082 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00002083 else
Reid Spencer5f016e22007-07-11 17:01:13 +00002084 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
2085
2086 // FIXME: handle stuff like:
2087 // void foo() { extern float X(); }
2088 // void bar() { X(); } <-- implicit decl for X in another scope.
2089
2090 // Set a Declarator for the implicit definition: int foo();
2091 const char *Dummy;
2092 DeclSpec DS;
2093 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2094 Error = Error; // Silence warning.
2095 assert(!Error && "Error setting up implicit decl!");
2096 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002097 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 D.SetIdentifier(&II, Loc);
2099
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002100 // Insert this function into translation-unit scope.
2101
2102 DeclContext *PrevDC = CurContext;
2103 CurContext = Context.getTranslationUnitDecl();
2104
Steve Naroffe2ef8152008-04-04 14:32:09 +00002105 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002106 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002107 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002108
2109 CurContext = PrevDC;
2110
Steve Naroffe2ef8152008-04-04 14:32:09 +00002111 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002112}
2113
2114
Chris Lattner41af0932007-11-14 06:34:38 +00002115TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002116 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002117 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002118 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002119
2120 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002121 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2122 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002123 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002124 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002125 if (D.getInvalidType())
2126 NewTD->setInvalidDecl();
2127 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002128}
2129
Steve Naroff08d92e42007-09-15 18:49:24 +00002130/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002131/// former case, Name will be non-null. In the later case, Name will be null.
2132/// TagType indicates what kind of tag this is. TK indicates whether this is a
2133/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002134Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002135 SourceLocation KWLoc, const CXXScopeSpec &SS,
2136 IdentifierInfo *Name, SourceLocation NameLoc,
2137 AttributeList *Attr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002138 // If this is a use of an existing tag, it must have a name.
2139 assert((Name != 0 || TK == TK_Definition) &&
2140 "Nameless record must be a definition!");
2141
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002142 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002143 switch (TagType) {
2144 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002145 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2146 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2147 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2148 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002149 }
2150
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002151 // Two code paths: a new one for structs/unions/classes where we create
2152 // separate decls for forward declarations, and an old (eventually to
2153 // be removed) code path for enums.
2154 if (Kind != TagDecl::TK_enum)
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002155 return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002156
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002157 DeclContext *DC = CurContext;
2158 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002159
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002160 if (Name && SS.isNotEmpty()) {
2161 // We have a nested-name tag ('struct foo::bar').
2162
2163 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002164 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002165 Name = 0;
2166 goto CreateNewDecl;
2167 }
2168
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002169 DC = static_cast<DeclContext*>(SS.getScopeRep());
2170 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002171 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2172
2173 // A tag 'foo::bar' must already exist.
2174 if (PrevDecl == 0) {
2175 Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(),
2176 SS.getRange());
2177 Name = 0;
2178 goto CreateNewDecl;
2179 }
2180 } else {
2181 // If this is a named struct, check to see if there was a previous forward
2182 // declaration or definition.
2183 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2184 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2185 }
2186
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002187 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002188 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2189 "unexpected Decl type");
2190 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002191 // If this is a use of a previous tag, or if the tag is already declared
2192 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002193 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002194 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002195 // Make sure that this wasn't declared as an enum and now used as a
2196 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002197 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002198 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2199 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002200 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002201 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002202 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002203 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00002204 // If this is a use or a forward declaration, we're good.
2205 if (TK != TK_Definition)
2206 return PrevDecl;
2207
2208 // Diagnose attempts to redefine a tag.
2209 if (PrevTagDecl->isDefinition()) {
2210 Diag(NameLoc, diag::err_redefinition, Name->getName());
2211 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2212 // If this is a redefinition, recover by making this struct be
2213 // anonymous, which will make any later references get the previous
2214 // definition.
2215 Name = 0;
2216 } else {
2217 // Okay, this is definition of a previously declared or referenced
2218 // tag. Move the location of the decl to be the definition site.
2219 PrevDecl->setLocation(NameLoc);
2220 return PrevDecl;
2221 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002222 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002223 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002224 // If we get here, this is a definition of a new struct type in a nested
2225 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2226 // type.
2227 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002228 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002229 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002230 // The tag name clashes with a namespace name, issue an error and
2231 // recover by making this tag be anonymous.
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002232 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2233 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2234 Name = 0;
2235 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002236 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002237 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002238
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002239 CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002240
2241 // If there is an identifier, use the location of the identifier as the
2242 // location of the decl, otherwise use the location of the struct/union
2243 // keyword.
2244 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2245
2246 // Otherwise, if this is the first time we've seen this tag, create the decl.
2247 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002248 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002249 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2250 // enum X { A, B, C } D; D should chain to X.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002251 New = EnumDecl::Create(Context, DC, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002252 // If this is an undefined enum, warn.
2253 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002254 } else {
2255 // struct/union/class
2256
Reid Spencer5f016e22007-07-11 17:01:13 +00002257 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2258 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002259 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002260 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002261 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002262 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002263 New = RecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002264 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002265
2266 // If this has an identifier, add it to the scope stack.
2267 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002268 // The scope passed in may not be a decl scope. Zip up the scope tree until
2269 // we find one that is.
2270 while ((S->getFlags() & Scope::DeclScope) == 0)
2271 S = S->getParent();
2272
2273 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002274 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002275 }
Chris Lattnere1e79852008-02-06 00:51:33 +00002276
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00002277 if (Attr)
2278 ProcessDeclAttributeList(New, Attr);
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002279
2280 // Set the lexical context. If the tag has a C++ scope specifier, the
2281 // lexical context will be different from the semantic context.
2282 New->setLexicalDeclContext(CurContext);
2283
Reid Spencer5f016e22007-07-11 17:01:13 +00002284 return New;
2285}
2286
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002287/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2288/// the logic for enums, we create separate decls for forward declarations.
2289/// This is called by ActOnTag, but eventually will replace its logic.
2290Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002291 SourceLocation KWLoc, const CXXScopeSpec &SS,
2292 IdentifierInfo *Name, SourceLocation NameLoc,
2293 AttributeList *Attr) {
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002294 DeclContext *DC = CurContext;
2295 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002296
2297 if (Name && SS.isNotEmpty()) {
2298 // We have a nested-name tag ('struct foo::bar').
2299
2300 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002301 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002302 Name = 0;
2303 goto CreateNewDecl;
2304 }
2305
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002306 DC = static_cast<DeclContext*>(SS.getScopeRep());
2307 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002308 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2309
2310 // A tag 'foo::bar' must already exist.
2311 if (PrevDecl == 0) {
2312 Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(),
2313 SS.getRange());
2314 Name = 0;
2315 goto CreateNewDecl;
2316 }
2317 } else {
2318 // If this is a named struct, check to see if there was a previous forward
2319 // declaration or definition.
2320 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2321 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2322 }
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002323
2324 if (PrevDecl) {
2325 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2326 "unexpected Decl type");
2327
2328 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2329 // If this is a use of a previous tag, or if the tag is already declared
2330 // in the same scope (so that the definition/declaration completes or
2331 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002332 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002333 // Make sure that this wasn't declared as an enum and now used as a
2334 // struct or something similar.
2335 if (PrevTagDecl->getTagKind() != Kind) {
2336 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2337 Diag(PrevDecl->getLocation(), diag::err_previous_use);
2338 // Recover by making this an anonymous redefinition.
2339 Name = 0;
2340 PrevDecl = 0;
2341 } else {
2342 // If this is a use, return the original decl.
2343
2344 // FIXME: In the future, return a variant or some other clue
2345 // for the consumer of this Decl to know it doesn't own it.
2346 // For our current ASTs this shouldn't be a problem, but will
2347 // need to be changed with DeclGroups.
2348 if (TK == TK_Reference)
2349 return PrevDecl;
2350
2351 // The new decl is a definition?
2352 if (TK == TK_Definition) {
2353 // Diagnose attempts to redefine a tag.
2354 if (RecordDecl* DefRecord =
2355 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
2356 Diag(NameLoc, diag::err_redefinition, Name->getName());
2357 Diag(DefRecord->getLocation(), diag::err_previous_definition);
2358 // If this is a redefinition, recover by making this struct be
2359 // anonymous, which will make any later references get the previous
2360 // definition.
2361 Name = 0;
2362 PrevDecl = 0;
2363 }
2364 // Okay, this is definition of a previously declared or referenced
2365 // tag. We're going to create a new Decl.
2366 }
2367 }
2368 // If we get here we have (another) forward declaration. Just create
2369 // a new decl.
2370 }
2371 else {
2372 // If we get here, this is a definition of a new struct type in a nested
2373 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2374 // new decl/type. We set PrevDecl to NULL so that the Records
2375 // have distinct types.
2376 PrevDecl = 0;
2377 }
2378 } else {
2379 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002380 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002381 // The tag name clashes with a namespace name, issue an error and
2382 // recover by making this tag be anonymous.
2383 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2384 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2385 Name = 0;
2386 }
2387 }
2388 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002389
2390 CreateNewDecl:
2391
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002392 // If there is an identifier, use the location of the identifier as the
2393 // location of the decl, otherwise use the location of the struct/union
2394 // keyword.
2395 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2396
2397 // Otherwise, if this is the first time we've seen this tag, create the decl.
2398 TagDecl *New;
2399
2400 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2401 // struct X { int A; } D; D should chain to X.
2402 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002403 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002404 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002405 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2406 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002407 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002408 dyn_cast_or_null<RecordDecl>(PrevDecl));
2409
2410 // If this has an identifier, add it to the scope stack.
2411 if ((TK == TK_Definition || !PrevDecl) && Name) {
2412 // The scope passed in may not be a decl scope. Zip up the scope tree until
2413 // we find one that is.
2414 while ((S->getFlags() & Scope::DeclScope) == 0)
2415 S = S->getParent();
2416
2417 // Add it to the decl chain.
2418 PushOnScopeChains(New, S);
2419 }
Daniel Dunbar3b0db902008-10-16 02:34:03 +00002420
2421 // Handle #pragma pack: if the #pragma pack stack has non-default
2422 // alignment, make up a packed attribute for this decl. These
2423 // attributes are checked when the ASTContext lays out the
2424 // structure.
2425 //
2426 // It is important for implementing the correct semantics that this
2427 // happen here (in act on tag decl). The #pragma pack stack is
2428 // maintained as a result of parser callbacks which can occur at
2429 // many points during the parsing of a struct declaration (because
2430 // the #pragma tokens are effectively skipped over during the
2431 // parsing of the struct).
2432 if (unsigned Alignment = PackContext.getAlignment())
2433 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002434
2435 if (Attr)
2436 ProcessDeclAttributeList(New, Attr);
2437
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002438 // Set the lexical context. If the tag has a C++ scope specifier, the
2439 // lexical context will be different from the semantic context.
2440 New->setLexicalDeclContext(CurContext);
2441
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002442 return New;
2443}
2444
2445
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002446/// Collect the instance variables declared in an Objective-C object. Used in
2447/// the creation of structures from objects using the @defs directive.
Ted Kremenek01e67792008-08-20 03:26:33 +00002448static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002449 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002450 if (Class->getSuperClass())
Ted Kremenek01e67792008-08-20 03:26:33 +00002451 CollectIvars(Class->getSuperClass(), Ctx, ivars);
2452
2453 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremeneka89d1972008-09-03 18:03:35 +00002454 for (ObjCInterfaceDecl::ivar_iterator
2455 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2456
Ted Kremenek01e67792008-08-20 03:26:33 +00002457 ObjCIvarDecl* ID = *I;
2458 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2459 ID->getIdentifier(),
2460 ID->getType(),
2461 ID->getBitWidth()));
2462 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002463}
2464
2465/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2466/// instance variables of ClassName into Decls.
2467void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2468 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002469 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002470 // Check that ClassName is a valid class
2471 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2472 if (!Class) {
2473 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
2474 return;
2475 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002476 // Collect the instance variables
Ted Kremenek01e67792008-08-20 03:26:33 +00002477 CollectIvars(Class, Context, Decls);
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002478}
2479
Eli Friedman1b76ada2008-06-03 21:01:11 +00002480QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
2481 // This method tries to turn a variable array into a constant
2482 // array even when the size isn't an ICE. This is necessary
2483 // for compatibility with code that depends on gcc's buggy
2484 // constant expression folding, like struct {char x[(int)(char*)2];}
2485 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc44eec62008-07-03 04:20:39 +00002486 APValue Result;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002487 if (VLATy->getSizeExpr() &&
Chris Lattnercf0f51d2008-07-11 19:19:21 +00002488 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
2489 llvm::APSInt &Res = Result.getInt();
2490 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2491 return Context.getConstantArrayType(VLATy->getElementType(),
2492 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002493 }
2494 }
2495 return QualType();
2496}
2497
Steve Naroff08d92e42007-09-15 18:49:24 +00002498/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002499/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002500Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00002501 SourceLocation DeclStart,
2502 Declarator &D, ExprTy *BitfieldWidth) {
2503 IdentifierInfo *II = D.getIdentifier();
2504 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002505 SourceLocation Loc = DeclStart;
2506 if (II) Loc = D.getIdentifierLoc();
2507
2508 // FIXME: Unnamed fields can be handled in various different ways, for
2509 // example, unnamed unions inject all members into the struct namespace!
Ted Kremeneka89d1972008-09-03 18:03:35 +00002510
Reid Spencer5f016e22007-07-11 17:01:13 +00002511 if (BitWidth) {
2512 // TODO: Validate.
2513 //printf("WARNING: BITFIELDS IGNORED!\n");
2514
2515 // 6.7.2.1p3
2516 // 6.7.2.1p4
2517
2518 } else {
2519 // Not a bitfield.
2520
2521 // validate II.
2522
2523 }
2524
2525 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002526 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2527 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00002528
Reid Spencer5f016e22007-07-11 17:01:13 +00002529 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2530 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002531 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002532 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
2533 if (!FixedTy.isNull()) {
2534 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
2535 T = FixedTy;
2536 } else {
2537 // FIXME: This diagnostic needs work
2538 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2539 InvalidDecl = true;
2540 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002541 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002542 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002543 FieldDecl *NewFD;
2544
2545 if (getLangOptions().CPlusPlus) {
2546 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2547 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2548 Loc, II, T, BitWidth);
2549 if (II)
2550 PushOnScopeChains(NewFD, S);
2551 }
2552 else
2553 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00002554
Chris Lattner3ff30c82008-06-29 00:02:00 +00002555 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002556
Steve Naroff5912a352007-08-28 20:14:24 +00002557 if (D.getInvalidType() || InvalidDecl)
2558 NewFD->setInvalidDecl();
2559 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002560}
2561
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002562/// TranslateIvarVisibility - Translate visibility from a token ID to an
2563/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002564static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002565TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002566 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002567 default: assert(0 && "Unknown visitibility kind");
2568 case tok::objc_private: return ObjCIvarDecl::Private;
2569 case tok::objc_public: return ObjCIvarDecl::Public;
2570 case tok::objc_protected: return ObjCIvarDecl::Protected;
2571 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002572 }
2573}
2574
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002575/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2576/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002577Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002578 SourceLocation DeclStart,
2579 Declarator &D, ExprTy *BitfieldWidth,
2580 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002581 IdentifierInfo *II = D.getIdentifier();
2582 Expr *BitWidth = (Expr*)BitfieldWidth;
2583 SourceLocation Loc = DeclStart;
2584 if (II) Loc = D.getIdentifierLoc();
2585
2586 // FIXME: Unnamed fields can be handled in various different ways, for
2587 // example, unnamed unions inject all members into the struct namespace!
2588
2589
2590 if (BitWidth) {
2591 // TODO: Validate.
2592 //printf("WARNING: BITFIELDS IGNORED!\n");
2593
2594 // 6.7.2.1p3
2595 // 6.7.2.1p4
2596
2597 } else {
2598 // Not a bitfield.
2599
2600 // validate II.
2601
2602 }
2603
2604 QualType T = GetTypeForDeclarator(D, S);
2605 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2606 bool InvalidDecl = false;
2607
2608 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2609 // than a variably modified type.
2610 if (T->isVariablyModifiedType()) {
2611 // FIXME: This diagnostic needs work
2612 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2613 InvalidDecl = true;
2614 }
2615
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002616 // Get the visibility (access control) for this ivar.
2617 ObjCIvarDecl::AccessControl ac =
2618 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2619 : ObjCIvarDecl::None;
2620
2621 // Construct the decl.
2622 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002623 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002624
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002625 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002626 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002627
2628 if (D.getInvalidType() || InvalidDecl)
2629 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002630
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002631 return NewID;
2632}
2633
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002634void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002635 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002636 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002637 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002638 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002639 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2640 assert(EnclosingDecl && "missing record or interface decl");
2641 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2642
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002643 if (Record)
2644 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2645 // Diagnose code like:
2646 // struct S { struct S {} X; };
2647 // We discover this when we complete the outer S. Reject and ignore the
2648 // outer S.
2649 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2650 DefRecord->getKindName());
2651 Diag(RecLoc, diag::err_previous_definition);
2652 Record->setInvalidDecl();
2653 return;
2654 }
2655
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 // Verify that all the fields are okay.
2657 unsigned NumNamedMembers = 0;
2658 llvm::SmallVector<FieldDecl*, 32> RecFields;
2659 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002660
Reid Spencer5f016e22007-07-11 17:01:13 +00002661 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002662
Steve Naroff74216642007-09-14 22:20:54 +00002663 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2664 assert(FD && "missing field decl");
2665
2666 // Remember all fields.
2667 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002668
2669 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002670 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002671
Reid Spencer5f016e22007-07-11 17:01:13 +00002672 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002673 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00002674 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00002675 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002676 FD->setInvalidDecl();
2677 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002678 continue;
2679 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002680 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2681 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002682 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002683 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002684 FD->setInvalidDecl();
2685 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002686 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002687 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002688 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002689 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002690 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002691 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002692 FD->setInvalidDecl();
2693 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002694 continue;
2695 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002696 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002697 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2698 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002699 FD->setInvalidDecl();
2700 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002701 continue;
2702 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002703 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002704 if (Record)
2705 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002706 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002707 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2708 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002709 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002710 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2711 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002712 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002713 Record->setHasFlexibleArrayMember(true);
2714 } else {
2715 // If this is a struct/class and this is not the last element, reject
2716 // it. Note that GCC supports variable sized arrays in the middle of
2717 // structures.
2718 if (i != NumFields-1) {
2719 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2720 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002721 FD->setInvalidDecl();
2722 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002723 continue;
2724 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002725 // We support flexible arrays at the end of structs in other structs
2726 // as an extension.
2727 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2728 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002729 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002730 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002731 }
2732 }
2733 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002734 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002735 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002736 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2737 FD->getName());
2738 FD->setInvalidDecl();
2739 EnclosingDecl->setInvalidDecl();
2740 continue;
2741 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002742 // Keep track of the number of named members.
2743 if (IdentifierInfo *II = FD->getIdentifier()) {
2744 // Detect duplicate member names.
2745 if (!FieldIDs.insert(II)) {
2746 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2747 // Find the previous decl.
2748 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00002749 for (unsigned i = 0; ; ++i) {
2750 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00002751 if (RecFields[i]->getIdentifier() == II) {
2752 PrevLoc = RecFields[i]->getLocation();
2753 break;
2754 }
2755 }
2756 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002757 FD->setInvalidDecl();
2758 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002759 continue;
2760 }
2761 ++NumNamedMembers;
2762 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002763 }
2764
Reid Spencer5f016e22007-07-11 17:01:13 +00002765 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002766 if (Record) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002767 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00002768 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2769 // Sema::ActOnFinishCXXClassDef.
2770 if (!isa<CXXRecordDecl>(Record))
2771 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00002772 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002773 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2774 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2775 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2776 else if (ObjCImplementationDecl *IMPDecl =
2777 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002778 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2779 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002780 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002781 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002782 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00002783
2784 if (Attr)
2785 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002786}
2787
Steve Naroff08d92e42007-09-15 18:49:24 +00002788Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002789 DeclTy *lastEnumConst,
2790 SourceLocation IdLoc, IdentifierInfo *Id,
2791 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002792 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002793 EnumConstantDecl *LastEnumConst =
2794 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2795 Expr *Val = static_cast<Expr*>(val);
2796
Chris Lattner31e05722007-08-26 06:24:45 +00002797 // The scope passed in may not be a decl scope. Zip up the scope tree until
2798 // we find one that is.
2799 while ((S->getFlags() & Scope::DeclScope) == 0)
2800 S = S->getParent();
2801
Reid Spencer5f016e22007-07-11 17:01:13 +00002802 // Verify that there isn't already something declared with this name in this
2803 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002804 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002805 // When in C++, we may get a TagDecl with the same name; in this case the
2806 // enum constant will 'hide' the tag.
2807 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2808 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002809 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002810 if (isa<EnumConstantDecl>(PrevDecl))
2811 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2812 else
2813 Diag(IdLoc, diag::err_redefinition, Id->getName());
2814 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002815 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002816 return 0;
2817 }
2818 }
2819
2820 llvm::APSInt EnumVal(32);
2821 QualType EltTy;
2822 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002823 // Make sure to promote the operand type to int.
2824 UsualUnaryConversions(Val);
2825
Reid Spencer5f016e22007-07-11 17:01:13 +00002826 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2827 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002828 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002829 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2830 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002831 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002832 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002833 } else {
2834 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002835 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002836 }
2837
2838 if (!Val) {
2839 if (LastEnumConst) {
2840 // Assign the last value + 1.
2841 EnumVal = LastEnumConst->getInitVal();
2842 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002843
2844 // Check for overflow on increment.
2845 if (EnumVal < LastEnumConst->getInitVal())
2846 Diag(IdLoc, diag::warn_enum_value_overflow);
2847
Chris Lattnerb7416f92007-08-27 17:37:24 +00002848 EltTy = LastEnumConst->getType();
2849 } else {
2850 // First value, set to zero.
2851 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002852 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002853 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002854 }
2855
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002856 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002857 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2858 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002859 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002860
2861 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002862 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002863 return New;
2864}
2865
Steve Naroff02408c62008-08-07 14:08:16 +00002866// FIXME: For consistency with ActOnFields(), we should have the parser
2867// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00002868void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002869 DeclTy **Elements, unsigned NumElements) {
2870 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00002871
Steve Naroff02408c62008-08-07 14:08:16 +00002872 if (Enum && Enum->isDefinition()) {
2873 // Diagnose code like:
2874 // enum e0 {
2875 // E0 = sizeof(enum e0 { E1 })
2876 // };
2877 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2878 Enum->getName());
2879 Diag(EnumLoc, diag::err_previous_definition);
2880 Enum->setInvalidDecl();
2881 return;
2882 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00002883 // TODO: If the result value doesn't fit in an int, it must be a long or long
2884 // long value. ISO C does not support this, but GCC does as an extension,
2885 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002886 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002887
Chris Lattnerac609682007-08-28 06:15:15 +00002888 // Verify that all the values are okay, compute the size of the values, and
2889 // reverse the list.
2890 unsigned NumNegativeBits = 0;
2891 unsigned NumPositiveBits = 0;
2892
2893 // Keep track of whether all elements have type int.
2894 bool AllElementsInt = true;
2895
Reid Spencer5f016e22007-07-11 17:01:13 +00002896 EnumConstantDecl *EltList = 0;
2897 for (unsigned i = 0; i != NumElements; ++i) {
2898 EnumConstantDecl *ECD =
2899 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2900 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002901
2902 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002903 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002904 assert(InitVal.getBitWidth() >= IntWidth &&
2905 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002906 if (InitVal.getBitWidth() > IntWidth) {
2907 llvm::APSInt V(InitVal);
2908 V.trunc(IntWidth);
2909 V.extend(InitVal.getBitWidth());
2910 if (V != InitVal)
2911 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattner9aa77f12008-08-17 07:19:51 +00002912 InitVal.toString(10));
Chris Lattner211a30e2007-08-28 05:27:00 +00002913 }
Chris Lattnerac609682007-08-28 06:15:15 +00002914
2915 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002916 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002917 NumPositiveBits = std::max(NumPositiveBits,
2918 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002919 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002920 NumNegativeBits = std::max(NumNegativeBits,
2921 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002922
Chris Lattnerac609682007-08-28 06:15:15 +00002923 // Keep track of whether every enum element has type int (very commmon).
2924 if (AllElementsInt)
2925 AllElementsInt = ECD->getType() == Context.IntTy;
2926
Reid Spencer5f016e22007-07-11 17:01:13 +00002927 ECD->setNextDeclarator(EltList);
2928 EltList = ECD;
2929 }
2930
Chris Lattnerac609682007-08-28 06:15:15 +00002931 // Figure out the type that should be used for this enum.
2932 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2933 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002934 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002935
2936 if (NumNegativeBits) {
2937 // If there is a negative value, figure out the smallest integer type (of
2938 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002939 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002940 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002941 BestWidth = IntWidth;
2942 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002943 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002944
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002945 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002946 BestType = Context.LongTy;
2947 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002948 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002949
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002950 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002951 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2952 BestType = Context.LongLongTy;
2953 }
2954 }
2955 } else {
2956 // If there is no negative value, figure out which of uint, ulong, ulonglong
2957 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002958 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002959 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002960 BestWidth = IntWidth;
2961 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002962 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002963 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002964 } else {
2965 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002966 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002967 "How could an initializer get larger than ULL?");
2968 BestType = Context.UnsignedLongLongTy;
2969 }
2970 }
2971
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002972 // Loop over all of the enumerator constants, changing their types to match
2973 // the type of the enum if needed.
2974 for (unsigned i = 0; i != NumElements; ++i) {
2975 EnumConstantDecl *ECD =
2976 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2977 if (!ECD) continue; // Already issued a diagnostic.
2978
2979 // Standard C says the enumerators have int type, but we allow, as an
2980 // extension, the enumerators to be larger than int size. If each
2981 // enumerator value fits in an int, type it as an int, otherwise type it the
2982 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2983 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002984 if (ECD->getType() == Context.IntTy) {
2985 // Make sure the init value is signed.
2986 llvm::APSInt IV = ECD->getInitVal();
2987 IV.setIsSigned(true);
2988 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002989 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002990 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002991
2992 // Determine whether the value fits into an int.
2993 llvm::APSInt InitVal = ECD->getInitVal();
2994 bool FitsInInt;
2995 if (InitVal.isUnsigned() || !InitVal.isNegative())
2996 FitsInInt = InitVal.getActiveBits() < IntWidth;
2997 else
2998 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2999
3000 // If it fits into an integer type, force it. Otherwise force it to match
3001 // the enum decl type.
3002 QualType NewTy;
3003 unsigned NewWidth;
3004 bool NewSign;
3005 if (FitsInInt) {
3006 NewTy = Context.IntTy;
3007 NewWidth = IntWidth;
3008 NewSign = true;
3009 } else if (ECD->getType() == BestType) {
3010 // Already the right type!
3011 continue;
3012 } else {
3013 NewTy = BestType;
3014 NewWidth = BestWidth;
3015 NewSign = BestType->isSignedIntegerType();
3016 }
3017
3018 // Adjust the APSInt value.
3019 InitVal.extOrTrunc(NewWidth);
3020 InitVal.setIsSigned(NewSign);
3021 ECD->setInitVal(InitVal);
3022
3023 // Adjust the Expr initializer and type.
3024 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
3025 ECD->setType(NewTy);
3026 }
Chris Lattnerac609682007-08-28 06:15:15 +00003027
Chris Lattnere00b18c2007-08-28 18:24:31 +00003028 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003029 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003030}
3031
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003032Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3033 ExprTy *expr) {
3034 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
3035
Chris Lattner8e25d862008-03-16 00:16:02 +00003036 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003037}
3038
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003039Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00003040 SourceLocation LBrace,
3041 SourceLocation RBrace,
3042 const char *Lang,
3043 unsigned StrSize,
3044 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003045 LinkageSpecDecl::LanguageIDs Language;
3046 Decl *dcl = static_cast<Decl *>(D);
3047 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3048 Language = LinkageSpecDecl::lang_c;
3049 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3050 Language = LinkageSpecDecl::lang_cxx;
3051 else {
3052 Diag(Loc, diag::err_bad_language);
3053 return 0;
3054 }
3055
3056 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00003057 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003058}
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003059
3060void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3061 ExprTy *alignment, SourceLocation PragmaLoc,
3062 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3063 Expr *Alignment = static_cast<Expr *>(alignment);
3064
3065 // If specified then alignment must be a "small" power of two.
3066 unsigned AlignmentVal = 0;
3067 if (Alignment) {
3068 llvm::APSInt Val;
3069 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3070 !Val.isPowerOf2() ||
3071 Val.getZExtValue() > 16) {
3072 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3073 delete Alignment;
3074 return; // Ignore
3075 }
3076
3077 AlignmentVal = (unsigned) Val.getZExtValue();
3078 }
3079
3080 switch (Kind) {
3081 case Action::PPK_Default: // pack([n])
3082 PackContext.setAlignment(AlignmentVal);
3083 break;
3084
3085 case Action::PPK_Show: // pack(show)
3086 // Show the current alignment, making sure to show the right value
3087 // for the default.
3088 AlignmentVal = PackContext.getAlignment();
3089 // FIXME: This should come from the target.
3090 if (AlignmentVal == 0)
3091 AlignmentVal = 8;
3092 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal));
3093 break;
3094
3095 case Action::PPK_Push: // pack(push [, id] [, [n])
3096 PackContext.push(Name);
3097 // Set the new alignment if specified.
3098 if (Alignment)
3099 PackContext.setAlignment(AlignmentVal);
3100 break;
3101
3102 case Action::PPK_Pop: // pack(pop [, id] [, n])
3103 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3104 // "#pragma pack(pop, identifier, n) is undefined"
3105 if (Alignment && Name)
3106 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3107
3108 // Do the pop.
3109 if (!PackContext.pop(Name)) {
3110 // If a name was specified then failure indicates the name
3111 // wasn't found. Otherwise failure indicates the stack was
3112 // empty.
3113 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
3114 Name ? "no record matching name" : "stack empty");
3115
3116 // FIXME: Warn about popping named records as MSVC does.
3117 } else {
3118 // Pop succeeded, set the new alignment if specified.
3119 if (Alignment)
3120 PackContext.setAlignment(AlignmentVal);
3121 }
3122 break;
3123
3124 default:
3125 assert(0 && "Invalid #pragma pack kind.");
3126 }
3127}
3128
3129bool PragmaPackStack::pop(IdentifierInfo *Name) {
3130 if (Stack.empty())
3131 return false;
3132
3133 // If name is empty just pop top.
3134 if (!Name) {
3135 Alignment = Stack.back().first;
3136 Stack.pop_back();
3137 return true;
3138 }
3139
3140 // Otherwise, find the named record.
3141 for (unsigned i = Stack.size(); i != 0; ) {
3142 --i;
3143 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) {
3144 // Found it, pop up to and including this record.
3145 Alignment = Stack[i].first;
3146 Stack.erase(Stack.begin() + i, Stack.end());
3147 return true;
3148 }
3149 }
3150
3151 return false;
3152}