blob: fbf89ae3117ae46ad52e6004618e071353343f7b [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6953a072008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregor39677622008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
29
Chris Lattner4b009652007-07-25 00:24:17 +000030using namespace clang;
31
Douglas Gregorb0212bd2008-11-17 20:34:05 +000032Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000033 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000034 DeclContext *DC = 0;
35 if (SS) {
36 if (SS->isInvalid())
37 return 0;
38 DC = static_cast<DeclContext*>(SS->getScopeRep());
39 }
40 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroff6384a012008-04-02 14:35:35 +000041
Douglas Gregor1d661552008-04-13 21:07:44 +000042 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
43 isa<ObjCInterfaceDecl>(IIDecl) ||
Douglas Gregordd861062008-12-05 18:15:24 +000044 isa<TagDecl>(IIDecl) ||
45 isa<TemplateTypeParmDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000046 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000047 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000048}
49
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000050DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000051 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000052 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000053 if (MD->isOutOfLineDefinition())
54 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000055
56 // A C++ inline method is parsed *after* the topmost class it was declared in
57 // is fully parsed (it's "complete").
58 // The parsing of a C++ inline method happens at the declaration context of
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000059 // the topmost (non-nested) class it is lexically declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000060 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
61 DC = MD->getParent();
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000062 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000063 DC = RD;
64
65 // Return the declaration context of the topmost class the inline method is
66 // declared in.
67 return DC;
68 }
69
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000070 if (isa<ObjCMethodDecl>(DC))
71 return Context.getTranslationUnitDecl();
72
73 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
74 return SD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000075
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000076 return DC->getLexicalParent();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000077}
78
Douglas Gregor8acb7272008-12-11 16:49:14 +000079void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000080 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu2c9b8102008-12-08 07:14:51 +000081 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000082 CurContext = DC;
Douglas Gregor8acb7272008-12-11 16:49:14 +000083 S->setEntity(DC);
Chris Lattnereee57c02008-04-04 06:12:32 +000084}
85
Chris Lattnerf3874bc2008-04-06 04:47:34 +000086void Sema::PopDeclContext() {
87 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor8acb7272008-12-11 16:49:14 +000088
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000089 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +000090}
91
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000092/// Add this decl to the scope shadowed decl chains.
93void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000094 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000095
96 // C++ [basic.scope]p4:
97 // -- exactly one declaration shall declare a class name or
98 // enumeration name that is not a typedef name and the other
99 // declarations shall all refer to the same object or
100 // enumerator, or all refer to functions and function templates;
101 // in this case the class name or enumeration name is hidden.
102 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
103 // We are pushing the name of a tag (enum or class).
Douglas Gregor8acb7272008-12-11 16:49:14 +0000104 if (CurContext == TD->getDeclContext()) {
105 // We're pushing the tag into the current context, which might
106 // require some reshuffling in the identifier resolver.
107 IdentifierResolver::iterator
108 I = IdResolver.begin(TD->getIdentifier(), CurContext,
109 false/*LookInParentCtx*/);
110 if (I != IdResolver.end()) {
111 // There is already a declaration with the same name in the same
112 // scope. It must be found before we find the new declaration,
113 // so swap the order on the shadowed declaration chain.
114 IdResolver.AddShadowedDecl(TD, *I);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000115
Douglas Gregor8acb7272008-12-11 16:49:14 +0000116 // Add this declaration to the current context.
117 CurContext->addDecl(Context, TD);
118
119 return;
120 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000121 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000122 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000123 // We are pushing the name of a function, which might be an
124 // overloaded name.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000125 FunctionDecl *FD = cast<FunctionDecl>(D);
126 Decl *Prev = LookupDecl(FD->getDeclName(), Decl::IDNS_Ordinary, S,
127 FD->getDeclContext(), false, false);
128 if (Prev && (isa<OverloadedFunctionDecl>(Prev) || isa<FunctionDecl>(Prev))) {
129 // There is already a declaration with the same name in
130 // the same scope. It must be a function or an overloaded
131 // function.
132 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(Prev);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000133 if (!Ovl) {
134 // We haven't yet overloaded this function. Take the existing
135 // FunctionDecl and put it into an OverloadedFunctionDecl.
136 Ovl = OverloadedFunctionDecl::Create(Context,
137 FD->getDeclContext(),
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000138 FD->getDeclName());
Douglas Gregor39677622008-12-11 20:41:00 +0000139 Ovl->addOverload(cast<FunctionDecl>(Prev));
Douglas Gregord2baafd2008-10-21 16:13:35 +0000140
Douglas Gregor39677622008-12-11 20:41:00 +0000141 // If there is an ame binding for the existing FunctionDecl,
Douglas Gregor8acb7272008-12-11 16:49:14 +0000142 // remove it.
143 for (IdentifierResolver::iterator I
144 = IdResolver.begin(FD->getDeclName(), FD->getDeclContext(),
Douglas Gregor39677622008-12-11 20:41:00 +0000145 false/*LookInParentCtx*/),
146 E = IdResolver.end(); I != E; ++I) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000147 if (*I == Prev) {
148 IdResolver.RemoveDecl(*I);
149 S->RemoveDecl(*I);
150 break;
151 }
152 }
153
154 // Add the name binding for the OverloadedFunctionDecl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000155 IdResolver.AddDecl(Ovl);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000156
157 // Update the context with the newly-created overloaded
158 // function set.
159 FD->getDeclContext()->insert(Context, Ovl);
160
161 S->AddDecl(Ovl);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000162 }
163
Douglas Gregor8acb7272008-12-11 16:49:14 +0000164 // We added this function declaration to the scope earlier, but
165 // we don't want it there because it is part of the overloaded
166 // function declaration.
167 S->RemoveDecl(FD);
168
Douglas Gregord2baafd2008-10-21 16:13:35 +0000169 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
170 // to its list of overloads.
171 Ovl->addOverload(FD);
172
Douglas Gregor8acb7272008-12-11 16:49:14 +0000173 // Add this new function declaration to the declaration context.
174 CurContext->addDecl(Context, FD, false);
175
176 return;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000177 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000178 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000179
Douglas Gregor39677622008-12-11 20:41:00 +0000180 // Add scoped declarations into their context, so that they can be
181 // found later. Declarations without a context won't be inserted
182 // into any context.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000183 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
184 CurContext->addDecl(Context, SD);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000185
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000186 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000187}
188
Steve Naroff9637a9b2007-10-09 22:01:59 +0000189void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000190 if (S->decl_empty()) return;
Douglas Gregordd861062008-12-05 18:15:24 +0000191 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
192 "Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000193
Chris Lattner4b009652007-07-25 00:24:17 +0000194 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
195 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000196 Decl *TmpD = static_cast<Decl*>(*I);
197 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000198
Douglas Gregor8acb7272008-12-11 16:49:14 +0000199 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
200 NamedDecl *D = cast<NamedDecl>(TmpD);
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000201
Douglas Gregor8acb7272008-12-11 16:49:14 +0000202 if (!D->getDeclName()) continue;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000203
Douglas Gregor8acb7272008-12-11 16:49:14 +0000204 // Remove this name from our lexical scope.
205 IdResolver.RemoveDecl(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000206 }
207}
208
Steve Naroffe57c21a2008-04-01 23:04:06 +0000209/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
210/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000211ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000212 // The third "scope" argument is 0 since we aren't enabling lazy built-in
213 // creation from this context.
214 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000215
Steve Naroff6384a012008-04-02 14:35:35 +0000216 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000217}
218
Steve Naroffe57c21a2008-04-01 23:04:06 +0000219/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000220/// namespace.
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000221Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000222 const DeclContext *LookupCtx,
Douglas Gregor8acb7272008-12-11 16:49:14 +0000223 bool enableLazyBuiltinCreation,
224 bool LookInParent) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000225 if (!Name) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000226 unsigned NS = NSI;
227 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
228 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000229
Douglas Gregor39677622008-12-11 20:41:00 +0000230 if (LookupCtx == 0 &&
231 (!getLangOptions().CPlusPlus || (NS == Decl::IDNS_Label))) {
232 // Unqualified name lookup in C/Objective-C and name lookup for
233 // labels in C++ is purely lexical, so search in the
234 // declarations attached to the name.
235 assert(!LookupCtx && "Can't perform qualified name lookup here");
236 IdentifierResolver::iterator I
237 = IdResolver.begin(Name, CurContext, LookInParent);
238
239 // Scan up the scope chain looking for a decl that matches this
240 // identifier that is in the appropriate namespace. This search
241 // should not take long, as shadowing of names is uncommon, and
242 // deep shadowing is extremely uncommon.
243 for (; I != IdResolver.end(); ++I)
244 if ((*I)->getIdentifierNamespace() & NS)
245 return *I;
246 } else if (LookupCtx) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000247 assert(getLangOptions().CPlusPlus && "No qualified name lookup in C");
248
Douglas Gregor98341042008-12-12 08:25:50 +0000249 switch (Name.getNameKind()) {
250 case DeclarationName::CXXConstructorName:
251 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(LookupCtx))
252 return const_cast<CXXRecordDecl *>(Record)->getConstructors();
253 else
254 return 0;
255
256 case DeclarationName::CXXDestructorName:
257 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(LookupCtx))
258 return Record->getDestructor();
259 else
260 return 0;
261
262 default:
263 // Normal name lookup.
264 break;
265 }
266
Douglas Gregor8acb7272008-12-11 16:49:14 +0000267 // Perform qualified name lookup into the LookupCtx.
268 // FIXME: Will need to look into base classes and such.
Douglas Gregor39677622008-12-11 20:41:00 +0000269 DeclContext::lookup_const_iterator I, E;
270 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
271 if ((*I)->getIdentifierNamespace() & NS)
272 return *I;
273 } else {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000274 // Name lookup for ordinary names and tag names in C++ requires
275 // looking into scopes that aren't strictly lexical, and
276 // therefore we walk through the context as well as walking
277 // through the scopes.
278 IdentifierResolver::iterator
279 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
280 IEnd = IdResolver.end();
281 for (; S; S = S->getParent()) {
282 // Check whether the IdResolver has anything in this scope.
283 // FIXME: The isDeclScope check could be expensive. Can we do better?
284 for (; I != IEnd && S->isDeclScope(*I); ++I)
285 if ((*I)->getIdentifierNamespace() & NS)
286 return *I;
287
288 // If there is an entity associated with this scope, it's a
289 // DeclContext. We might need to perform qualified lookup into
290 // it.
291 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
292 while (Ctx && Ctx->isFunctionOrMethod())
293 Ctx = Ctx->getParent();
294 while (Ctx && (Ctx->isNamespace() || Ctx->isCXXRecord())) {
295 // Look for declarations of this name in this scope.
Douglas Gregor39677622008-12-11 20:41:00 +0000296 DeclContext::lookup_const_iterator I, E;
297 for (llvm::tie(I, E) = Ctx->lookup(Context, Name); I != E; ++I) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000298 // FIXME: Cache this result in the IdResolver
Douglas Gregor39677622008-12-11 20:41:00 +0000299 if ((*I)->getIdentifierNamespace() & NS)
300 return *I;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000301 }
302
303 Ctx = Ctx->getParent();
304 }
305
306 if (!LookInParent)
307 return 0;
308 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000309 }
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000310
Chris Lattner4b009652007-07-25 00:24:17 +0000311 // If we didn't find a use of this identifier, and if the identifier
312 // corresponds to a compiler builtin, create the decl object for the builtin
313 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000314 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000315 IdentifierInfo *II = Name.getAsIdentifierInfo();
316 if (enableLazyBuiltinCreation && II &&
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000317 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroff6384a012008-04-02 14:35:35 +0000318 // If this is a builtin on this (or all) targets, create the decl.
319 if (unsigned BuiltinID = II->getBuiltinID())
320 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
321 }
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000322 if (getLangOptions().ObjC1 && II) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000323 // @interface and @compatibility_alias introduce typedef-like names.
324 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000325 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000326 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000327 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
328 if (IDI != ObjCInterfaceDecls.end())
329 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000330 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
331 if (I != ObjCAliasDecls.end())
332 return I->second->getClassInterface();
333 }
Chris Lattner4b009652007-07-25 00:24:17 +0000334 }
335 return 0;
336}
337
Chris Lattnera9c87f22008-05-05 22:18:14 +0000338void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000339 if (!Context.getBuiltinVaListType().isNull())
340 return;
341
342 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000343 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000344 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000345 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
346}
347
Chris Lattner4b009652007-07-25 00:24:17 +0000348/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
349/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000350ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
351 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000352 Builtin::ID BID = (Builtin::ID)bid;
353
Chris Lattnerb23469f2008-09-28 05:54:29 +0000354 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000355 InitBuiltinVaListType();
356
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000357 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000358 FunctionDecl *New = FunctionDecl::Create(Context,
359 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000360 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000361 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000362
Chris Lattnera9c87f22008-05-05 22:18:14 +0000363 // Create Decl objects for each parameter, adding them to the
364 // FunctionDecl.
365 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
366 llvm::SmallVector<ParmVarDecl*, 16> Params;
367 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
368 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
369 FT->getArgType(i), VarDecl::None, 0,
370 0));
371 New->setParams(&Params[0], Params.size());
372 }
373
374
375
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000376 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000377 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000378 return New;
379}
380
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000381/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
382/// everything from the standard library is defined.
383NamespaceDecl *Sema::GetStdNamespace() {
384 if (!StdNamespace) {
Chris Lattnerf0939602008-11-20 05:45:14 +0000385 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000386 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattnerf0939602008-11-20 05:45:14 +0000387 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000388 0, Global, /*enableLazyBuiltinCreation=*/false);
389 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
390 }
391 return StdNamespace;
392}
393
Chris Lattner4b009652007-07-25 00:24:17 +0000394/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
395/// and scope as a previous declaration 'Old'. Figure out how to resolve this
396/// situation, merging decls or emitting diagnostics as appropriate.
397///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000398TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff453a8782008-09-09 14:32:20 +0000399 // Allow multiple definitions for ObjC built-in typedefs.
400 // FIXME: Verify the underlying types are equivalent!
401 if (getLangOptions().ObjC1) {
Chris Lattner6d16b052008-11-20 05:41:43 +0000402 const IdentifierInfo *TypeID = New->getIdentifier();
403 switch (TypeID->getLength()) {
404 default: break;
405 case 2:
406 if (!TypeID->isStr("id"))
407 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000408 Context.setObjCIdType(New);
409 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000410 case 5:
411 if (!TypeID->isStr("Class"))
412 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000413 Context.setObjCClassType(New);
414 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000415 case 3:
416 if (!TypeID->isStr("SEL"))
417 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000418 Context.setObjCSelType(New);
419 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000420 case 8:
421 if (!TypeID->isStr("Protocol"))
422 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000423 Context.setObjCProtoType(New->getUnderlyingType());
424 return New;
425 }
426 // Fall through - the typedef name was not a builtin type.
427 }
Chris Lattner4b009652007-07-25 00:24:17 +0000428 // Verify the old decl was also a typedef.
429 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
430 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000431 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000432 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000433 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000434 return New;
435 }
436
Chris Lattnerbef8d622008-07-25 18:44:27 +0000437 // If the typedef types are not identical, reject them in all languages and
438 // with any extensions enabled.
439 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
440 Context.getCanonicalType(Old->getUnderlyingType()) !=
441 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner8d756812008-11-20 06:13:02 +0000442 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000443 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner1336cab2008-11-23 23:12:31 +0000444 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerbef8d622008-07-25 18:44:27 +0000445 return Old;
446 }
447
Eli Friedman324d5032008-06-11 06:20:39 +0000448 if (getLangOptions().Microsoft) return New;
449
Douglas Gregor49ba1b72008-11-21 16:29:06 +0000450 // C++ [dcl.typedef]p2:
451 // In a given non-class scope, a typedef specifier can be used to
452 // redefine the name of any type declared in that scope to refer
453 // to the type to which it already refers.
454 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
455 return New;
456
457 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroffa9eae582008-01-30 23:46:05 +0000458 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
459 // *either* declaration is in a system header. The code below implements
460 // this adhoc compatibility rule. FIXME: The following code will not
461 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000462 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
463 SourceManager &SrcMgr = Context.getSourceManager();
464 if (SrcMgr.isInSystemHeader(Old->getLocation()))
465 return New;
466 if (SrcMgr.isInSystemHeader(New->getLocation()))
467 return New;
468 }
Eli Friedman324d5032008-06-11 06:20:39 +0000469
Chris Lattnerb1753422008-11-23 21:45:46 +0000470 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000471 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000472 return New;
473}
474
Chris Lattner6953a072008-06-26 18:38:35 +0000475/// DeclhasAttr - returns true if decl Declaration already has the target
476/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000477static bool DeclHasAttr(const Decl *decl, const Attr *target) {
478 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
479 if (attr->getKind() == target->getKind())
480 return true;
481
482 return false;
483}
484
485/// MergeAttributes - append attributes from the Old decl to the New one.
486static void MergeAttributes(Decl *New, Decl *Old) {
487 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
488
Chris Lattner402b3372008-03-03 03:28:21 +0000489 while (attr) {
490 tmp = attr;
491 attr = attr->getNext();
492
493 if (!DeclHasAttr(New, tmp)) {
494 New->addAttr(tmp);
495 } else {
496 tmp->setNext(0);
497 delete(tmp);
498 }
499 }
Nuno Lopes77654342008-06-01 22:53:53 +0000500
501 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000502}
503
Chris Lattner3e254fb2008-04-08 04:40:51 +0000504/// MergeFunctionDecl - We just parsed a function 'New' from
505/// declarator D which has the same name and scope as a previous
506/// declaration 'Old'. Figure out how to resolve this situation,
507/// merging decls or emitting diagnostics as appropriate.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000508/// Redeclaration will be set true if this New is a redeclaration OldD.
509///
510/// In C++, New and Old must be declarations that are not
511/// overloaded. Use IsOverload to determine whether New and Old are
512/// overloaded, and to select the Old declaration that New should be
513/// merged with.
Douglas Gregor42214c52008-04-21 02:02:58 +0000514FunctionDecl *
515Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000516 assert(!isa<OverloadedFunctionDecl>(OldD) &&
517 "Cannot merge with an overloaded function declaration");
518
Douglas Gregor42214c52008-04-21 02:02:58 +0000519 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000520 // Verify the old decl was also a function.
521 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
522 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000523 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000524 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000525 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000526 return New;
527 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000528
529 // Determine whether the previous declaration was a definition,
530 // implicit declaration, or a declaration.
531 diag::kind PrevDiag;
532 if (Old->isThisDeclarationADefinition())
Chris Lattner1336cab2008-11-23 23:12:31 +0000533 PrevDiag = diag::note_previous_definition;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000534 else if (Old->isImplicit())
Chris Lattner1336cab2008-11-23 23:12:31 +0000535 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000536 else
Chris Lattner1336cab2008-11-23 23:12:31 +0000537 PrevDiag = diag::note_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000538
Chris Lattner42a21742008-04-06 23:10:54 +0000539 QualType OldQType = Context.getCanonicalType(Old->getType());
540 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000541
Douglas Gregord2baafd2008-10-21 16:13:35 +0000542 if (getLangOptions().CPlusPlus) {
543 // (C++98 13.1p2):
544 // Certain function declarations cannot be overloaded:
545 // -- Function declarations that differ only in the return type
546 // cannot be overloaded.
547 QualType OldReturnType
548 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
549 QualType NewReturnType
550 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
551 if (OldReturnType != NewReturnType) {
552 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
553 Diag(Old->getLocation(), PrevDiag);
554 return New;
555 }
556
557 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
558 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
559 if (OldMethod && NewMethod) {
560 // -- Member function declarations with the same name and the
561 // same parameter types cannot be overloaded if any of them
562 // is a static member function declaration.
563 if (OldMethod->isStatic() || NewMethod->isStatic()) {
564 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
565 Diag(Old->getLocation(), PrevDiag);
566 return New;
567 }
568 }
569
570 // (C++98 8.3.5p3):
571 // All declarations for a function shall agree exactly in both the
572 // return type and the parameter-type-list.
573 if (OldQType == NewQType) {
574 // We have a redeclaration.
575 MergeAttributes(New, Old);
576 Redeclaration = true;
577 return MergeCXXFunctionDecl(New, Old);
578 }
579
580 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000581 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000582
583 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000584 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000585 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000586 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000587 MergeAttributes(New, Old);
588 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000589 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000590 }
Chris Lattner1470b072007-11-06 06:07:26 +0000591
Steve Naroff6c9e7922008-01-16 15:01:34 +0000592 // A function that has already been declared has been redeclared or defined
593 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000594
Chris Lattner4b009652007-07-25 00:24:17 +0000595 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
596 // TODO: This is totally simplistic. It should handle merging functions
597 // together etc, merging extern int X; int X; ...
Chris Lattner271d4c22008-11-24 05:29:24 +0000598 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff6c9e7922008-01-16 15:01:34 +0000599 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000600 return New;
601}
602
Steve Naroffb5e78152008-08-08 17:50:35 +0000603/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000604static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000605 if (VD->isFileVarDecl())
606 return (!VD->getInit() &&
607 (VD->getStorageClass() == VarDecl::None ||
608 VD->getStorageClass() == VarDecl::Static));
609 return false;
610}
611
612/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
613/// when dealing with C "tentative" external object definitions (C99 6.9.2).
614void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
615 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000616 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000617
618 for (IdentifierResolver::iterator
619 I = IdResolver.begin(VD->getIdentifier(),
620 VD->getDeclContext(), false/*LookInParentCtx*/),
621 E = IdResolver.end(); I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000622 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000623 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
624
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000625 // Handle the following case:
626 // int a[10];
627 // int a[]; - the code below makes sure we set the correct type.
628 // int a[11]; - this is an error, size isn't 10.
629 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
630 OldDecl->getType()->isConstantArrayType())
631 VD->setType(OldDecl->getType());
632
Steve Naroffb5e78152008-08-08 17:50:35 +0000633 // Check for "tentative" definitions. We can't accomplish this in
634 // MergeVarDecl since the initializer hasn't been attached.
635 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
636 continue;
637
638 // Handle __private_extern__ just like extern.
639 if (OldDecl->getStorageClass() != VarDecl::Extern &&
640 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
641 VD->getStorageClass() != VarDecl::Extern &&
642 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000643 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000644 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffb5e78152008-08-08 17:50:35 +0000645 }
646 }
647 }
648}
649
Chris Lattner4b009652007-07-25 00:24:17 +0000650/// MergeVarDecl - We just parsed a variable 'New' which has the same name
651/// and scope as a previous declaration 'Old'. Figure out how to resolve this
652/// situation, merging decls or emitting diagnostics as appropriate.
653///
Steve Naroffb5e78152008-08-08 17:50:35 +0000654/// Tentative definition rules (C99 6.9.2p2) are checked by
655/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
656/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000657///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000658VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000659 // Verify the old decl was also a variable.
660 VarDecl *Old = dyn_cast<VarDecl>(OldD);
661 if (!Old) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000662 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000663 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000664 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000665 return New;
666 }
Chris Lattner402b3372008-03-03 03:28:21 +0000667
668 MergeAttributes(New, Old);
669
Chris Lattner4b009652007-07-25 00:24:17 +0000670 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000671 QualType OldCType = Context.getCanonicalType(Old->getType());
672 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000673 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000674 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000675 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000676 return New;
677 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000678 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
679 if (New->getStorageClass() == VarDecl::Static &&
680 (Old->getStorageClass() == VarDecl::None ||
681 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000682 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000683 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000684 return New;
685 }
686 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
687 if (New->getStorageClass() != VarDecl::Static &&
688 Old->getStorageClass() == VarDecl::Static) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000689 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000690 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000691 return New;
692 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000693 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
694 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000695 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000696 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000697 }
698 return New;
699}
700
Chris Lattner3e254fb2008-04-08 04:40:51 +0000701/// CheckParmsForFunctionDef - Check that the parameters of the given
702/// function are appropriate for the definition of a function. This
703/// takes care of any checks that cannot be performed on the
704/// declaration itself, e.g., that the types of each of the function
705/// parameters are complete.
706bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
707 bool HasInvalidParm = false;
708 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
709 ParmVarDecl *Param = FD->getParamDecl(p);
710
711 // C99 6.7.5.3p4: the parameters in a parameter type list in a
712 // function declarator that is part of a function definition of
713 // that function shall not have incomplete type.
714 if (Param->getType()->isIncompleteType() &&
715 !Param->isInvalidDecl()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000716 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +0000717 << Param->getType();
Chris Lattner3e254fb2008-04-08 04:40:51 +0000718 Param->setInvalidDecl();
719 HasInvalidParm = true;
720 }
721 }
722
723 return HasInvalidParm;
724}
725
Chris Lattner4b009652007-07-25 00:24:17 +0000726/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
727/// no declarator (e.g. "struct foo;") is parsed.
728Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
729 // TODO: emit error on 'int;' or 'const enum foo;'.
730 // TODO: emit error on 'typedef int;'
731 // if (!DS.isMissingDeclaratorOk()) Diag(...);
732
Steve Naroffedafc0b2007-11-17 21:37:36 +0000733 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000734}
735
Steve Narofff0b23542008-01-10 22:15:12 +0000736bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000737 // Get the type before calling CheckSingleAssignmentConstraints(), since
738 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000739 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000740
Chris Lattner005ed752008-01-04 18:04:52 +0000741 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
742 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
743 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000744}
745
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000746bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000747 const ArrayType *AT = Context.getAsArrayType(DeclT);
748
749 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000750 // C99 6.7.8p14. We have an array of character type with unknown size
751 // being initialized to a string literal.
752 llvm::APSInt ConstVal(32);
753 ConstVal = strLiteral->getByteLength() + 1;
754 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000755 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000756 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000757 } else {
758 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000759 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000760 // FIXME: Avoid truncation for 64-bit length strings.
761 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000762 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000763 diag::warn_initializer_string_for_char_array_too_long)
764 << strLiteral->getSourceRange();
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000765 }
766 // Set type from "char *" to "constant array of char".
767 strLiteral->setType(DeclT);
768 // For now, we always return false (meaning success).
769 return false;
770}
771
772StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000773 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +0000774 if (AT && AT->getElementType()->isCharType()) {
775 return dyn_cast<StringLiteral>(Init);
776 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000777 return 0;
778}
779
Douglas Gregor6428e762008-11-05 15:29:30 +0000780bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
781 SourceLocation InitLoc,
Chris Lattner271d4c22008-11-24 05:29:24 +0000782 DeclarationName InitEntity) {
Douglas Gregor81c29152008-10-29 00:13:59 +0000783 // C++ [dcl.init.ref]p1:
Sebastian Redl51504af2008-11-24 20:06:50 +0000784 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor81c29152008-10-29 00:13:59 +0000785 // (8.3.2), shall be initialized by an object, or function, of
786 // type T or by an object that can be converted into a T.
787 if (DeclType->isReferenceType())
788 return CheckReferenceInit(Init, DeclType);
789
Steve Naroff8e9337f2008-01-21 23:53:58 +0000790 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
791 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +0000792 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattner9d2cf082008-11-19 05:27:50 +0000793 return Diag(InitLoc, diag::err_variable_object_no_init)
794 << VAT->getSizeExpr()->getSourceRange();
Steve Naroff8e9337f2008-01-21 23:53:58 +0000795
Steve Naroffcb69fb72007-12-10 22:44:33 +0000796 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
797 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000798 // FIXME: Handle wide strings
799 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
800 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000801
Douglas Gregor6428e762008-11-05 15:29:30 +0000802 // C++ [dcl.init]p14:
803 // -- If the destination type is a (possibly cv-qualified) class
804 // type:
805 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
806 QualType DeclTypeC = Context.getCanonicalType(DeclType);
807 QualType InitTypeC = Context.getCanonicalType(Init->getType());
808
809 // -- If the initialization is direct-initialization, or if it is
810 // copy-initialization where the cv-unqualified version of the
811 // source type is the same class as, or a derived class of, the
812 // class of the destination, constructors are considered.
813 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
814 IsDerivedFrom(InitTypeC, DeclTypeC)) {
815 CXXConstructorDecl *Constructor
816 = PerformInitializationByConstructor(DeclType, &Init, 1,
817 InitLoc, Init->getSourceRange(),
818 InitEntity, IK_Copy);
819 return Constructor == 0;
820 }
821
822 // -- Otherwise (i.e., for the remaining copy-initialization
823 // cases), user-defined conversion sequences that can
824 // convert from the source type to the destination type or
825 // (when a conversion function is used) to a derived class
826 // thereof are enumerated as described in 13.3.1.4, and the
827 // best one is chosen through overload resolution
828 // (13.3). If the conversion cannot be done or is
829 // ambiguous, the initialization is ill-formed. The
830 // function selected is called with the initializer
831 // expression as its argument; if the function is a
832 // constructor, the call initializes a temporary of the
833 // destination type.
834 // FIXME: We're pretending to do copy elision here; return to
835 // this when we have ASTs for such things.
Chris Lattner70b93d82008-11-18 22:52:51 +0000836 if (!PerformImplicitConversion(Init, DeclType))
Douglas Gregor6428e762008-11-05 15:29:30 +0000837 return false;
Chris Lattner70b93d82008-11-18 22:52:51 +0000838
839 return Diag(InitLoc, diag::err_typecheck_convert_incompatible)
Chris Lattner271d4c22008-11-24 05:29:24 +0000840 << DeclType << InitEntity << "initializing"
Chris Lattner70b93d82008-11-18 22:52:51 +0000841 << Init->getSourceRange();
Douglas Gregor6428e762008-11-05 15:29:30 +0000842 }
843
Steve Naroffb2f72412008-09-29 20:07:05 +0000844 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +0000845 if (DeclType->isArrayType())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000846 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
847 << Init->getSourceRange();
Eli Friedman65280992008-02-08 00:48:24 +0000848
Steve Narofff0b23542008-01-10 22:15:12 +0000849 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor15e04622008-11-05 16:20:31 +0000850 } else if (getLangOptions().CPlusPlus) {
851 // C++ [dcl.init]p14:
852 // [...] If the class is an aggregate (8.5.1), and the initializer
853 // is a brace-enclosed list, see 8.5.1.
854 //
855 // Note: 8.5.1 is handled below; here, we diagnose the case where
856 // we have an initializer list and a destination type that is not
857 // an aggregate.
858 // FIXME: In C++0x, this is yet another form of initialization.
859 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
860 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
861 if (!ClassDecl->isAggregate())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000862 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000863 << DeclType << Init->getSourceRange();
Douglas Gregor15e04622008-11-05 16:20:31 +0000864 }
Steve Naroffcb69fb72007-12-10 22:44:33 +0000865 }
Eli Friedman38b7a912008-06-06 19:40:52 +0000866
Steve Naroffc4d4a482008-05-01 22:18:59 +0000867 InitListChecker CheckInitList(this, InitList, DeclType);
868 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +0000869}
870
Douglas Gregor6704b312008-11-17 22:58:34 +0000871/// GetNameForDeclarator - Determine the full declaration name for the
872/// given Declarator.
873DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
874 switch (D.getKind()) {
875 case Declarator::DK_Abstract:
876 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
877 return DeclarationName();
878
879 case Declarator::DK_Normal:
880 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
881 return DeclarationName(D.getIdentifier());
882
883 case Declarator::DK_Constructor: {
884 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
885 Ty = Context.getCanonicalType(Ty);
886 return Context.DeclarationNames.getCXXConstructorName(Ty);
887 }
888
889 case Declarator::DK_Destructor: {
890 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
891 Ty = Context.getCanonicalType(Ty);
892 return Context.DeclarationNames.getCXXDestructorName(Ty);
893 }
894
895 case Declarator::DK_Conversion: {
896 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
897 Ty = Context.getCanonicalType(Ty);
898 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
899 }
Douglas Gregor96a32dd2008-11-18 14:39:36 +0000900
901 case Declarator::DK_Operator:
902 assert(D.getIdentifier() == 0 && "operator names have no identifier");
903 return Context.DeclarationNames.getCXXOperatorName(
904 D.getOverloadedOperator());
Douglas Gregor6704b312008-11-17 22:58:34 +0000905 }
906
907 assert(false && "Unknown name kind");
908 return DeclarationName();
909}
910
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000911Sema::DeclTy *
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000912Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000913 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor6704b312008-11-17 22:58:34 +0000914 DeclarationName Name = GetNameForDeclarator(D);
915
Chris Lattner4b009652007-07-25 00:24:17 +0000916 // All of these full declarators require an identifier. If it doesn't have
917 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor6704b312008-11-17 22:58:34 +0000918 if (!Name) {
Chris Lattnercd61d592008-11-11 06:13:16 +0000919 if (!D.getInvalidType()) // Reject this if we think it is valid.
920 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000921 diag::err_declarator_need_ident)
922 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +0000923 return 0;
924 }
925
Chris Lattnera7549902007-08-26 06:24:45 +0000926 // The scope passed in may not be a decl scope. Zip up the scope tree until
927 // we find one that is.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000928 while ((S->getFlags() & Scope::DeclScope) == 0 ||
929 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattnera7549902007-08-26 06:24:45 +0000930 S = S->getParent();
931
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000932 DeclContext *DC;
933 Decl *PrevDecl;
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000934 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000935 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000936
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000937 // See if this is a redefinition of a variable in the same scope.
938 if (!D.getCXXScopeSpec().isSet()) {
939 DC = CurContext;
Douglas Gregor6704b312008-11-17 22:58:34 +0000940 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000941 } else { // Something like "int foo::x;"
942 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor6704b312008-11-17 22:58:34 +0000943 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000944
945 // C++ 7.3.1.2p2:
946 // Members (including explicit specializations of templates) of a named
947 // namespace can also be defined outside that namespace by explicit
948 // qualification of the name being defined, provided that the entity being
949 // defined was already declared in the namespace and the definition appears
950 // after the point of declaration in a namespace that encloses the
951 // declarations namespace.
952 //
Douglas Gregor98341042008-12-12 08:25:50 +0000953 // FIXME: We need to perform this check later, once we know that
954 // we've actually found a redeclaration. Otherwise, just the fact
955 // that there is some entity with the same name will suppress this
956 // diagnostic, e.g., we fail to diagnose:
957 // class X {
958 // void f();
959 // };
960 //
961 // void X::f(int) { } // ill-formed, but we don't complain.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000962 if (PrevDecl == 0) {
963 // No previous declaration in the qualifying scope.
Chris Lattner77d52da2008-11-20 06:06:08 +0000964 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
Chris Lattnerb1753422008-11-23 21:45:46 +0000965 << Name << D.getCXXScopeSpec().getRange();
Douglas Gregor8acb7272008-12-11 16:49:14 +0000966 InvalidDecl = true;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000967 } else if (!CurContext->Encloses(DC)) {
968 // The qualifying scope doesn't enclose the original declaration.
969 // Emit diagnostic based on current scope.
970 SourceLocation L = D.getIdentifierLoc();
971 SourceRange R = D.getCXXScopeSpec().getRange();
972 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner254de7d2008-11-23 20:28:15 +0000973 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000974 } else {
Chris Lattner254de7d2008-11-23 20:28:15 +0000975 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattner271d4c22008-11-24 05:29:24 +0000976 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000977 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000978 InvalidDecl = true;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000979 }
980 }
981
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000982 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +0000983 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000984 InvalidDecl = InvalidDecl
985 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000986 // Just pretend that we didn't see the previous declaration.
987 PrevDecl = 0;
988 }
989
Douglas Gregor1d661552008-04-13 21:07:44 +0000990 // In C++, the previous declaration we find might be a tag type
991 // (class or enum). In this case, the new declaration will hide the
992 // tag type.
993 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
994 PrevDecl = 0;
995
Chris Lattner82bb4792007-11-14 06:34:38 +0000996 QualType R = GetTypeForDeclarator(D, S);
997 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
998
Chris Lattner4b009652007-07-25 00:24:17 +0000999 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001000 // Check that there are no default arguments (C++ only).
1001 if (getLangOptions().CPlusPlus)
1002 CheckExtraCXXDefaultArguments(D);
1003
Chris Lattner82bb4792007-11-14 06:34:38 +00001004 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +00001005 if (!NewTD) return 0;
1006
1007 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +00001008 ProcessDeclAttributes(NewTD, D);
Steve Narofff8a09432008-01-09 23:34:55 +00001009 // Merge the decl with the existing one if appropriate. If the decl is
1010 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001011 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001012 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1013 if (NewTD == 0) return 0;
1014 }
1015 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001016 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001017 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1018 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +00001019 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00001020 if (NewTD->getUnderlyingType()->isVariableArrayType())
1021 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1022 else
1023 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1024
Steve Naroff5eb879b2007-08-31 17:20:07 +00001025 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001026 }
1027 }
Chris Lattner82bb4792007-11-14 06:34:38 +00001028 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +00001029 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +00001030 switch (D.getDeclSpec().getStorageClassSpec()) {
1031 default: assert(0 && "Unknown storage class!");
1032 case DeclSpec::SCS_auto:
1033 case DeclSpec::SCS_register:
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001034 case DeclSpec::SCS_mutable:
Chris Lattner4bfd2232008-11-24 06:25:27 +00001035 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001036 InvalidDecl = true;
1037 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001038 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1039 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1040 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +00001041 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +00001042 }
1043
Chris Lattner4c7802b2008-03-15 21:24:04 +00001044 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001045 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001046 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1047
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001048 FunctionDecl *NewFD;
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001049 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001050 // This is a C++ constructor declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001051 assert(DC->isCXXRecord() &&
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001052 "Constructors can only be declared in a member context");
1053
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001054 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001055
1056 // Create the new declaration
1057 NewFD = CXXConstructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001058 cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001059 D.getIdentifierLoc(), Name, R,
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001060 isExplicit, isInline,
1061 /*isImplicitlyDeclared=*/false);
1062
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001063 if (isInvalidDecl)
1064 NewFD->setInvalidDecl();
1065 } else if (D.getKind() == Declarator::DK_Destructor) {
1066 // This is a C++ destructor declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001067 if (DC->isCXXRecord()) {
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001068 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001069
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001070 NewFD = CXXDestructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001071 cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001072 D.getIdentifierLoc(), Name, R,
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001073 isInline,
1074 /*isImplicitlyDeclared=*/false);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001075
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001076 if (isInvalidDecl)
1077 NewFD->setInvalidDecl();
1078 } else {
1079 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1080 // Create a FunctionDecl to satisfy the function definition parsing
1081 // code path.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001082 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor6704b312008-11-17 22:58:34 +00001083 Name, R, SC, isInline, LastDeclarator,
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001084 // FIXME: Move to DeclGroup...
1085 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001086 NewFD->setInvalidDecl();
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001087 }
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001088 } else if (D.getKind() == Declarator::DK_Conversion) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001089 if (!DC->isCXXRecord()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001090 Diag(D.getIdentifierLoc(),
1091 diag::err_conv_function_not_member);
1092 return 0;
1093 } else {
1094 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
1095
1096 NewFD = CXXConversionDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001097 cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001098 D.getIdentifierLoc(), Name, R,
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001099 isInline, isExplicit);
1100
1101 if (isInvalidDecl)
1102 NewFD->setInvalidDecl();
1103 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001104 } else if (DC->isCXXRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001105 // This is a C++ method declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001106 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001107 D.getIdentifierLoc(), Name, R,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001108 (SC == FunctionDecl::Static), isInline,
1109 LastDeclarator);
1110 } else {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001111 NewFD = FunctionDecl::Create(Context, DC,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001112 D.getIdentifierLoc(),
Douglas Gregor6704b312008-11-17 22:58:34 +00001113 Name, R, SC, isInline, LastDeclarator,
Steve Naroff71cd7762008-10-03 00:02:03 +00001114 // FIXME: Move to DeclGroup...
1115 D.getDeclSpec().getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001116 }
Ted Kremenek117f1862008-02-27 22:18:07 +00001117 // Handle attributes.
Chris Lattner9b384ca2008-06-29 00:02:00 +00001118 ProcessDeclAttributes(NewFD, D);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001119
Daniel Dunbarc3540ff2008-08-05 01:35:17 +00001120 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001121 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +00001122 // The parser guarantees this is a string.
1123 StringLiteral *SE = cast<StringLiteral>(E);
1124 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1125 SE->getByteLength())));
1126 }
1127
Chris Lattner3e254fb2008-04-08 04:40:51 +00001128 // Copy the parameter declarations from the declarator D to
1129 // the function declaration NewFD, if they are available.
Eli Friedman769e7302008-08-25 21:31:01 +00001130 if (D.getNumTypeObjects() > 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001131 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1132
1133 // Create Decl objects for each parameter, adding them to the
1134 // FunctionDecl.
1135 llvm::SmallVector<ParmVarDecl*, 16> Params;
1136
1137 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1138 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +00001139 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +00001140 // We let through "const void" here because Sema::GetTypeForDeclarator
1141 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001142 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1143 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +00001144 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1145 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +00001146 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1147
Chris Lattnerda7b5f02008-04-10 02:26:16 +00001148 // In C++, the empty parameter-type-list must be spelled "void"; a
1149 // typedef of void is not permitted.
1150 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +00001151 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +00001152 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1153 }
Eli Friedman769e7302008-08-25 21:31:01 +00001154 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001155 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1156 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1157 }
1158
1159 NewFD->setParams(&Params[0], Params.size());
Douglas Gregorba3e8b72008-10-24 18:09:54 +00001160 } else if (R->getAsTypedefType()) {
1161 // When we're declaring a function with a typedef, as in the
1162 // following example, we'll need to synthesize (unnamed)
1163 // parameters for use in the declaration.
1164 //
1165 // @code
1166 // typedef void fn(int);
1167 // fn f;
1168 // @endcode
1169 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1170 if (!FT) {
1171 // This is a typedef of a function with no prototype, so we
1172 // don't need to do anything.
1173 } else if ((FT->getNumArgs() == 0) ||
1174 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1175 FT->getArgType(0)->isVoidType())) {
1176 // This is a zero-argument function. We don't need to do anything.
1177 } else {
1178 // Synthesize a parameter for each argument type.
1179 llvm::SmallVector<ParmVarDecl*, 16> Params;
1180 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1181 ArgType != FT->arg_type_end(); ++ArgType) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001182 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregorba3e8b72008-10-24 18:09:54 +00001183 SourceLocation(), 0,
1184 *ArgType, VarDecl::None,
1185 0, 0));
1186 }
1187
1188 NewFD->setParams(&Params[0], Params.size());
1189 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001190 }
1191
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001192 // C++ constructors and destructors are handled by separate
1193 // routines, since they don't require any declaration merging (C++
1194 // [class.mfct]p2) and they aren't ever pushed into scope, because
1195 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1196 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1197 return ActOnConstructorDeclarator(Constructor);
1198 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1199 return ActOnDestructorDeclarator(Destructor);
Douglas Gregorb0212bd2008-11-17 20:34:05 +00001200
1201 // Extra checking for conversion functions, including recording
1202 // the conversion function in its class.
1203 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1204 ActOnConversionDeclarator(Conversion);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001205
Douglas Gregore60e5d32008-11-06 22:13:31 +00001206 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1207 if (NewFD->isOverloadedOperator() &&
1208 CheckOverloadedOperatorDeclaration(NewFD))
1209 NewFD->setInvalidDecl();
1210
Steve Narofff8a09432008-01-09 23:34:55 +00001211 // Merge the decl with the existing one if appropriate. Since C functions
1212 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001213 if (PrevDecl &&
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001214 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregor42214c52008-04-21 02:02:58 +00001215 bool Redeclaration = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001216
1217 // If C++, determine whether NewFD is an overload of PrevDecl or
1218 // a declaration that requires merging. If it's an overload,
1219 // there's no more work to do here; we'll just add the new
1220 // function to the scope.
1221 OverloadedFunctionDecl::function_iterator MatchedDecl;
1222 if (!getLangOptions().CPlusPlus ||
1223 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1224 Decl *OldDecl = PrevDecl;
1225
1226 // If PrevDecl was an overloaded function, extract the
1227 // FunctionDecl that matched.
1228 if (isa<OverloadedFunctionDecl>(PrevDecl))
1229 OldDecl = *MatchedDecl;
1230
1231 // NewFD and PrevDecl represent declarations that need to be
1232 // merged.
1233 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1234
1235 if (NewFD == 0) return 0;
1236 if (Redeclaration) {
1237 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1238
1239 if (OldDecl == PrevDecl) {
1240 // Remove the name binding for the previous
Douglas Gregor8acb7272008-12-11 16:49:14 +00001241 // declaration.
1242 if (S->isDeclScope(PrevDecl)) {
1243 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1244 S->RemoveDecl(PrevDecl);
1245 }
1246
1247 // Introduce the new binding for this declaration.
1248 IdResolver.AddDecl(NewFD);
1249 if (getLangOptions().CPlusPlus && NewFD->getParent())
1250 NewFD->getParent()->insert(Context, NewFD);
1251
1252 // Add the redeclaration to the current scope, since we'll
1253 // be skipping PushOnScopeChains.
1254 S->AddDecl(NewFD);
Douglas Gregord2baafd2008-10-21 16:13:35 +00001255 } else {
1256 // We need to update the OverloadedFunctionDecl with the
1257 // latest declaration of this function, so that name
1258 // lookup will always refer to the latest declaration of
1259 // this function.
1260 *MatchedDecl = NewFD;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001261 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001262
Douglas Gregor8acb7272008-12-11 16:49:14 +00001263 if (getLangOptions().CPlusPlus) {
1264 // Add this declaration to the current context.
1265 CurContext->addDecl(Context, NewFD, false);
Douglas Gregord2baafd2008-10-21 16:13:35 +00001266
Douglas Gregor8acb7272008-12-11 16:49:14 +00001267 // Check default arguments now that we have merged decls.
1268 CheckCXXDefaultArguments(NewFD);
Douglas Gregord2baafd2008-10-21 16:13:35 +00001269 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001270
1271 // Set the lexical context. If the declarator has a C++
1272 // scope specifier, the lexical context will be different
1273 // from the semantic context.
1274 NewFD->setLexicalDeclContext(CurContext);
1275
1276 return NewFD;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001277 }
Douglas Gregor42214c52008-04-21 02:02:58 +00001278 }
Chris Lattner4b009652007-07-25 00:24:17 +00001279 }
1280 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001281
1282 // In C++, check default arguments now that we have merged decls.
1283 if (getLangOptions().CPlusPlus)
1284 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +00001285 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001286 // Check that there are no default arguments (C++ only).
1287 if (getLangOptions().CPlusPlus)
1288 CheckExtraCXXDefaultArguments(D);
1289
Ted Kremenek42730c52008-01-07 19:49:32 +00001290 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner65cae292008-11-19 08:23:25 +00001291 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1292 << D.getIdentifier();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001293 InvalidDecl = true;
1294 }
Chris Lattner4b009652007-07-25 00:24:17 +00001295
1296 VarDecl *NewVD;
1297 VarDecl::StorageClass SC;
1298 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +00001299 default: assert(0 && "Unknown storage class!");
1300 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1301 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1302 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1303 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1304 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1305 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001306 case DeclSpec::SCS_mutable:
1307 // mutable can only appear on non-static class members, so it's always
1308 // an error here
1309 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1310 InvalidDecl = true;
Douglas Gregor538754e2008-12-01 22:46:22 +00001311 SC = VarDecl::None;
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +00001312 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001313 }
Douglas Gregor6704b312008-11-17 22:58:34 +00001314
1315 IdentifierInfo *II = Name.getAsIdentifierInfo();
1316 if (!II) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00001317 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1318 << Name.getAsString();
Douglas Gregor6704b312008-11-17 22:58:34 +00001319 return 0;
1320 }
1321
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001322 if (DC->isCXXRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001323 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1324 // This is a static data member for a C++ class.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001325 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001326 D.getIdentifierLoc(), II,
1327 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +00001328 } else {
Daniel Dunbar5eea5622008-09-08 20:05:47 +00001329 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001330 if (S->getFnParent() == 0) {
1331 // C99 6.9p2: The storage-class specifiers auto and register shall not
1332 // appear in the declaration specifiers in an external declaration.
1333 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattner4bfd2232008-11-24 06:25:27 +00001334 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001335 InvalidDecl = true;
1336 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001337 }
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001338 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1339 II, R, SC, LastDeclarator,
1340 // FIXME: Move to DeclGroup...
1341 D.getDeclSpec().getSourceRange().getBegin());
1342 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroffcae537d2007-08-28 18:45:29 +00001343 }
Chris Lattner4b009652007-07-25 00:24:17 +00001344 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +00001345 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +00001346
Daniel Dunbarced89142008-08-06 00:03:29 +00001347 // Handle GNU asm-label extension (encoded as an attribute).
1348 if (Expr *E = (Expr*) D.getAsmLabel()) {
1349 // The parser guarantees this is a string.
1350 StringLiteral *SE = cast<StringLiteral>(E);
1351 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1352 SE->getByteLength())));
1353 }
1354
Nate Begemanea583262008-03-14 18:07:10 +00001355 // Emit an error if an address space was applied to decl with local storage.
1356 // This includes arrays of objects with address space qualifiers, but not
1357 // automatic variables that point to other address spaces.
1358 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +00001359 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1360 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1361 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +00001362 }
Steve Narofff8a09432008-01-09 23:34:55 +00001363 // Merge the decl with the existing one if appropriate. If the decl is
1364 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001365 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001366 NewVD = MergeVarDecl(NewVD, PrevDecl);
1367 if (NewVD == 0) return 0;
1368 }
Chris Lattner4b009652007-07-25 00:24:17 +00001369 New = NewVD;
1370 }
1371
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001372 // Set the lexical context. If the declarator has a C++ scope specifier, the
1373 // lexical context will be different from the semantic context.
1374 New->setLexicalDeclContext(CurContext);
1375
Chris Lattner4b009652007-07-25 00:24:17 +00001376 // If this has an identifier, add it to the scope stack.
Douglas Gregor6704b312008-11-17 22:58:34 +00001377 if (Name)
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001378 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001379 // If any semantic error occurred, mark the decl as invalid.
1380 if (D.getInvalidType() || InvalidDecl)
1381 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001382
1383 return New;
1384}
1385
Steve Narofffc08f5e2008-10-27 11:34:16 +00001386void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001387 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1388 << Init->getSourceRange();
Steve Narofffc08f5e2008-10-27 11:34:16 +00001389}
1390
Eli Friedman02c22ce2008-05-20 13:48:25 +00001391bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1392 switch (Init->getStmtClass()) {
1393 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001394 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001395 return true;
1396 case Expr::ParenExprClass: {
1397 const ParenExpr* PE = cast<ParenExpr>(Init);
1398 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1399 }
1400 case Expr::CompoundLiteralExprClass:
1401 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1402 case Expr::DeclRefExprClass: {
1403 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001404 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1405 if (VD->hasGlobalStorage())
1406 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001407 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001408 return true;
1409 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001410 if (isa<FunctionDecl>(D))
1411 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001412 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001413 return true;
1414 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001415 case Expr::MemberExprClass: {
1416 const MemberExpr *M = cast<MemberExpr>(Init);
1417 if (M->isArrow())
1418 return CheckAddressConstantExpression(M->getBase());
1419 return CheckAddressConstantExpressionLValue(M->getBase());
1420 }
1421 case Expr::ArraySubscriptExprClass: {
1422 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1423 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1424 return CheckAddressConstantExpression(ASE->getBase()) ||
1425 CheckArithmeticConstantExpression(ASE->getIdx());
1426 }
1427 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001428 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001429 return false;
1430 case Expr::UnaryOperatorClass: {
1431 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1432
1433 // C99 6.6p9
1434 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001435 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001436
Steve Narofffc08f5e2008-10-27 11:34:16 +00001437 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001438 return true;
1439 }
1440 }
1441}
1442
1443bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1444 switch (Init->getStmtClass()) {
1445 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001446 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001447 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001448 case Expr::ParenExprClass:
1449 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001450 case Expr::StringLiteralClass:
1451 case Expr::ObjCStringLiteralClass:
1452 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001453 case Expr::CallExprClass:
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001454 case Expr::CXXOperatorCallExprClass:
Chris Lattner0903cba2008-10-06 07:26:43 +00001455 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1456 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1457 Builtin::BI__builtin___CFStringMakeConstantString)
1458 return false;
1459
Steve Narofffc08f5e2008-10-27 11:34:16 +00001460 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001461 return true;
1462
Eli Friedman02c22ce2008-05-20 13:48:25 +00001463 case Expr::UnaryOperatorClass: {
1464 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1465
1466 // C99 6.6p9
1467 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1468 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1469
1470 if (Exp->getOpcode() == UnaryOperator::Extension)
1471 return CheckAddressConstantExpression(Exp->getSubExpr());
1472
Steve Narofffc08f5e2008-10-27 11:34:16 +00001473 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001474 return true;
1475 }
1476 case Expr::BinaryOperatorClass: {
1477 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1478 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1479
1480 Expr *PExp = Exp->getLHS();
1481 Expr *IExp = Exp->getRHS();
1482 if (IExp->getType()->isPointerType())
1483 std::swap(PExp, IExp);
1484
1485 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1486 return CheckAddressConstantExpression(PExp) ||
1487 CheckArithmeticConstantExpression(IExp);
1488 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001489 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001490 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001491 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001492 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1493 // Check for implicit promotion
1494 if (SubExpr->getType()->isFunctionType() ||
1495 SubExpr->getType()->isArrayType())
1496 return CheckAddressConstantExpressionLValue(SubExpr);
1497 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001498
1499 // Check for pointer->pointer cast
1500 if (SubExpr->getType()->isPointerType())
1501 return CheckAddressConstantExpression(SubExpr);
1502
Eli Friedman1fad3c62008-08-25 20:46:57 +00001503 if (SubExpr->getType()->isIntegralType()) {
1504 // Check for the special-case of a pointer->int->pointer cast;
1505 // this isn't standard, but some code requires it. See
1506 // PR2720 for an example.
1507 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1508 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1509 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1510 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1511 if (IntWidth >= PointerWidth) {
1512 return CheckAddressConstantExpression(SubCast->getSubExpr());
1513 }
1514 }
1515 }
1516 }
1517 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001518 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001519 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001520
Steve Narofffc08f5e2008-10-27 11:34:16 +00001521 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001522 return true;
1523 }
1524 case Expr::ConditionalOperatorClass: {
1525 // FIXME: Should we pedwarn here?
1526 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1527 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001528 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001529 return true;
1530 }
1531 if (CheckArithmeticConstantExpression(Exp->getCond()))
1532 return true;
1533 if (Exp->getLHS() &&
1534 CheckAddressConstantExpression(Exp->getLHS()))
1535 return true;
1536 return CheckAddressConstantExpression(Exp->getRHS());
1537 }
1538 case Expr::AddrLabelExprClass:
1539 return false;
1540 }
1541}
1542
Eli Friedman998dffb2008-06-09 05:05:07 +00001543static const Expr* FindExpressionBaseAddress(const Expr* E);
1544
1545static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1546 switch (E->getStmtClass()) {
1547 default:
1548 return E;
1549 case Expr::ParenExprClass: {
1550 const ParenExpr* PE = cast<ParenExpr>(E);
1551 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1552 }
1553 case Expr::MemberExprClass: {
1554 const MemberExpr *M = cast<MemberExpr>(E);
1555 if (M->isArrow())
1556 return FindExpressionBaseAddress(M->getBase());
1557 return FindExpressionBaseAddressLValue(M->getBase());
1558 }
1559 case Expr::ArraySubscriptExprClass: {
1560 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1561 return FindExpressionBaseAddress(ASE->getBase());
1562 }
1563 case Expr::UnaryOperatorClass: {
1564 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1565
1566 if (Exp->getOpcode() == UnaryOperator::Deref)
1567 return FindExpressionBaseAddress(Exp->getSubExpr());
1568
1569 return E;
1570 }
1571 }
1572}
1573
1574static const Expr* FindExpressionBaseAddress(const Expr* E) {
1575 switch (E->getStmtClass()) {
1576 default:
1577 return E;
1578 case Expr::ParenExprClass: {
1579 const ParenExpr* PE = cast<ParenExpr>(E);
1580 return FindExpressionBaseAddress(PE->getSubExpr());
1581 }
1582 case Expr::UnaryOperatorClass: {
1583 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1584
1585 // C99 6.6p9
1586 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1587 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1588
1589 if (Exp->getOpcode() == UnaryOperator::Extension)
1590 return FindExpressionBaseAddress(Exp->getSubExpr());
1591
1592 return E;
1593 }
1594 case Expr::BinaryOperatorClass: {
1595 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1596
1597 Expr *PExp = Exp->getLHS();
1598 Expr *IExp = Exp->getRHS();
1599 if (IExp->getType()->isPointerType())
1600 std::swap(PExp, IExp);
1601
1602 return FindExpressionBaseAddress(PExp);
1603 }
1604 case Expr::ImplicitCastExprClass: {
1605 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1606
1607 // Check for implicit promotion
1608 if (SubExpr->getType()->isFunctionType() ||
1609 SubExpr->getType()->isArrayType())
1610 return FindExpressionBaseAddressLValue(SubExpr);
1611
1612 // Check for pointer->pointer cast
1613 if (SubExpr->getType()->isPointerType())
1614 return FindExpressionBaseAddress(SubExpr);
1615
1616 // We assume that we have an arithmetic expression here;
1617 // if we don't, we'll figure it out later
1618 return 0;
1619 }
Douglas Gregor035d0882008-10-28 15:36:24 +00001620 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001621 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1622
1623 // Check for pointer->pointer cast
1624 if (SubExpr->getType()->isPointerType())
1625 return FindExpressionBaseAddress(SubExpr);
1626
1627 // We assume that we have an arithmetic expression here;
1628 // if we don't, we'll figure it out later
1629 return 0;
1630 }
1631 }
1632}
1633
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001634bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001635 switch (Init->getStmtClass()) {
1636 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001637 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001638 return true;
1639 case Expr::ParenExprClass: {
1640 const ParenExpr* PE = cast<ParenExpr>(Init);
1641 return CheckArithmeticConstantExpression(PE->getSubExpr());
1642 }
1643 case Expr::FloatingLiteralClass:
1644 case Expr::IntegerLiteralClass:
1645 case Expr::CharacterLiteralClass:
1646 case Expr::ImaginaryLiteralClass:
1647 case Expr::TypesCompatibleExprClass:
1648 case Expr::CXXBoolLiteralExprClass:
1649 return false;
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001650 case Expr::CallExprClass:
1651 case Expr::CXXOperatorCallExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001652 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001653
1654 // Allow any constant foldable calls to builtins.
1655 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001656 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001657
Steve Narofffc08f5e2008-10-27 11:34:16 +00001658 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001659 return true;
1660 }
1661 case Expr::DeclRefExprClass: {
1662 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1663 if (isa<EnumConstantDecl>(D))
1664 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001665 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001666 return true;
1667 }
1668 case Expr::CompoundLiteralExprClass:
1669 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1670 // but vectors are allowed to be magic.
1671 if (Init->getType()->isVectorType())
1672 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001673 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001674 return true;
1675 case Expr::UnaryOperatorClass: {
1676 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1677
1678 switch (Exp->getOpcode()) {
1679 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1680 // See C99 6.6p3.
1681 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001682 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001683 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001684 case UnaryOperator::OffsetOf:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001685 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1686 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001687 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001688 return true;
1689 case UnaryOperator::Extension:
1690 case UnaryOperator::LNot:
1691 case UnaryOperator::Plus:
1692 case UnaryOperator::Minus:
1693 case UnaryOperator::Not:
1694 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1695 }
1696 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001697 case Expr::SizeOfAlignOfExprClass: {
1698 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001699 // Special check for void types, which are allowed as an extension
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001700 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedman02c22ce2008-05-20 13:48:25 +00001701 return false;
1702 // alignof always evaluates to a constant.
1703 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001704 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001705 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001706 return true;
1707 }
1708 return false;
1709 }
1710 case Expr::BinaryOperatorClass: {
1711 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1712
1713 if (Exp->getLHS()->getType()->isArithmeticType() &&
1714 Exp->getRHS()->getType()->isArithmeticType()) {
1715 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1716 CheckArithmeticConstantExpression(Exp->getRHS());
1717 }
1718
Eli Friedman998dffb2008-06-09 05:05:07 +00001719 if (Exp->getLHS()->getType()->isPointerType() &&
1720 Exp->getRHS()->getType()->isPointerType()) {
1721 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1722 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1723
1724 // Only allow a null (constant integer) base; we could
1725 // allow some additional cases if necessary, but this
1726 // is sufficient to cover offsetof-like constructs.
1727 if (!LHSBase && !RHSBase) {
1728 return CheckAddressConstantExpression(Exp->getLHS()) ||
1729 CheckAddressConstantExpression(Exp->getRHS());
1730 }
1731 }
1732
Steve Narofffc08f5e2008-10-27 11:34:16 +00001733 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001734 return true;
1735 }
1736 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001737 case Expr::CStyleCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001738 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00001739 if (SubExpr->getType()->isArithmeticType())
1740 return CheckArithmeticConstantExpression(SubExpr);
1741
Eli Friedman266df142008-09-02 09:37:00 +00001742 if (SubExpr->getType()->isPointerType()) {
1743 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1744 // If the pointer has a null base, this is an offsetof-like construct
1745 if (!Base)
1746 return CheckAddressConstantExpression(SubExpr);
1747 }
1748
Steve Narofffc08f5e2008-10-27 11:34:16 +00001749 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00001750 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001751 }
1752 case Expr::ConditionalOperatorClass: {
1753 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00001754
1755 // If GNU extensions are disabled, we require all operands to be arithmetic
1756 // constant expressions.
1757 if (getLangOptions().NoExtensions) {
1758 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1759 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1760 CheckArithmeticConstantExpression(Exp->getRHS());
1761 }
1762
1763 // Otherwise, we have to emulate some of the behavior of fold here.
1764 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1765 // because it can constant fold things away. To retain compatibility with
1766 // GCC code, we see if we can fold the condition to a constant (which we
1767 // should always be able to do in theory). If so, we only require the
1768 // specified arm of the conditional to be a constant. This is a horrible
1769 // hack, but is require by real world code that uses __builtin_constant_p.
1770 APValue Val;
Chris Lattneref069662008-11-16 21:24:15 +00001771 if (!Exp->getCond()->Evaluate(Val, Context)) {
1772 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner94d45412008-10-06 05:42:39 +00001773 // won't be able to either. Use it to emit the diagnostic though.
1774 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattneref069662008-11-16 21:24:15 +00001775 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner94d45412008-10-06 05:42:39 +00001776 return Res;
1777 }
1778
1779 // Verify that the side following the condition is also a constant.
1780 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1781 if (Val.getInt() == 0)
1782 std::swap(TrueSide, FalseSide);
1783
1784 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001785 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00001786
1787 // Okay, the evaluated side evaluates to a constant, so we accept this.
1788 // Check to see if the other side is obviously not a constant. If so,
1789 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001790 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00001791 Diag(Init->getExprLoc(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00001792 diag::ext_typecheck_expression_not_constant_but_accepted)
1793 << FalseSide->getSourceRange();
Chris Lattner94d45412008-10-06 05:42:39 +00001794 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001795 }
1796 }
1797}
1798
1799bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlssonf6791c62008-12-05 05:09:56 +00001800 Expr::EvalResult Result;
1801
Nuno Lopese7280452008-07-07 16:46:50 +00001802 Init = Init->IgnoreParens();
1803
Anders Carlssonf6791c62008-12-05 05:09:56 +00001804 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
1805 return false;
1806
Eli Friedman02c22ce2008-05-20 13:48:25 +00001807 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1808 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1809 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1810
Nuno Lopese7280452008-07-07 16:46:50 +00001811 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1812 return CheckForConstantInitializer(e->getInitializer(), DclT);
1813
Eli Friedman02c22ce2008-05-20 13:48:25 +00001814 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1815 unsigned numInits = Exp->getNumInits();
1816 for (unsigned i = 0; i < numInits; i++) {
1817 // FIXME: Need to get the type of the declaration for C++,
1818 // because it could be a reference?
1819 if (CheckForConstantInitializer(Exp->getInit(i),
1820 Exp->getInit(i)->getType()))
1821 return true;
1822 }
1823 return false;
1824 }
1825
Anders Carlssonf6791c62008-12-05 05:09:56 +00001826 // FIXME: We can probably remove some of this code below, now that
1827 // Expr::Evaluate is doing the heavy lifting for scalars.
1828
Eli Friedman02c22ce2008-05-20 13:48:25 +00001829 if (Init->isNullPointerConstant(Context))
1830 return false;
1831 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001832 QualType InitTy = Context.getCanonicalType(Init->getType())
1833 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00001834 if (InitTy == Context.BoolTy) {
1835 // Special handling for pointers implicitly cast to bool;
1836 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1837 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1838 Expr* SubE = ICE->getSubExpr();
1839 if (SubE->getType()->isPointerType() ||
1840 SubE->getType()->isArrayType() ||
1841 SubE->getType()->isFunctionType()) {
1842 return CheckAddressConstantExpression(Init);
1843 }
1844 }
1845 } else if (InitTy->isIntegralType()) {
1846 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001847 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00001848 SubE = CE->getSubExpr();
1849 // Special check for pointer cast to int; we allow as an extension
1850 // an address constant cast to an integer if the integer
1851 // is of an appropriate width (this sort of code is apparently used
1852 // in some places).
1853 // FIXME: Add pedwarn?
1854 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1855 if (SubE && (SubE->getType()->isPointerType() ||
1856 SubE->getType()->isArrayType() ||
1857 SubE->getType()->isFunctionType())) {
1858 unsigned IntWidth = Context.getTypeSize(Init->getType());
1859 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1860 if (IntWidth >= PointerWidth)
1861 return CheckAddressConstantExpression(Init);
1862 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001863 }
1864
1865 return CheckArithmeticConstantExpression(Init);
1866 }
1867
1868 if (Init->getType()->isPointerType())
1869 return CheckAddressConstantExpression(Init);
1870
Eli Friedman25086f02008-05-30 18:14:48 +00001871 // An array type at the top level that isn't an init-list must
1872 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00001873 if (Init->getType()->isArrayType())
1874 return false;
1875
Nuno Lopes1dc26762008-09-01 18:42:41 +00001876 if (Init->getType()->isFunctionType())
1877 return false;
1878
Steve Naroffdff3fb22008-10-02 17:12:56 +00001879 // Allow block exprs at top level.
1880 if (Init->getType()->isBlockPointerType())
1881 return false;
1882
Steve Narofffc08f5e2008-10-27 11:34:16 +00001883 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001884 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00001885}
1886
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00001887void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001888 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00001889 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001890 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001891
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001892 // If there is no declaration, there was an error parsing it. Just ignore
1893 // the initializer.
1894 if (RealDecl == 0) {
1895 delete Init;
1896 return;
1897 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001898
Steve Naroff420d0f52007-09-12 20:13:48 +00001899 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1900 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001901 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1902 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001903 RealDecl->setInvalidDecl();
1904 return;
1905 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001906 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001907 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001908 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001909 if (VDecl->isBlockVarDecl()) {
1910 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001911 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001912 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001913 VDecl->setInvalidDecl();
1914 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001915 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00001916 VDecl->getDeclName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001917 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00001918
1919 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1920 if (!getLangOptions().CPlusPlus) {
1921 if (SC == VarDecl::Static) // C99 6.7.8p4.
1922 CheckForConstantInitializer(Init, DclT);
1923 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001924 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001925 } else if (VDecl->isFileVarDecl()) {
1926 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001927 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001928 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00001929 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00001930 VDecl->getDeclName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001931 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001932
Anders Carlssonea7140a2008-08-22 05:00:02 +00001933 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1934 if (!getLangOptions().CPlusPlus) {
1935 // C99 6.7.8p4. All file scoped initializers need to be constant.
1936 CheckForConstantInitializer(Init, DclT);
1937 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001938 }
1939 // If the type changed, it means we had an incomplete type that was
1940 // completed by the initializer. For example:
1941 // int ary[] = { 1, 3, 5 };
1942 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001943 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001944 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001945 Init->setType(DclT);
1946 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001947
1948 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001949 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001950 return;
1951}
1952
Douglas Gregor81c29152008-10-29 00:13:59 +00001953void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1954 Decl *RealDecl = static_cast<Decl *>(dcl);
1955
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00001956 // If there is no declaration, there was an error parsing it. Just ignore it.
1957 if (RealDecl == 0)
1958 return;
1959
Douglas Gregor81c29152008-10-29 00:13:59 +00001960 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1961 QualType Type = Var->getType();
1962 // C++ [dcl.init.ref]p3:
1963 // The initializer can be omitted for a reference only in a
1964 // parameter declaration (8.3.5), in the declaration of a
1965 // function return type, in the declaration of a class member
1966 // within its class declaration (9.2), and where the extern
1967 // specifier is explicitly used.
Douglas Gregor5870a952008-11-03 20:45:27 +00001968 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Chris Lattner77d52da2008-11-20 06:06:08 +00001969 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattner271d4c22008-11-24 05:29:24 +00001970 << Var->getDeclName()
1971 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor5870a952008-11-03 20:45:27 +00001972 Var->setInvalidDecl();
1973 return;
1974 }
1975
1976 // C++ [dcl.init]p9:
1977 //
1978 // If no initializer is specified for an object, and the object
1979 // is of (possibly cv-qualified) non-POD class type (or array
1980 // thereof), the object shall be default-initialized; if the
1981 // object is of const-qualified type, the underlying class type
1982 // shall have a user-declared default constructor.
1983 if (getLangOptions().CPlusPlus) {
1984 QualType InitType = Type;
1985 if (const ArrayType *Array = Context.getAsArrayType(Type))
1986 InitType = Array->getElementType();
1987 if (InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001988 const CXXConstructorDecl *Constructor
1989 = PerformInitializationByConstructor(InitType, 0, 0,
1990 Var->getLocation(),
1991 SourceRange(Var->getLocation(),
1992 Var->getLocation()),
Chris Lattner271d4c22008-11-24 05:29:24 +00001993 Var->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00001994 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00001995 if (!Constructor)
1996 Var->setInvalidDecl();
1997 }
1998 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001999
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002000#if 0
2001 // FIXME: Temporarily disabled because we are not properly parsing
2002 // linkage specifications on declarations, e.g.,
2003 //
2004 // extern "C" const CGPoint CGPointerZero;
2005 //
Douglas Gregor81c29152008-10-29 00:13:59 +00002006 // C++ [dcl.init]p9:
2007 //
2008 // If no initializer is specified for an object, and the
2009 // object is of (possibly cv-qualified) non-POD class type (or
2010 // array thereof), the object shall be default-initialized; if
2011 // the object is of const-qualified type, the underlying class
2012 // type shall have a user-declared default
2013 // constructor. Otherwise, if no initializer is specified for
2014 // an object, the object and its subobjects, if any, have an
2015 // indeterminate initial value; if the object or any of its
2016 // subobjects are of const-qualified type, the program is
2017 // ill-formed.
2018 //
2019 // This isn't technically an error in C, so we don't diagnose it.
2020 //
2021 // FIXME: Actually perform the POD/user-defined default
2022 // constructor check.
2023 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002024 Context.getCanonicalType(Type).isConstQualified() &&
2025 Var->getStorageClass() != VarDecl::Extern)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002026 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2027 << Var->getName()
2028 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002029#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00002030 }
2031}
2032
Chris Lattner4b009652007-07-25 00:24:17 +00002033/// The declarators are chained together backwards, reverse the list.
2034Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2035 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002036 Decl *GroupDecl = static_cast<Decl*>(group);
2037 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00002038 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00002039
2040 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2041 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002042 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00002043 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002044 else { // reverse the list.
2045 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00002046 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002047 Group->setNextDeclarator(NewGroup);
2048 NewGroup = Group;
2049 Group = Next;
2050 }
2051 }
2052 // Perform semantic analysis that depends on having fully processed both
2053 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002054 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00002055 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2056 if (!IDecl)
2057 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002058 QualType T = IDecl->getType();
2059
Anders Carlsson68adbd12008-12-07 00:20:55 +00002060 if (T->isVariableArrayType()) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002061 const VariableArrayType *VAT =
2062 cast<VariableArrayType>(T.getUnqualifiedType());
2063
2064 // FIXME: This won't give the correct result for
2065 // int a[10][n];
2066 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002067 if (IDecl->isFileVarDecl()) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002068 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2069 SizeRange;
2070
Eli Friedman8ff07782008-02-15 18:16:39 +00002071 IDecl->setInvalidDecl();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002072 } else {
2073 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2074 // static storage duration, it shall not have a variable length array.
2075 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002076 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2077 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002078 IDecl->setInvalidDecl();
2079 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002080 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2081 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002082 IDecl->setInvalidDecl();
2083 }
2084 }
2085 } else if (T->isVariablyModifiedType()) {
2086 if (IDecl->isFileVarDecl()) {
2087 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2088 IDecl->setInvalidDecl();
2089 } else {
2090 if (IDecl->getStorageClass() == VarDecl::Extern) {
2091 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2092 IDecl->setInvalidDecl();
2093 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002094 }
2095 }
Anders Carlsson68adbd12008-12-07 00:20:55 +00002096
Steve Naroff6a0e2092007-09-12 14:07:44 +00002097 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2098 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002099 if (IDecl->isBlockVarDecl() &&
2100 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00002101 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner271d4c22008-11-24 05:29:24 +00002102 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002103 IDecl->setInvalidDecl();
2104 }
2105 }
2106 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2107 // object that has file scope without an initializer, and without a
2108 // storage-class specifier or with the storage-class specifier "static",
2109 // constitutes a tentative definition. Note: A tentative definition with
2110 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00002111 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00002112 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00002113 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2114 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00002115 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00002116 // C99 6.9.2p3: If the declaration of an identifier for an object is
2117 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2118 // declared type shall not be an incomplete type.
Chris Lattner271d4c22008-11-24 05:29:24 +00002119 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002120 IDecl->setInvalidDecl();
2121 }
2122 }
Steve Naroffb5e78152008-08-08 17:50:35 +00002123 if (IDecl->isFileVarDecl())
2124 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002125 }
2126 return NewGroup;
2127}
Steve Naroff91b03f72007-08-28 03:03:08 +00002128
Chris Lattner3e254fb2008-04-08 04:40:51 +00002129/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2130/// to introduce parameters into function prototype scope.
2131Sema::DeclTy *
2132Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002133 // FIXME: disallow CXXScopeSpec for param declarators.
Chris Lattner5e77ade2008-06-26 06:49:43 +00002134 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002135
2136 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002137 VarDecl::StorageClass StorageClass = VarDecl::None;
2138 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2139 StorageClass = VarDecl::Register;
2140 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002141 Diag(DS.getStorageClassSpecLoc(),
2142 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002143 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002144 }
2145 if (DS.isThreadSpecified()) {
2146 Diag(DS.getThreadSpecLoc(),
2147 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002148 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002149 }
2150
Douglas Gregor2b9422f2008-05-07 04:49:29 +00002151 // Check that there are no default arguments inside the type of this
2152 // parameter (C++ only).
2153 if (getLangOptions().CPlusPlus)
2154 CheckExtraCXXDefaultArguments(D);
2155
Chris Lattner3e254fb2008-04-08 04:40:51 +00002156 // In this context, we *do not* check D.getInvalidType(). If the declarator
2157 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2158 // though it will not reflect the user specified type.
2159 QualType parmDeclType = GetTypeForDeclarator(D, S);
2160
2161 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2162
Chris Lattner4b009652007-07-25 00:24:17 +00002163 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2164 // Can this happen for params? We already checked that they don't conflict
2165 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002166 IdentifierInfo *II = D.getIdentifier();
2167 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002168 if (PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002169 // Maybe we will complain about the shadowed template parameter.
2170 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2171 // Just pretend that we didn't see the previous declaration.
2172 PrevDecl = 0;
2173 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002174 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002175
2176 // Recover by removing the name
2177 II = 0;
2178 D.SetIdentifier(0, D.getIdentifierLoc());
2179 }
Chris Lattner4b009652007-07-25 00:24:17 +00002180 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00002181
2182 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2183 // Doing the promotion here has a win and a loss. The win is the type for
2184 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2185 // code generator). The loss is the orginal type isn't preserved. For example:
2186 //
2187 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2188 // int blockvardecl[5];
2189 // sizeof(parmvardecl); // size == 4
2190 // sizeof(blockvardecl); // size == 20
2191 // }
2192 //
2193 // For expressions, all implicit conversions are captured using the
2194 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2195 //
2196 // FIXME: If a source translation tool needs to see the original type, then
2197 // we need to consider storing both types (in ParmVarDecl)...
2198 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00002199 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00002200 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00002201 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00002202 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00002203 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002204
Chris Lattner3e254fb2008-04-08 04:40:51 +00002205 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2206 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002207 parmDeclType, StorageClass,
Chris Lattner3e254fb2008-04-08 04:40:51 +00002208 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00002209
Chris Lattner3e254fb2008-04-08 04:40:51 +00002210 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00002211 New->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002212
2213 // Add the parameter declaration into this scope.
2214 S->AddDecl(New);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002215 if (II)
Douglas Gregor8acb7272008-12-11 16:49:14 +00002216 IdResolver.AddDecl(New);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00002217
Chris Lattner9b384ca2008-06-29 00:02:00 +00002218 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00002219 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002220
Chris Lattner4b009652007-07-25 00:24:17 +00002221}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00002222
Chris Lattnerea148702007-10-09 17:14:05 +00002223Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002224 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00002225 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2226 "Not a function declarator!");
2227 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002228
Chris Lattner4b009652007-07-25 00:24:17 +00002229 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2230 // for a K&R function.
2231 if (!FTI.hasPrototype) {
2232 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002233 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002234 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2235 << FTI.ArgInfo[i].Ident;
Chris Lattner4b009652007-07-25 00:24:17 +00002236 // Implicitly declare the argument as type 'int' for lack of a better
2237 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002238 DeclSpec DS;
2239 const char* PrevSpec; // unused
2240 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2241 PrevSpec);
2242 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2243 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2244 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00002245 }
2246 }
Chris Lattner4b009652007-07-25 00:24:17 +00002247 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002248 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00002249 }
2250
2251 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00002252
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002253 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002254 ActOnDeclarator(GlobalScope, D, 0));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002255}
2256
2257Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2258 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002259 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002260
2261 // See if this is a redefinition.
2262 const FunctionDecl *Definition;
2263 if (FD->getBody(Definition)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002264 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00002265 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor56da7862008-10-29 15:10:40 +00002266 }
2267
Douglas Gregor8acb7272008-12-11 16:49:14 +00002268 PushDeclContext(FnBodyScope, FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00002269
2270 // Check the validity of our function parameters
2271 CheckParmsForFunctionDef(FD);
2272
2273 // Introduce our parameters into the function scope
2274 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2275 ParmVarDecl *Param = FD->getParamDecl(p);
2276 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002277 if (Param->getIdentifier())
2278 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002279 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002280
Chris Lattner4b009652007-07-25 00:24:17 +00002281 return FD;
2282}
2283
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002284Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002285 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002286 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff3ac43f92008-07-25 17:57:26 +00002287 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002288 FD->setBody(Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002289 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002290 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002291 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002292 } else
2293 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002294 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002295 // Verify and clean out per-function state.
2296
2297 // Check goto/label use.
2298 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2299 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2300 // Verify that we have no forward references left. If so, there was a goto
2301 // or address of a label taken, but no definition of it. Label fwd
2302 // definitions are indicated with a null substmt.
2303 if (I->second->getSubStmt() == 0) {
2304 LabelStmt *L = I->second;
2305 // Emit error.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002306 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Chris Lattner4b009652007-07-25 00:24:17 +00002307
2308 // At this point, we have gotos that use the bogus label. Stitch it into
2309 // the function body so that they aren't leaked and that the AST is well
2310 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002311 if (Body) {
2312 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002313 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner83343342008-01-25 00:01:10 +00002314 } else {
2315 // The whole function wasn't parsed correctly, just delete this.
2316 delete L;
2317 }
Chris Lattner4b009652007-07-25 00:24:17 +00002318 }
2319 }
2320 LabelMap.clear();
2321
Steve Naroff99ee4302007-11-11 23:20:51 +00002322 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002323}
2324
Chris Lattner4b009652007-07-25 00:24:17 +00002325/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2326/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00002327ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2328 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002329 // Extension in C99. Legal in C90, but warn about it.
2330 if (getLangOptions().C99)
Chris Lattner65cae292008-11-19 08:23:25 +00002331 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002332 else
Chris Lattner65cae292008-11-19 08:23:25 +00002333 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Chris Lattner4b009652007-07-25 00:24:17 +00002334
2335 // FIXME: handle stuff like:
2336 // void foo() { extern float X(); }
2337 // void bar() { X(); } <-- implicit decl for X in another scope.
2338
2339 // Set a Declarator for the implicit definition: int foo();
2340 const char *Dummy;
2341 DeclSpec DS;
2342 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2343 Error = Error; // Silence warning.
2344 assert(!Error && "Error setting up implicit decl!");
2345 Declarator D(DS, Declarator::BlockContext);
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00002346 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Chris Lattner4b009652007-07-25 00:24:17 +00002347 D.SetIdentifier(&II, Loc);
2348
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002349 // Insert this function into translation-unit scope.
2350
2351 DeclContext *PrevDC = CurContext;
2352 CurContext = Context.getTranslationUnitDecl();
2353
Steve Naroff9104f3c2008-04-04 14:32:09 +00002354 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002355 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002356 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002357
2358 CurContext = PrevDC;
2359
Steve Naroff9104f3c2008-04-04 14:32:09 +00002360 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002361}
2362
2363
Chris Lattner82bb4792007-11-14 06:34:38 +00002364TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00002365 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002366 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002367 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002368
2369 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002370 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2371 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002372 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00002373 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002374 if (D.getInvalidType())
2375 NewTD->setInvalidDecl();
2376 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002377}
2378
Steve Naroff0acc9c92007-09-15 18:49:24 +00002379/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002380/// former case, Name will be non-null. In the later case, Name will be null.
2381/// TagType indicates what kind of tag this is. TK indicates whether this is a
2382/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002383Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002384 SourceLocation KWLoc, const CXXScopeSpec &SS,
2385 IdentifierInfo *Name, SourceLocation NameLoc,
2386 AttributeList *Attr) {
Douglas Gregorae644892008-12-15 16:32:14 +00002387 // If this is not a definition, it must have a name.
Chris Lattner4b009652007-07-25 00:24:17 +00002388 assert((Name != 0 || TK == TK_Definition) &&
2389 "Nameless record must be a definition!");
2390
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002391 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00002392 switch (TagType) {
2393 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002394 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2395 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2396 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2397 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002398 }
2399
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002400 DeclContext *DC = CurContext;
2401 ScopedDecl *PrevDecl = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002402
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002403 if (Name && SS.isNotEmpty()) {
2404 // We have a nested-name tag ('struct foo::bar').
2405
2406 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002407 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002408 Name = 0;
2409 goto CreateNewDecl;
2410 }
2411
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002412 DC = static_cast<DeclContext*>(SS.getScopeRep());
2413 // Look-up name inside 'foo::'.
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002414 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2415
2416 // A tag 'foo::bar' must already exist.
2417 if (PrevDecl == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002418 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002419 Name = 0;
2420 goto CreateNewDecl;
2421 }
2422 } else {
2423 // If this is a named struct, check to see if there was a previous forward
2424 // declaration or definition.
2425 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2426 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2427 }
2428
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002429 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002430 // Maybe we will complain about the shadowed template parameter.
2431 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2432 // Just pretend that we didn't see the previous declaration.
2433 PrevDecl = 0;
2434 }
2435
Ted Kremenekd4434152008-09-02 21:26:19 +00002436 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002437 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2438 "unexpected Decl type");
2439 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002440 // If this is a use of a previous tag, or if the tag is already declared
2441 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002442 // rementions the tag), reuse the decl.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002443 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002444 // Make sure that this wasn't declared as an enum and now used as a
2445 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002446 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner65cae292008-11-19 08:23:25 +00002447 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002448 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002449 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002450 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002451 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002452 } else {
Douglas Gregorae644892008-12-15 16:32:14 +00002453 // If this is a use, just return the declaration we found.
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002454
Douglas Gregorae644892008-12-15 16:32:14 +00002455 // FIXME: In the future, return a variant or some other clue
2456 // for the consumer of this Decl to know it doesn't own it.
2457 // For our current ASTs this shouldn't be a problem, but will
2458 // need to be changed with DeclGroups.
2459 if (TK == TK_Reference)
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002460 return PrevDecl;
Douglas Gregorae644892008-12-15 16:32:14 +00002461
2462 // Diagnose attempts to redefine a tag.
2463 if (TK == TK_Definition) {
2464 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2465 Diag(NameLoc, diag::err_redefinition) << Name;
2466 Diag(Def->getLocation(), diag::note_previous_definition);
2467 // If this is a redefinition, recover by making this struct be
2468 // anonymous, which will make any later references get the previous
2469 // definition.
2470 Name = 0;
2471 PrevDecl = 0;
2472 }
2473 // Okay, this is definition of a previously declared or referenced
2474 // tag PrevDecl. We're going to create a new Decl for it.
2475 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002476 }
Douglas Gregorae644892008-12-15 16:32:14 +00002477 // If we get here we have (another) forward declaration or we
2478 // have a definition. Just create a new decl.
2479 } else {
2480 // If we get here, this is a definition of a new tag type in a nested
2481 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2482 // new decl/type. We set PrevDecl to NULL so that the entities
2483 // have distinct types.
2484 PrevDecl = 0;
Chris Lattner4b009652007-07-25 00:24:17 +00002485 }
Douglas Gregorae644892008-12-15 16:32:14 +00002486 // If we get here, we're going to create a new Decl. If PrevDecl
2487 // is non-NULL, it's a definition of the tag declared by
2488 // PrevDecl. If it's NULL, we have a new definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002489 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002490 // PrevDecl is a namespace.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002491 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002492 // The tag name clashes with a namespace name, issue an error and
2493 // recover by making this tag be anonymous.
Chris Lattner65cae292008-11-19 08:23:25 +00002494 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002495 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002496 Name = 0;
Douglas Gregorae644892008-12-15 16:32:14 +00002497 PrevDecl = 0;
2498 } else {
2499 // The existing declaration isn't relevant to us; we're in a
2500 // new scope, so clear out the previous declaration.
2501 PrevDecl = 0;
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002502 }
Chris Lattner4b009652007-07-25 00:24:17 +00002503 }
Chris Lattner4b009652007-07-25 00:24:17 +00002504 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002505
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002506 CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00002507
2508 // If there is an identifier, use the location of the identifier as the
2509 // location of the decl, otherwise use the location of the struct/union
2510 // keyword.
2511 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2512
Douglas Gregorae644892008-12-15 16:32:14 +00002513 // Otherwise, create a new declaration. If there is a previous
2514 // declaration of the same entity, the two will be linked via
2515 // PrevDecl.
Chris Lattner4b009652007-07-25 00:24:17 +00002516 TagDecl *New;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002517 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00002518 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2519 // enum X { A, B, C } D; D should chain to X.
Douglas Gregorae644892008-12-15 16:32:14 +00002520 New = EnumDecl::Create(Context, DC, Loc, Name,
2521 cast_or_null<EnumDecl>(PrevDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002522 // If this is an undefined enum, warn.
2523 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002524 } else {
2525 // struct/union/class
2526
Chris Lattner4b009652007-07-25 00:24:17 +00002527 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2528 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002529 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002530 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregorae644892008-12-15 16:32:14 +00002531 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2532 cast_or_null<CXXRecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002533 else
Douglas Gregorae644892008-12-15 16:32:14 +00002534 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2535 cast_or_null<RecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002536 }
Douglas Gregorae644892008-12-15 16:32:14 +00002537
2538 if (Kind != TagDecl::TK_enum) {
2539 // Handle #pragma pack: if the #pragma pack stack has non-default
2540 // alignment, make up a packed attribute for this decl. These
2541 // attributes are checked when the ASTContext lays out the
2542 // structure.
2543 //
2544 // It is important for implementing the correct semantics that this
2545 // happen here (in act on tag decl). The #pragma pack stack is
2546 // maintained as a result of parser callbacks which can occur at
2547 // many points during the parsing of a struct declaration (because
2548 // the #pragma tokens are effectively skipped over during the
2549 // parsing of the struct).
2550 if (unsigned Alignment = PackContext.getAlignment())
2551 New->addAttr(new PackedAttr(Alignment * 8));
2552 }
2553
2554 if (Attr)
2555 ProcessDeclAttributeList(New, Attr);
2556
2557 // Set the lexical context. If the tag has a C++ scope specifier, the
2558 // lexical context will be different from the semantic context.
2559 New->setLexicalDeclContext(CurContext);
Chris Lattner4b009652007-07-25 00:24:17 +00002560
2561 // If this has an identifier, add it to the scope stack.
2562 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00002563 // The scope passed in may not be a decl scope. Zip up the scope tree until
2564 // we find one that is.
2565 while ((S->getFlags() & Scope::DeclScope) == 0)
2566 S = S->getParent();
2567
2568 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002569 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002570 }
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00002571
Chris Lattner4b009652007-07-25 00:24:17 +00002572 return New;
2573}
2574
Chris Lattner1bf58f62008-06-21 19:39:06 +00002575/// Collect the instance variables declared in an Objective-C object. Used in
2576/// the creation of structures from objects using the @defs directive.
Fariborz Jahanian138f7bb2008-12-15 18:04:20 +00002577/// FIXME: This should be consolidated with CollectObjCIvars as it is also
2578/// part of the AST generation logic of @defs.
Douglas Gregor8acb7272008-12-11 16:49:14 +00002579static void CollectIvars(ObjCInterfaceDecl *Class, RecordDecl *Record,
2580 ASTContext& Ctx,
Chris Lattnere705e5e2008-07-21 22:17:28 +00002581 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00002582 if (Class->getSuperClass())
Douglas Gregor8acb7272008-12-11 16:49:14 +00002583 CollectIvars(Class->getSuperClass(), Record, Ctx, ivars);
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002584
2585 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremenek40e70e72008-09-03 18:03:35 +00002586 for (ObjCInterfaceDecl::ivar_iterator
2587 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2588
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002589 ObjCIvarDecl* ID = *I;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002590 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, Record,
2591 ID->getLocation(),
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002592 ID->getIdentifier(),
2593 ID->getType(),
2594 ID->getBitWidth()));
2595 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002596}
2597
2598/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2599/// instance variables of ClassName into Decls.
Douglas Gregor8acb7272008-12-11 16:49:14 +00002600void Sema::ActOnDefs(Scope *S, DeclTy *TagD, SourceLocation DeclStart,
Chris Lattner1bf58f62008-06-21 19:39:06 +00002601 IdentifierInfo *ClassName,
Chris Lattnere705e5e2008-07-21 22:17:28 +00002602 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00002603 // Check that ClassName is a valid class
2604 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2605 if (!Class) {
Chris Lattner65cae292008-11-19 08:23:25 +00002606 Diag(DeclStart, diag::err_undef_interface) << ClassName;
Chris Lattner1bf58f62008-06-21 19:39:06 +00002607 return;
2608 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002609 // Collect the instance variables
Douglas Gregor8acb7272008-12-11 16:49:14 +00002610 CollectIvars(Class, dyn_cast<RecordDecl>((Decl*)TagD), Context, Decls);
2611
2612 // Introduce all of these fields into the appropriate scope.
2613 for (llvm::SmallVectorImpl<DeclTy*>::iterator D = Decls.begin();
2614 D != Decls.end(); ++D) {
2615 FieldDecl *FD = cast<FieldDecl>((Decl*)*D);
2616 if (getLangOptions().CPlusPlus)
2617 PushOnScopeChains(cast<FieldDecl>(FD), S);
2618 else if (RecordDecl *Record = dyn_cast<RecordDecl>((Decl*)TagD))
2619 Record->addDecl(Context, FD);
2620 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002621}
2622
Chris Lattnera73e2202008-11-12 21:17:48 +00002623/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2624/// types into constant array types in certain situations which would otherwise
2625/// be errors (for GCC compatibility).
2626static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2627 ASTContext &Context) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002628 // This method tries to turn a variable array into a constant
2629 // array even when the size isn't an ICE. This is necessary
2630 // for compatibility with code that depends on gcc's buggy
2631 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002632 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2633 if (!VLATy) return QualType();
2634
2635 APValue Result;
2636 if (!VLATy->getSizeExpr() ||
Chris Lattneref069662008-11-16 21:24:15 +00002637 !VLATy->getSizeExpr()->Evaluate(Result, Context))
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002638 return QualType();
2639
2640 assert(Result.isInt() && "Size expressions must be integers!");
2641 llvm::APSInt &Res = Result.getInt();
2642 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2643 return Context.getConstantArrayType(VLATy->getElementType(),
2644 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002645 return QualType();
2646}
2647
Anders Carlsson108229a2008-12-06 20:33:04 +00002648bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattner8464c372008-12-12 04:56:04 +00002649 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson108229a2008-12-06 20:33:04 +00002650 // FIXME: 6.7.2.1p4 - verify the field type.
2651
2652 llvm::APSInt Value;
2653 if (VerifyIntegerConstantExpression(BitWidth, &Value))
2654 return true;
2655
Chris Lattner8464c372008-12-12 04:56:04 +00002656 // Zero-width bitfield is ok for anonymous field.
2657 if (Value == 0 && FieldName)
2658 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
2659
2660 if (Value.isNegative())
2661 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson108229a2008-12-06 20:33:04 +00002662
2663 uint64_t TypeSize = Context.getTypeSize(FieldTy);
2664 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattner8464c372008-12-12 04:56:04 +00002665 if (TypeSize && Value.getZExtValue() > TypeSize)
2666 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
2667 << FieldName << (unsigned)TypeSize;
Anders Carlsson108229a2008-12-06 20:33:04 +00002668
2669 return false;
2670}
2671
Steve Naroff0acc9c92007-09-15 18:49:24 +00002672/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00002673/// to create a FieldDecl object for it.
Douglas Gregor8acb7272008-12-11 16:49:14 +00002674Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Chris Lattner4b009652007-07-25 00:24:17 +00002675 SourceLocation DeclStart,
2676 Declarator &D, ExprTy *BitfieldWidth) {
2677 IdentifierInfo *II = D.getIdentifier();
2678 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00002679 SourceLocation Loc = DeclStart;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002680 RecordDecl *Record = (RecordDecl *)TagD;
Chris Lattner4b009652007-07-25 00:24:17 +00002681 if (II) Loc = D.getIdentifierLoc();
2682
2683 // FIXME: Unnamed fields can be handled in various different ways, for
2684 // example, unnamed unions inject all members into the struct namespace!
Chris Lattner4b009652007-07-25 00:24:17 +00002685
Chris Lattner4b009652007-07-25 00:24:17 +00002686 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002687 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2688 bool InvalidDecl = false;
Anders Carlsson108229a2008-12-06 20:33:04 +00002689
Chris Lattner4b009652007-07-25 00:24:17 +00002690 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2691 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00002692 if (T->isVariablyModifiedType()) {
Chris Lattnera73e2202008-11-12 21:17:48 +00002693 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002694 if (!FixedTy.isNull()) {
Chris Lattner86be8572008-11-13 18:49:38 +00002695 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002696 T = FixedTy;
2697 } else {
Chris Lattner86be8572008-11-13 18:49:38 +00002698 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner2a884752008-11-12 19:45:49 +00002699 T = Context.IntTy;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002700 InvalidDecl = true;
2701 }
Chris Lattner4b009652007-07-25 00:24:17 +00002702 }
Anders Carlsson108229a2008-12-06 20:33:04 +00002703
2704 if (BitWidth) {
2705 if (VerifyBitField(Loc, II, T, BitWidth))
2706 InvalidDecl = true;
2707 } else {
2708 // Not a bitfield.
2709
2710 // validate II.
2711
2712 }
2713
Chris Lattner4b009652007-07-25 00:24:17 +00002714 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002715 FieldDecl *NewFD;
2716
Douglas Gregor8acb7272008-12-11 16:49:14 +00002717 // FIXME: We don't want CurContext for C, do we? No, we'll need some
2718 // other way to determine the current RecordDecl.
2719 NewFD = FieldDecl::Create(Context, Record,
2720 Loc, II, T, BitWidth,
2721 D.getDeclSpec().getStorageClassSpec() ==
2722 DeclSpec::SCS_mutable,
2723 /*PrevDecl=*/0);
2724
Chris Lattner9b384ca2008-06-29 00:02:00 +00002725 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002726
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002727 if (D.getInvalidType() || InvalidDecl)
2728 NewFD->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002729
2730 if (II && getLangOptions().CPlusPlus)
2731 PushOnScopeChains(NewFD, S);
2732 else
2733 Record->addDecl(Context, NewFD);
2734
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002735 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00002736}
2737
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002738/// TranslateIvarVisibility - Translate visibility from a token ID to an
2739/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00002740static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002741TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00002742 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00002743 default: assert(0 && "Unknown visitibility kind");
2744 case tok::objc_private: return ObjCIvarDecl::Private;
2745 case tok::objc_public: return ObjCIvarDecl::Public;
2746 case tok::objc_protected: return ObjCIvarDecl::Protected;
2747 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00002748 }
2749}
2750
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002751/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2752/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002753Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002754 SourceLocation DeclStart,
2755 Declarator &D, ExprTy *BitfieldWidth,
2756 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002757 IdentifierInfo *II = D.getIdentifier();
2758 Expr *BitWidth = (Expr*)BitfieldWidth;
2759 SourceLocation Loc = DeclStart;
2760 if (II) Loc = D.getIdentifierLoc();
2761
2762 // FIXME: Unnamed fields can be handled in various different ways, for
2763 // example, unnamed unions inject all members into the struct namespace!
2764
Anders Carlsson108229a2008-12-06 20:33:04 +00002765 QualType T = GetTypeForDeclarator(D, S);
2766 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2767 bool InvalidDecl = false;
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002768
2769 if (BitWidth) {
2770 // TODO: Validate.
2771 //printf("WARNING: BITFIELDS IGNORED!\n");
2772
2773 // 6.7.2.1p3
2774 // 6.7.2.1p4
2775
2776 } else {
2777 // Not a bitfield.
2778
2779 // validate II.
2780
2781 }
2782
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002783 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2784 // than a variably modified type.
2785 if (T->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00002786 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002787 InvalidDecl = true;
2788 }
2789
Ted Kremenek173dd312008-07-23 18:04:17 +00002790 // Get the visibility (access control) for this ivar.
2791 ObjCIvarDecl::AccessControl ac =
2792 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2793 : ObjCIvarDecl::None;
2794
2795 // Construct the decl.
2796 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00002797 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002798
Ted Kremenek173dd312008-07-23 18:04:17 +00002799 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00002800 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002801
2802 if (D.getInvalidType() || InvalidDecl)
2803 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00002804
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002805 return NewID;
2806}
2807
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00002808void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002809 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00002810 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00002811 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00002812 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002813 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2814 assert(EnclosingDecl && "missing record or interface decl");
2815 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2816
Ted Kremenek46a837c2008-09-05 17:16:31 +00002817 if (Record)
2818 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2819 // Diagnose code like:
2820 // struct S { struct S {} X; };
2821 // We discover this when we complete the outer S. Reject and ignore the
2822 // outer S.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002823 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
Chris Lattner271d4c22008-11-24 05:29:24 +00002824 << DefRecord->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00002825 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek46a837c2008-09-05 17:16:31 +00002826 Record->setInvalidDecl();
2827 return;
2828 }
2829
Chris Lattner4b009652007-07-25 00:24:17 +00002830 // Verify that all the fields are okay.
2831 unsigned NumNamedMembers = 0;
2832 llvm::SmallVector<FieldDecl*, 32> RecFields;
2833 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00002834
Chris Lattner4b009652007-07-25 00:24:17 +00002835 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002836
Steve Naroff9bb759f2007-09-14 22:20:54 +00002837 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2838 assert(FD && "missing field decl");
2839
2840 // Remember all fields.
2841 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00002842
2843 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00002844 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00002845
Chris Lattner4b009652007-07-25 00:24:17 +00002846 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00002847 if (FDTy->isFunctionType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002848 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattner271d4c22008-11-24 05:29:24 +00002849 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00002850 FD->setInvalidDecl();
2851 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002852 continue;
2853 }
Chris Lattner4b009652007-07-25 00:24:17 +00002854 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2855 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002856 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattner271d4c22008-11-24 05:29:24 +00002857 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00002858 FD->setInvalidDecl();
2859 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002860 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002861 }
Chris Lattner4b009652007-07-25 00:24:17 +00002862 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002863 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002864 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner271d4c22008-11-24 05:29:24 +00002865 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00002866 FD->setInvalidDecl();
2867 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002868 continue;
2869 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002870 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002871 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00002872 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00002873 FD->setInvalidDecl();
2874 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002875 continue;
2876 }
Chris Lattner4b009652007-07-25 00:24:17 +00002877 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002878 if (Record)
2879 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002880 }
Chris Lattner4b009652007-07-25 00:24:17 +00002881 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2882 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002883 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002884 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2885 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002886 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002887 Record->setHasFlexibleArrayMember(true);
2888 } else {
2889 // If this is a struct/class and this is not the last element, reject
2890 // it. Note that GCC supports variable sized arrays in the middle of
2891 // structures.
2892 if (i != NumFields-1) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002893 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00002894 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00002895 FD->setInvalidDecl();
2896 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002897 continue;
2898 }
Chris Lattner4b009652007-07-25 00:24:17 +00002899 // We support flexible arrays at the end of structs in other structs
2900 // as an extension.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002901 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00002902 << FD->getDeclName();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002903 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002904 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002905 }
2906 }
2907 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002908 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00002909 if (FDTy->isObjCInterfaceType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002910 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattnerb1753422008-11-23 21:45:46 +00002911 << FD->getDeclName();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002912 FD->setInvalidDecl();
2913 EnclosingDecl->setInvalidDecl();
2914 continue;
2915 }
Chris Lattner4b009652007-07-25 00:24:17 +00002916 // Keep track of the number of named members.
2917 if (IdentifierInfo *II = FD->getIdentifier()) {
2918 // Detect duplicate member names.
2919 if (!FieldIDs.insert(II)) {
Chris Lattner65cae292008-11-19 08:23:25 +00002920 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Chris Lattner4b009652007-07-25 00:24:17 +00002921 // Find the previous decl.
2922 SourceLocation PrevLoc;
Chris Lattner504c5432008-10-12 00:28:42 +00002923 for (unsigned i = 0; ; ++i) {
2924 assert(i != RecFields.size() && "Didn't find previous def!");
Chris Lattner4b009652007-07-25 00:24:17 +00002925 if (RecFields[i]->getIdentifier() == II) {
2926 PrevLoc = RecFields[i]->getLocation();
2927 break;
2928 }
2929 }
Chris Lattner1336cab2008-11-23 23:12:31 +00002930 Diag(PrevLoc, diag::note_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002931 FD->setInvalidDecl();
2932 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002933 continue;
2934 }
2935 ++NumNamedMembers;
2936 }
Chris Lattner4b009652007-07-25 00:24:17 +00002937 }
2938
Chris Lattner4b009652007-07-25 00:24:17 +00002939 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00002940 if (Record) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00002941 Record->completeDefinition(Context);
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +00002942 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2943 // Sema::ActOnFinishCXXClassDef.
2944 if (!isa<CXXRecordDecl>(Record))
2945 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002946 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00002947 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian624921a2008-12-13 20:28:25 +00002948 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner1100cfb2008-02-05 22:40:55 +00002949 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian624921a2008-12-13 20:28:25 +00002950 ID->addLayoutToClass(Context);
2951 }
Chris Lattner1100cfb2008-02-05 22:40:55 +00002952 else if (ObjCImplementationDecl *IMPDecl =
2953 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002954 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2955 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00002956 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00002957 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00002958 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00002959
2960 if (Attr)
2961 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002962}
2963
Steve Naroff0acc9c92007-09-15 18:49:24 +00002964Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00002965 DeclTy *lastEnumConst,
2966 SourceLocation IdLoc, IdentifierInfo *Id,
2967 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00002968 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002969 EnumConstantDecl *LastEnumConst =
2970 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2971 Expr *Val = static_cast<Expr*>(val);
2972
Chris Lattnera7549902007-08-26 06:24:45 +00002973 // The scope passed in may not be a decl scope. Zip up the scope tree until
2974 // we find one that is.
2975 while ((S->getFlags() & Scope::DeclScope) == 0)
2976 S = S->getParent();
2977
Chris Lattner4b009652007-07-25 00:24:17 +00002978 // Verify that there isn't already something declared with this name in this
2979 // scope.
Douglas Gregordd861062008-12-05 18:15:24 +00002980 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002981 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002982 // Maybe we will complain about the shadowed template parameter.
2983 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
2984 // Just pretend that we didn't see the previous declaration.
2985 PrevDecl = 0;
2986 }
2987
2988 if (PrevDecl) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00002989 // When in C++, we may get a TagDecl with the same name; in this case the
2990 // enum constant will 'hide' the tag.
2991 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2992 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002993 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002994 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner65cae292008-11-19 08:23:25 +00002995 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner4b009652007-07-25 00:24:17 +00002996 else
Chris Lattner65cae292008-11-19 08:23:25 +00002997 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner1336cab2008-11-23 23:12:31 +00002998 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002999 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00003000 return 0;
3001 }
3002 }
3003
3004 llvm::APSInt EnumVal(32);
3005 QualType EltTy;
3006 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00003007 // Make sure to promote the operand type to int.
3008 UsualUnaryConversions(Val);
3009
Chris Lattner4b009652007-07-25 00:24:17 +00003010 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3011 SourceLocation ExpLoc;
Anders Carlsson5374c6b2008-12-05 16:33:57 +00003012 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003013 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00003014 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00003015 } else {
3016 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003017 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00003018 }
3019
3020 if (!Val) {
3021 if (LastEnumConst) {
3022 // Assign the last value + 1.
3023 EnumVal = LastEnumConst->getInitVal();
3024 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00003025
3026 // Check for overflow on increment.
3027 if (EnumVal < LastEnumConst->getInitVal())
3028 Diag(IdLoc, diag::warn_enum_value_overflow);
3029
Chris Lattnere7f53a42007-08-27 17:37:24 +00003030 EltTy = LastEnumConst->getType();
3031 } else {
3032 // First value, set to zero.
3033 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003034 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00003035 }
Chris Lattner4b009652007-07-25 00:24:17 +00003036 }
3037
Chris Lattnere4650482008-03-15 06:12:44 +00003038 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00003039 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3040 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00003041 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00003042
3043 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00003044 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00003045 return New;
3046}
3047
Steve Naroffb0726b82008-08-07 14:08:16 +00003048// FIXME: For consistency with ActOnFields(), we should have the parser
3049// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00003050void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00003051 DeclTy **Elements, unsigned NumElements) {
3052 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Chris Lattner4b009652007-07-25 00:24:17 +00003053
Douglas Gregorae644892008-12-15 16:32:14 +00003054 if (Enum) {
3055 if (EnumDecl *Def = cast_or_null<EnumDecl>(Enum->getDefinition(Context))) {
3056 // Diagnose code like:
3057 // enum e0 {
3058 // E0 = sizeof(enum e0 { E1 })
3059 // };
3060 Diag(Def->getLocation(), diag::err_nested_redefinition)
3061 << Enum->getDeclName();
3062 Diag(Enum->getLocation(), diag::note_previous_definition);
3063 Enum->setInvalidDecl();
3064 return;
3065 }
Steve Naroffb0726b82008-08-07 14:08:16 +00003066 }
Chris Lattner435c3fd2007-08-28 05:10:31 +00003067 // TODO: If the result value doesn't fit in an int, it must be a long or long
3068 // long value. ISO C does not support this, but GCC does as an extension,
3069 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00003070 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00003071
Chris Lattner206754a2007-08-28 06:15:15 +00003072 // Verify that all the values are okay, compute the size of the values, and
3073 // reverse the list.
3074 unsigned NumNegativeBits = 0;
3075 unsigned NumPositiveBits = 0;
3076
3077 // Keep track of whether all elements have type int.
3078 bool AllElementsInt = true;
3079
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003080 QualType EnumType = Context.getTypeDeclType(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003081 EnumConstantDecl *EltList = 0;
3082 for (unsigned i = 0; i != NumElements; ++i) {
3083 EnumConstantDecl *ECD =
3084 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3085 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003086
3087 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003088 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003089 assert(InitVal.getBitWidth() >= IntWidth &&
3090 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00003091 if (InitVal.getBitWidth() > IntWidth) {
3092 llvm::APSInt V(InitVal);
3093 V.trunc(IntWidth);
3094 V.extend(InitVal.getBitWidth());
3095 if (V != InitVal)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003096 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3097 << InitVal.toString(10);
Chris Lattnercb33ae12007-08-28 05:27:00 +00003098 }
Chris Lattner206754a2007-08-28 06:15:15 +00003099
3100 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003101 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00003102 NumPositiveBits = std::max(NumPositiveBits,
3103 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00003104 else
Chris Lattneraff63f02008-01-14 21:47:29 +00003105 NumNegativeBits = std::max(NumNegativeBits,
3106 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00003107
Chris Lattner206754a2007-08-28 06:15:15 +00003108 // Keep track of whether every enum element has type int (very commmon).
3109 if (AllElementsInt)
3110 AllElementsInt = ECD->getType() == Context.IntTy;
3111
Chris Lattner4b009652007-07-25 00:24:17 +00003112 ECD->setNextDeclarator(EltList);
3113 EltList = ECD;
3114 }
3115
Chris Lattner206754a2007-08-28 06:15:15 +00003116 // Figure out the type that should be used for this enum.
3117 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3118 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003119 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00003120
3121 if (NumNegativeBits) {
3122 // If there is a negative value, figure out the smallest integer type (of
3123 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003124 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003125 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003126 BestWidth = IntWidth;
3127 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003128 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003129
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003130 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003131 BestType = Context.LongTy;
3132 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003133 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003134
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003135 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003136 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3137 BestType = Context.LongLongTy;
3138 }
3139 }
3140 } else {
3141 // If there is no negative value, figure out which of uint, ulong, ulonglong
3142 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003143 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003144 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003145 BestWidth = IntWidth;
3146 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00003147 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00003148 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003149 } else {
3150 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003151 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00003152 "How could an initializer get larger than ULL?");
3153 BestType = Context.UnsignedLongLongTy;
3154 }
3155 }
3156
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003157 // Loop over all of the enumerator constants, changing their types to match
3158 // the type of the enum if needed.
3159 for (unsigned i = 0; i != NumElements; ++i) {
3160 EnumConstantDecl *ECD =
3161 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3162 if (!ECD) continue; // Already issued a diagnostic.
3163
3164 // Standard C says the enumerators have int type, but we allow, as an
3165 // extension, the enumerators to be larger than int size. If each
3166 // enumerator value fits in an int, type it as an int, otherwise type it the
3167 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3168 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003169 if (ECD->getType() == Context.IntTy) {
3170 // Make sure the init value is signed.
3171 llvm::APSInt IV = ECD->getInitVal();
3172 IV.setIsSigned(true);
3173 ECD->setInitVal(IV);
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003174
3175 if (getLangOptions().CPlusPlus)
3176 // C++ [dcl.enum]p4: Following the closing brace of an
3177 // enum-specifier, each enumerator has the type of its
3178 // enumeration.
3179 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003180 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003181 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003182
3183 // Determine whether the value fits into an int.
3184 llvm::APSInt InitVal = ECD->getInitVal();
3185 bool FitsInInt;
3186 if (InitVal.isUnsigned() || !InitVal.isNegative())
3187 FitsInInt = InitVal.getActiveBits() < IntWidth;
3188 else
3189 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3190
3191 // If it fits into an integer type, force it. Otherwise force it to match
3192 // the enum decl type.
3193 QualType NewTy;
3194 unsigned NewWidth;
3195 bool NewSign;
3196 if (FitsInInt) {
3197 NewTy = Context.IntTy;
3198 NewWidth = IntWidth;
3199 NewSign = true;
3200 } else if (ECD->getType() == BestType) {
3201 // Already the right type!
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003202 if (getLangOptions().CPlusPlus)
3203 // C++ [dcl.enum]p4: Following the closing brace of an
3204 // enum-specifier, each enumerator has the type of its
3205 // enumeration.
3206 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003207 continue;
3208 } else {
3209 NewTy = BestType;
3210 NewWidth = BestWidth;
3211 NewSign = BestType->isSignedIntegerType();
3212 }
3213
3214 // Adjust the APSInt value.
3215 InitVal.extOrTrunc(NewWidth);
3216 InitVal.setIsSigned(NewSign);
3217 ECD->setInitVal(InitVal);
3218
3219 // Adjust the Expr initializer and type.
Douglas Gregor70d26122008-11-12 17:17:38 +00003220 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3221 /*isLvalue=*/false));
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003222 if (getLangOptions().CPlusPlus)
3223 // C++ [dcl.enum]p4: Following the closing brace of an
3224 // enum-specifier, each enumerator has the type of its
3225 // enumeration.
3226 ECD->setType(EnumType);
3227 else
3228 ECD->setType(NewTy);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003229 }
Chris Lattner206754a2007-08-28 06:15:15 +00003230
Douglas Gregor8acb7272008-12-11 16:49:14 +00003231 Enum->completeDefinition(Context, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003232 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003233}
3234
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003235Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00003236 ExprArg expr) {
3237 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3238
Chris Lattner81db64a2008-03-16 00:16:02 +00003239 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003240}
3241
Chris Lattner806a5f52008-01-12 07:05:38 +00003242Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00003243 SourceLocation LBrace,
3244 SourceLocation RBrace,
3245 const char *Lang,
3246 unsigned StrSize,
3247 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00003248 LinkageSpecDecl::LanguageIDs Language;
3249 Decl *dcl = static_cast<Decl *>(D);
3250 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3251 Language = LinkageSpecDecl::lang_c;
3252 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3253 Language = LinkageSpecDecl::lang_cxx;
3254 else {
3255 Diag(Loc, diag::err_bad_language);
3256 return 0;
3257 }
3258
3259 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00003260 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00003261}
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003262
3263void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3264 ExprTy *alignment, SourceLocation PragmaLoc,
3265 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3266 Expr *Alignment = static_cast<Expr *>(alignment);
3267
3268 // If specified then alignment must be a "small" power of two.
3269 unsigned AlignmentVal = 0;
3270 if (Alignment) {
3271 llvm::APSInt Val;
3272 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3273 !Val.isPowerOf2() ||
3274 Val.getZExtValue() > 16) {
3275 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3276 delete Alignment;
3277 return; // Ignore
3278 }
3279
3280 AlignmentVal = (unsigned) Val.getZExtValue();
3281 }
3282
3283 switch (Kind) {
3284 case Action::PPK_Default: // pack([n])
3285 PackContext.setAlignment(AlignmentVal);
3286 break;
3287
3288 case Action::PPK_Show: // pack(show)
3289 // Show the current alignment, making sure to show the right value
3290 // for the default.
3291 AlignmentVal = PackContext.getAlignment();
3292 // FIXME: This should come from the target.
3293 if (AlignmentVal == 0)
3294 AlignmentVal = 8;
Chris Lattnera5cc1882008-11-19 07:25:44 +00003295 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003296 break;
3297
3298 case Action::PPK_Push: // pack(push [, id] [, [n])
3299 PackContext.push(Name);
3300 // Set the new alignment if specified.
3301 if (Alignment)
3302 PackContext.setAlignment(AlignmentVal);
3303 break;
3304
3305 case Action::PPK_Pop: // pack(pop [, id] [, n])
3306 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3307 // "#pragma pack(pop, identifier, n) is undefined"
3308 if (Alignment && Name)
3309 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3310
3311 // Do the pop.
3312 if (!PackContext.pop(Name)) {
3313 // If a name was specified then failure indicates the name
3314 // wasn't found. Otherwise failure indicates the stack was
3315 // empty.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003316 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3317 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003318
3319 // FIXME: Warn about popping named records as MSVC does.
3320 } else {
3321 // Pop succeeded, set the new alignment if specified.
3322 if (Alignment)
3323 PackContext.setAlignment(AlignmentVal);
3324 }
3325 break;
3326
3327 default:
3328 assert(0 && "Invalid #pragma pack kind.");
3329 }
3330}
3331
3332bool PragmaPackStack::pop(IdentifierInfo *Name) {
3333 if (Stack.empty())
3334 return false;
3335
3336 // If name is empty just pop top.
3337 if (!Name) {
3338 Alignment = Stack.back().first;
3339 Stack.pop_back();
3340 return true;
3341 }
3342
3343 // Otherwise, find the named record.
3344 for (unsigned i = Stack.size(); i != 0; ) {
3345 --i;
Daniel Dunbarc13c54c2008-11-19 10:32:38 +00003346 if (Stack[i].second == Name) {
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003347 // Found it, pop up to and including this record.
3348 Alignment = Stack[i].first;
3349 Stack.erase(Stack.begin() + i, Stack.end());
3350 return true;
3351 }
3352 }
3353
3354 return false;
3355}