blob: df9118238337bc164baa22c36d280845aea089b1 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
28using namespace clang;
29
Argyrios Kyrtzidis39caa082008-08-01 10:35:27 +000030Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
Steve Naroffb327ce02008-04-02 14:35:35 +000031 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
32
Douglas Gregor2ce52f32008-04-13 21:07:44 +000033 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
34 isa<ObjCInterfaceDecl>(IIDecl) ||
35 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000036 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000037 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000038}
39
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000040DeclContext *Sema::getDCParent(DeclContext *DC) {
41 // If CurContext is a ObjC method, getParent() will return NULL.
42 if (isa<ObjCMethodDecl>(DC))
43 return Context.getTranslationUnitDecl();
44
45 // A C++ inline method is parsed *after* the topmost class it was declared in
46 // is fully parsed (it's "complete").
47 // The parsing of a C++ inline method happens at the declaration context of
48 // the topmost (non-nested) class it is declared in.
49 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
50 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
51 DC = MD->getParent();
52 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
53 DC = RD;
54
55 // Return the declaration context of the topmost class the inline method is
56 // declared in.
57 return DC;
58 }
59
60 return DC->getParent();
61}
62
Chris Lattner9fdf9c62008-04-22 18:39:57 +000063void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000064 assert(getDCParent(DC) == CurContext &&
65 "The next DeclContext should be directly contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000066 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000067}
68
Chris Lattnerb048c982008-04-06 04:47:34 +000069void Sema::PopDeclContext() {
70 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000071 CurContext = getDCParent(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000072}
73
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000074/// Add this decl to the scope shadowed decl chains.
75void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000076 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000077
78 // C++ [basic.scope]p4:
79 // -- exactly one declaration shall declare a class name or
80 // enumeration name that is not a typedef name and the other
81 // declarations shall all refer to the same object or
82 // enumerator, or all refer to functions and function templates;
83 // in this case the class name or enumeration name is hidden.
84 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
85 // We are pushing the name of a tag (enum or class).
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +000086 IdentifierResolver::iterator
87 I = IdResolver.begin(TD->getIdentifier(),
88 TD->getDeclContext(), false/*LookInParentCtx*/);
89 if (I != IdResolver.end() &&
90 IdResolver.isDeclInScope(*I, TD->getDeclContext(), S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000091 // There is already a declaration with the same name in the same
92 // scope. It must be found before we find the new declaration,
93 // so swap the order on the shadowed declaration chain.
94
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +000095 IdResolver.AddShadowedDecl(TD, *I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000096 return;
97 }
98 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000099 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000100}
101
Steve Naroffb216c882007-10-09 22:01:59 +0000102void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000103 if (S->decl_empty()) return;
104 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000105
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
107 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000108 Decl *TmpD = static_cast<Decl*>(*I);
109 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000110
111 if (isa<CXXFieldDecl>(TmpD)) continue;
112
113 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
114 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000115
Reid Spencer5f016e22007-07-11 17:01:13 +0000116 IdentifierInfo *II = D->getIdentifier();
117 if (!II) continue;
118
Ted Kremeneka89d1972008-09-03 18:03:35 +0000119 // We only want to remove the decls from the identifier decl chains for
120 // local scopes, when inside a function/method.
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000121 if (S->getFnParent() != 0)
122 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000123
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000124 // Chain this decl to the containing DeclContext.
125 D->setNext(CurContext->getDeclChain());
126 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 }
128}
129
Steve Naroffe8043c32008-04-01 23:04:06 +0000130/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
131/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000132ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000133 // The third "scope" argument is 0 since we aren't enabling lazy built-in
134 // creation from this context.
135 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000136
Steve Naroffb327ce02008-04-02 14:35:35 +0000137 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000138}
139
Steve Naroffe8043c32008-04-01 23:04:06 +0000140/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000141/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000142Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
143 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000145 unsigned NS = NSI;
146 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
147 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000148
Reid Spencer5f016e22007-07-11 17:01:13 +0000149 // Scan up the scope chain looking for a decl that matches this identifier
150 // that is in the appropriate namespace. This search should not take long, as
151 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000152 for (IdentifierResolver::iterator
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000153 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I)
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000154 if ((*I)->getIdentifierNamespace() & NS)
155 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000156
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 // If we didn't find a use of this identifier, and if the identifier
158 // corresponds to a compiler builtin, create the decl object for the builtin
159 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000160 if (NS & Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000161 if (enableLazyBuiltinCreation) {
162 // If this is a builtin on this (or all) targets, create the decl.
163 if (unsigned BuiltinID = II->getBuiltinID())
164 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
165 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000166 if (getLangOptions().ObjC1) {
167 // @interface and @compatibility_alias introduce typedef-like names.
168 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000169 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000170 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000171 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
172 if (IDI != ObjCInterfaceDecls.end())
173 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000174 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
175 if (I != ObjCAliasDecls.end())
176 return I->second->getClassInterface();
177 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000178 }
179 return 0;
180}
181
Chris Lattner95e2c712008-05-05 22:18:14 +0000182void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000183 if (!Context.getBuiltinVaListType().isNull())
184 return;
185
186 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000187 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000188 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000189 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
190}
191
Reid Spencer5f016e22007-07-11 17:01:13 +0000192/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
193/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000194ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
195 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000196 Builtin::ID BID = (Builtin::ID)bid;
197
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000198 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattner95e2c712008-05-05 22:18:14 +0000199 BID == Builtin::BI__builtin_va_copy ||
Chris Lattnerf8396b62008-07-09 17:26:36 +0000200 BID == Builtin::BI__builtin_va_end ||
201 BID == Builtin::BI__builtin_stdarg_start)
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000202 InitBuiltinVaListType();
203
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000204 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000205 FunctionDecl *New = FunctionDecl::Create(Context,
206 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000207 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000208 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000209
Chris Lattner95e2c712008-05-05 22:18:14 +0000210 // Create Decl objects for each parameter, adding them to the
211 // FunctionDecl.
212 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
213 llvm::SmallVector<ParmVarDecl*, 16> Params;
214 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
215 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
216 FT->getArgType(i), VarDecl::None, 0,
217 0));
218 New->setParams(&Params[0], Params.size());
219 }
220
221
222
Chris Lattner7f925cc2008-04-11 07:00:53 +0000223 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000224 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000225 return New;
226}
227
228/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
229/// and scope as a previous declaration 'Old'. Figure out how to resolve this
230/// situation, merging decls or emitting diagnostics as appropriate.
231///
Steve Naroffe8043c32008-04-01 23:04:06 +0000232TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000233 // Verify the old decl was also a typedef.
234 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
235 if (!Old) {
236 Diag(New->getLocation(), diag::err_redefinition_different_kind,
237 New->getName());
238 Diag(OldD->getLocation(), diag::err_previous_definition);
239 return New;
240 }
241
Chris Lattner99cb9972008-07-25 18:44:27 +0000242 // If the typedef types are not identical, reject them in all languages and
243 // with any extensions enabled.
244 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
245 Context.getCanonicalType(Old->getUnderlyingType()) !=
246 Context.getCanonicalType(New->getUnderlyingType())) {
247 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
248 New->getUnderlyingType().getAsString(),
249 Old->getUnderlyingType().getAsString());
250 Diag(Old->getLocation(), diag::err_previous_definition);
251 return Old;
252 }
253
Steve Naroff8ee529b2007-10-31 18:42:27 +0000254 // Allow multiple definitions for ObjC built-in typedefs.
255 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000256 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000257 return Old;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000258
259 if (getLangOptions().Microsoft) return New;
260
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000261 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
262 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
263 // *either* declaration is in a system header. The code below implements
264 // this adhoc compatibility rule. FIXME: The following code will not
265 // work properly when compiling ".i" files (containing preprocessed output).
266 SourceManager &SrcMgr = Context.getSourceManager();
Nico Weber491be732008-08-29 17:02:23 +0000267 if (SrcMgr.isInSystemHeader(Old->getLocation()))
268 return New;
269 if (SrcMgr.isInSystemHeader(New->getLocation()))
270 return New;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000271
Ted Kremenek2d05c082008-05-23 21:28:18 +0000272 Diag(New->getLocation(), diag::err_redefinition, New->getName());
273 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 return New;
275}
276
Chris Lattner6b6b5372008-06-26 18:38:35 +0000277/// DeclhasAttr - returns true if decl Declaration already has the target
278/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000279static bool DeclHasAttr(const Decl *decl, const Attr *target) {
280 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
281 if (attr->getKind() == target->getKind())
282 return true;
283
284 return false;
285}
286
287/// MergeAttributes - append attributes from the Old decl to the New one.
288static void MergeAttributes(Decl *New, Decl *Old) {
289 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
290
Chris Lattnerddee4232008-03-03 03:28:21 +0000291 while (attr) {
292 tmp = attr;
293 attr = attr->getNext();
294
295 if (!DeclHasAttr(New, tmp)) {
296 New->addAttr(tmp);
297 } else {
298 tmp->setNext(0);
299 delete(tmp);
300 }
301 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000302
303 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000304}
305
Chris Lattner04421082008-04-08 04:40:51 +0000306/// MergeFunctionDecl - We just parsed a function 'New' from
307/// declarator D which has the same name and scope as a previous
308/// declaration 'Old'. Figure out how to resolve this situation,
309/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000310/// Redeclaration will be set true if thisNew is a redeclaration OldD.
311FunctionDecl *
312Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
313 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 // Verify the old decl was also a function.
315 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
316 if (!Old) {
317 Diag(New->getLocation(), diag::err_redefinition_different_kind,
318 New->getName());
319 Diag(OldD->getLocation(), diag::err_previous_definition);
320 return New;
321 }
Chris Lattner04421082008-04-08 04:40:51 +0000322
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000323 QualType OldQType = Context.getCanonicalType(Old->getType());
324 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000325
Chris Lattner04421082008-04-08 04:40:51 +0000326 // C++ [dcl.fct]p3:
327 // All declarations for a function shall agree exactly in both the
328 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000329 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
330 MergeAttributes(New, Old);
331 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000332 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000333 }
Chris Lattner04421082008-04-08 04:40:51 +0000334
335 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000336 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000337 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000338 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000339 MergeAttributes(New, Old);
340 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000341 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000342 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000343
Steve Naroff837618c2008-01-16 15:01:34 +0000344 // A function that has already been declared has been redeclared or defined
345 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000346 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000347 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000348 PrevDiag = diag::err_previous_definition;
349 else if (Old->isImplicit())
350 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000351 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000352 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000353
Reid Spencer5f016e22007-07-11 17:01:13 +0000354 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
355 // TODO: This is totally simplistic. It should handle merging functions
356 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000357 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
358 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 return New;
360}
361
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000362/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000363static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000364 if (VD->isFileVarDecl())
365 return (!VD->getInit() &&
366 (VD->getStorageClass() == VarDecl::None ||
367 VD->getStorageClass() == VarDecl::Static));
368 return false;
369}
370
371/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
372/// when dealing with C "tentative" external object definitions (C99 6.9.2).
373void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
374 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000375 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000376
377 for (IdentifierResolver::iterator
378 I = IdResolver.begin(VD->getIdentifier(),
379 VD->getDeclContext(), false/*LookInParentCtx*/),
380 E = IdResolver.end(); I != E; ++I) {
381 if (*I != VD && IdResolver.isDeclInScope(*I, VD->getDeclContext(), S)) {
382 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
383
Steve Narofff855e6f2008-08-10 15:20:13 +0000384 // Handle the following case:
385 // int a[10];
386 // int a[]; - the code below makes sure we set the correct type.
387 // int a[11]; - this is an error, size isn't 10.
388 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
389 OldDecl->getType()->isConstantArrayType())
390 VD->setType(OldDecl->getType());
391
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000392 // Check for "tentative" definitions. We can't accomplish this in
393 // MergeVarDecl since the initializer hasn't been attached.
394 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
395 continue;
396
397 // Handle __private_extern__ just like extern.
398 if (OldDecl->getStorageClass() != VarDecl::Extern &&
399 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
400 VD->getStorageClass() != VarDecl::Extern &&
401 VD->getStorageClass() != VarDecl::PrivateExtern) {
402 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
403 Diag(OldDecl->getLocation(), diag::err_previous_definition);
404 }
405 }
406 }
407}
408
Reid Spencer5f016e22007-07-11 17:01:13 +0000409/// MergeVarDecl - We just parsed a variable 'New' which has the same name
410/// and scope as a previous declaration 'Old'. Figure out how to resolve this
411/// situation, merging decls or emitting diagnostics as appropriate.
412///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000413/// Tentative definition rules (C99 6.9.2p2) are checked by
414/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
415/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000416///
Steve Naroffe8043c32008-04-01 23:04:06 +0000417VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000418 // Verify the old decl was also a variable.
419 VarDecl *Old = dyn_cast<VarDecl>(OldD);
420 if (!Old) {
421 Diag(New->getLocation(), diag::err_redefinition_different_kind,
422 New->getName());
423 Diag(OldD->getLocation(), diag::err_previous_definition);
424 return New;
425 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000426
427 MergeAttributes(New, Old);
428
Reid Spencer5f016e22007-07-11 17:01:13 +0000429 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000430 QualType OldCType = Context.getCanonicalType(Old->getType());
431 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000432 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 Diag(New->getLocation(), diag::err_redefinition, New->getName());
434 Diag(Old->getLocation(), diag::err_previous_definition);
435 return New;
436 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000437 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
438 if (New->getStorageClass() == VarDecl::Static &&
439 (Old->getStorageClass() == VarDecl::None ||
440 Old->getStorageClass() == VarDecl::Extern)) {
441 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
442 Diag(Old->getLocation(), diag::err_previous_definition);
443 return New;
444 }
445 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
446 if (New->getStorageClass() != VarDecl::Static &&
447 Old->getStorageClass() == VarDecl::Static) {
448 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
449 Diag(Old->getLocation(), diag::err_previous_definition);
450 return New;
451 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000452 // File scoped variables are analyzed in FinalizeDeclaratorGroup.
453 if (!New->isFileVarDecl()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 Diag(New->getLocation(), diag::err_redefinition, New->getName());
455 Diag(Old->getLocation(), diag::err_previous_definition);
456 }
457 return New;
458}
459
Chris Lattner04421082008-04-08 04:40:51 +0000460/// CheckParmsForFunctionDef - Check that the parameters of the given
461/// function are appropriate for the definition of a function. This
462/// takes care of any checks that cannot be performed on the
463/// declaration itself, e.g., that the types of each of the function
464/// parameters are complete.
465bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
466 bool HasInvalidParm = false;
467 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
468 ParmVarDecl *Param = FD->getParamDecl(p);
469
470 // C99 6.7.5.3p4: the parameters in a parameter type list in a
471 // function declarator that is part of a function definition of
472 // that function shall not have incomplete type.
473 if (Param->getType()->isIncompleteType() &&
474 !Param->isInvalidDecl()) {
475 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
476 Param->getType().getAsString());
477 Param->setInvalidDecl();
478 HasInvalidParm = true;
479 }
480 }
481
482 return HasInvalidParm;
483}
484
Reid Spencer5f016e22007-07-11 17:01:13 +0000485/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
486/// no declarator (e.g. "struct foo;") is parsed.
487Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
488 // TODO: emit error on 'int;' or 'const enum foo;'.
489 // TODO: emit error on 'typedef int;'
490 // if (!DS.isMissingDeclaratorOk()) Diag(...);
491
Steve Naroff92199282007-11-17 21:37:36 +0000492 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000493}
494
Steve Naroffd0091aa2008-01-10 22:15:12 +0000495bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000496 // Get the type before calling CheckSingleAssignmentConstraints(), since
497 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000498 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000499
Chris Lattner5cf216b2008-01-04 18:04:52 +0000500 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
501 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
502 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000503}
504
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000505bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000506 const ArrayType *AT = Context.getAsArrayType(DeclT);
507
508 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000509 // C99 6.7.8p14. We have an array of character type with unknown size
510 // being initialized to a string literal.
511 llvm::APSInt ConstVal(32);
512 ConstVal = strLiteral->getByteLength() + 1;
513 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000514 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000515 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000516 } else {
517 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000518 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000519 // FIXME: Avoid truncation for 64-bit length strings.
520 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000521 Diag(strLiteral->getSourceRange().getBegin(),
522 diag::warn_initializer_string_for_char_array_too_long,
523 strLiteral->getSourceRange());
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000524 }
525 // Set type from "char *" to "constant array of char".
526 strLiteral->setType(DeclT);
527 // For now, we always return false (meaning success).
528 return false;
529}
530
531StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000532 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000533 if (AT && AT->getElementType()->isCharType()) {
534 return dyn_cast<StringLiteral>(Init);
535 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000536 return 0;
537}
538
Steve Naroffa9960332008-01-25 00:51:06 +0000539bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000540 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
541 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000542 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Steve Naroffca107302008-01-21 23:53:58 +0000543 return Diag(VAT->getSizeExpr()->getLocStart(),
544 diag::err_variable_object_no_init,
545 VAT->getSizeExpr()->getSourceRange());
546
Steve Naroff2fdc3742007-12-10 22:44:33 +0000547 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
548 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000549 // FIXME: Handle wide strings
550 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
551 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000552
553 if (DeclType->isArrayType())
554 return Diag(Init->getLocStart(),
555 diag::err_array_init_list_required,
556 Init->getSourceRange());
557
Steve Naroffd0091aa2008-01-10 22:15:12 +0000558 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000559 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000560
Steve Naroff0cca7492008-05-01 22:18:59 +0000561 InitListChecker CheckInitList(this, InitList, DeclType);
562 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000563}
564
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000565Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000566Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000567 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000568 IdentifierInfo *II = D.getIdentifier();
569
Chris Lattnere80a59c2007-07-25 00:24:17 +0000570 // All of these full declarators require an identifier. If it doesn't have
571 // one, the ParsedFreeStandingDeclSpec action should be used.
572 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000573 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000574 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000575 D.getDeclSpec().getSourceRange(), D.getSourceRange());
576 return 0;
577 }
578
Chris Lattner31e05722007-08-26 06:24:45 +0000579 // The scope passed in may not be a decl scope. Zip up the scope tree until
580 // we find one that is.
581 while ((S->getFlags() & Scope::DeclScope) == 0)
582 S = S->getParent();
583
Reid Spencer5f016e22007-07-11 17:01:13 +0000584 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000585 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000586 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000587 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000588
589 // In C++, the previous declaration we find might be a tag type
590 // (class or enum). In this case, the new declaration will hide the
591 // tag type.
592 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
593 PrevDecl = 0;
594
Chris Lattner41af0932007-11-14 06:34:38 +0000595 QualType R = GetTypeForDeclarator(D, S);
596 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
597
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000599 // Check that there are no default arguments (C++ only).
600 if (getLangOptions().CPlusPlus)
601 CheckExtraCXXDefaultArguments(D);
602
Chris Lattner41af0932007-11-14 06:34:38 +0000603 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000604 if (!NewTD) return 0;
605
606 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000607 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000608 // Merge the decl with the existing one if appropriate. If the decl is
609 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000610 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000611 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
612 if (NewTD == 0) return 0;
613 }
614 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000615 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000616 // C99 6.7.7p2: If a typedef name specifies a variably modified type
617 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000618 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
619 // FIXME: Diagnostic needs to be fixed.
620 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000621 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 }
623 }
Chris Lattner41af0932007-11-14 06:34:38 +0000624 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000625 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000626 switch (D.getDeclSpec().getStorageClassSpec()) {
627 default: assert(0 && "Unknown storage class!");
628 case DeclSpec::SCS_auto:
629 case DeclSpec::SCS_register:
630 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
631 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000632 InvalidDecl = true;
633 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000634 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
635 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
636 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000637 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000638 }
639
Chris Lattnera98e58d2008-03-15 21:24:04 +0000640 bool isInline = D.getDeclSpec().isInlineSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000641 FunctionDecl *NewFD;
642 if (D.getContext() == Declarator::MemberContext) {
643 // This is a C++ method declaration.
644 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
645 D.getIdentifierLoc(), II, R,
646 (SC == FunctionDecl::Static), isInline,
647 LastDeclarator);
648 } else {
649 NewFD = FunctionDecl::Create(Context, CurContext,
650 D.getIdentifierLoc(),
651 II, R, SC, isInline,
652 LastDeclarator);
653 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000654 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000655 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000656
Daniel Dunbara80f8742008-08-05 01:35:17 +0000657 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +0000658 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +0000659 // The parser guarantees this is a string.
660 StringLiteral *SE = cast<StringLiteral>(E);
661 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
662 SE->getByteLength())));
663 }
664
Chris Lattner04421082008-04-08 04:40:51 +0000665 // Copy the parameter declarations from the declarator D to
666 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000667 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000668 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
669
670 // Create Decl objects for each parameter, adding them to the
671 // FunctionDecl.
672 llvm::SmallVector<ParmVarDecl*, 16> Params;
673
674 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
675 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000676 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000677 // We let through "const void" here because Sema::GetTypeForDeclarator
678 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000679 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
680 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000681 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
682 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000683 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
684
Chris Lattnerdef026a2008-04-10 02:26:16 +0000685 // In C++, the empty parameter-type-list must be spelled "void"; a
686 // typedef of void is not permitted.
687 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000688 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000689 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
690 }
691
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000692 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000693 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
694 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
695 }
696
697 NewFD->setParams(&Params[0], Params.size());
698 }
699
Steve Naroffffce4d52008-01-09 23:34:55 +0000700 // Merge the decl with the existing one if appropriate. Since C functions
701 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000702 if (PrevDecl &&
703 (!getLangOptions().CPlusPlus ||
704 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000705 bool Redeclaration = false;
706 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 if (NewFD == 0) return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +0000708 if (Redeclaration) {
Eli Friedman27424962008-05-27 05:07:37 +0000709 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregorf0097952008-04-21 02:02:58 +0000710 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000711 }
712 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000713
714 // In C++, check default arguments now that we have merged decls.
715 if (getLangOptions().CPlusPlus)
716 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000718 // Check that there are no default arguments (C++ only).
719 if (getLangOptions().CPlusPlus)
720 CheckExtraCXXDefaultArguments(D);
721
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000722 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000723 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
724 D.getIdentifier()->getName());
725 InvalidDecl = true;
726 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000727
728 VarDecl *NewVD;
729 VarDecl::StorageClass SC;
730 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000731 default: assert(0 && "Unknown storage class!");
732 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
733 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
734 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
735 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
736 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
737 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000739 if (D.getContext() == Declarator::MemberContext) {
740 assert(SC == VarDecl::Static && "Invalid storage class for member!");
741 // This is a static data member for a C++ class.
742 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
743 D.getIdentifierLoc(), II,
744 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000745 } else {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000746 if (S->getFnParent() == 0) {
747 // C99 6.9p2: The storage-class specifiers auto and register shall not
748 // appear in the declaration specifiers in an external declaration.
749 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
750 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
751 R.getAsString());
752 InvalidDecl = true;
753 }
754 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
755 II, R, SC, LastDeclarator);
756 } else {
757 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
758 II, R, SC, LastDeclarator);
759 }
Steve Naroff53a32342007-08-28 18:45:29 +0000760 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000762 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +0000763
Daniel Dunbara735ad82008-08-06 00:03:29 +0000764 // Handle GNU asm-label extension (encoded as an attribute).
765 if (Expr *E = (Expr*) D.getAsmLabel()) {
766 // The parser guarantees this is a string.
767 StringLiteral *SE = cast<StringLiteral>(E);
768 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
769 SE->getByteLength())));
770 }
771
Nate Begemanc8e89a82008-03-14 18:07:10 +0000772 // Emit an error if an address space was applied to decl with local storage.
773 // This includes arrays of objects with address space qualifiers, but not
774 // automatic variables that point to other address spaces.
775 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000776 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
777 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
778 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000779 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000780 // Merge the decl with the existing one if appropriate. If the decl is
781 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000782 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000783 NewVD = MergeVarDecl(NewVD, PrevDecl);
784 if (NewVD == 0) return 0;
785 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 New = NewVD;
787 }
788
789 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000790 if (II)
791 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000792 // If any semantic error occurred, mark the decl as invalid.
793 if (D.getInvalidType() || InvalidDecl)
794 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000795
796 return New;
797}
798
Eli Friedmanc594b322008-05-20 13:48:25 +0000799bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
800 switch (Init->getStmtClass()) {
801 default:
802 Diag(Init->getExprLoc(),
803 diag::err_init_element_not_constant, Init->getSourceRange());
804 return true;
805 case Expr::ParenExprClass: {
806 const ParenExpr* PE = cast<ParenExpr>(Init);
807 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
808 }
809 case Expr::CompoundLiteralExprClass:
810 return cast<CompoundLiteralExpr>(Init)->isFileScope();
811 case Expr::DeclRefExprClass: {
812 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +0000813 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
814 if (VD->hasGlobalStorage())
815 return false;
816 Diag(Init->getExprLoc(),
817 diag::err_init_element_not_constant, Init->getSourceRange());
818 return true;
819 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000820 if (isa<FunctionDecl>(D))
821 return false;
822 Diag(Init->getExprLoc(),
823 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Naroffd0091aa2008-01-10 22:15:12 +0000824 return true;
825 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000826 case Expr::MemberExprClass: {
827 const MemberExpr *M = cast<MemberExpr>(Init);
828 if (M->isArrow())
829 return CheckAddressConstantExpression(M->getBase());
830 return CheckAddressConstantExpressionLValue(M->getBase());
831 }
832 case Expr::ArraySubscriptExprClass: {
833 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
834 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
835 return CheckAddressConstantExpression(ASE->getBase()) ||
836 CheckArithmeticConstantExpression(ASE->getIdx());
837 }
838 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +0000839 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +0000840 return false;
841 case Expr::UnaryOperatorClass: {
842 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
843
844 // C99 6.6p9
845 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +0000846 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +0000847
848 Diag(Init->getExprLoc(),
849 diag::err_init_element_not_constant, Init->getSourceRange());
850 return true;
851 }
852 }
853}
854
855bool Sema::CheckAddressConstantExpression(const Expr* Init) {
856 switch (Init->getStmtClass()) {
857 default:
858 Diag(Init->getExprLoc(),
859 diag::err_init_element_not_constant, Init->getSourceRange());
860 return true;
861 case Expr::ParenExprClass: {
862 const ParenExpr* PE = cast<ParenExpr>(Init);
863 return CheckAddressConstantExpression(PE->getSubExpr());
864 }
865 case Expr::StringLiteralClass:
866 case Expr::ObjCStringLiteralClass:
867 return false;
868 case Expr::CallExprClass: {
869 const CallExpr *CE = cast<CallExpr>(Init);
870 if (CE->isBuiltinConstantExpr())
871 return false;
872 Diag(Init->getExprLoc(),
873 diag::err_init_element_not_constant, Init->getSourceRange());
874 return true;
875 }
876 case Expr::UnaryOperatorClass: {
877 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
878
879 // C99 6.6p9
880 if (Exp->getOpcode() == UnaryOperator::AddrOf)
881 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
882
883 if (Exp->getOpcode() == UnaryOperator::Extension)
884 return CheckAddressConstantExpression(Exp->getSubExpr());
885
886 Diag(Init->getExprLoc(),
887 diag::err_init_element_not_constant, Init->getSourceRange());
888 return true;
889 }
890 case Expr::BinaryOperatorClass: {
891 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
892 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
893
894 Expr *PExp = Exp->getLHS();
895 Expr *IExp = Exp->getRHS();
896 if (IExp->getType()->isPointerType())
897 std::swap(PExp, IExp);
898
899 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
900 return CheckAddressConstantExpression(PExp) ||
901 CheckArithmeticConstantExpression(IExp);
902 }
Eli Friedmanc3f07642008-08-25 20:46:57 +0000903 case Expr::ImplicitCastExprClass:
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000904 case Expr::ExplicitCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +0000905 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +0000906 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
907 // Check for implicit promotion
908 if (SubExpr->getType()->isFunctionType() ||
909 SubExpr->getType()->isArrayType())
910 return CheckAddressConstantExpressionLValue(SubExpr);
911 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000912
913 // Check for pointer->pointer cast
914 if (SubExpr->getType()->isPointerType())
915 return CheckAddressConstantExpression(SubExpr);
916
Eli Friedmanc3f07642008-08-25 20:46:57 +0000917 if (SubExpr->getType()->isIntegralType()) {
918 // Check for the special-case of a pointer->int->pointer cast;
919 // this isn't standard, but some code requires it. See
920 // PR2720 for an example.
921 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
922 if (SubCast->getSubExpr()->getType()->isPointerType()) {
923 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
924 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
925 if (IntWidth >= PointerWidth) {
926 return CheckAddressConstantExpression(SubCast->getSubExpr());
927 }
928 }
929 }
930 }
931 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +0000932 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +0000933 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000934
935 Diag(Init->getExprLoc(),
936 diag::err_init_element_not_constant, Init->getSourceRange());
937 return true;
938 }
939 case Expr::ConditionalOperatorClass: {
940 // FIXME: Should we pedwarn here?
941 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
942 if (!Exp->getCond()->getType()->isArithmeticType()) {
943 Diag(Init->getExprLoc(),
944 diag::err_init_element_not_constant, Init->getSourceRange());
945 return true;
946 }
947 if (CheckArithmeticConstantExpression(Exp->getCond()))
948 return true;
949 if (Exp->getLHS() &&
950 CheckAddressConstantExpression(Exp->getLHS()))
951 return true;
952 return CheckAddressConstantExpression(Exp->getRHS());
953 }
954 case Expr::AddrLabelExprClass:
955 return false;
956 }
957}
958
Eli Friedman4caf0552008-06-09 05:05:07 +0000959static const Expr* FindExpressionBaseAddress(const Expr* E);
960
961static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
962 switch (E->getStmtClass()) {
963 default:
964 return E;
965 case Expr::ParenExprClass: {
966 const ParenExpr* PE = cast<ParenExpr>(E);
967 return FindExpressionBaseAddressLValue(PE->getSubExpr());
968 }
969 case Expr::MemberExprClass: {
970 const MemberExpr *M = cast<MemberExpr>(E);
971 if (M->isArrow())
972 return FindExpressionBaseAddress(M->getBase());
973 return FindExpressionBaseAddressLValue(M->getBase());
974 }
975 case Expr::ArraySubscriptExprClass: {
976 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
977 return FindExpressionBaseAddress(ASE->getBase());
978 }
979 case Expr::UnaryOperatorClass: {
980 const UnaryOperator *Exp = cast<UnaryOperator>(E);
981
982 if (Exp->getOpcode() == UnaryOperator::Deref)
983 return FindExpressionBaseAddress(Exp->getSubExpr());
984
985 return E;
986 }
987 }
988}
989
990static const Expr* FindExpressionBaseAddress(const Expr* E) {
991 switch (E->getStmtClass()) {
992 default:
993 return E;
994 case Expr::ParenExprClass: {
995 const ParenExpr* PE = cast<ParenExpr>(E);
996 return FindExpressionBaseAddress(PE->getSubExpr());
997 }
998 case Expr::UnaryOperatorClass: {
999 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1000
1001 // C99 6.6p9
1002 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1003 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1004
1005 if (Exp->getOpcode() == UnaryOperator::Extension)
1006 return FindExpressionBaseAddress(Exp->getSubExpr());
1007
1008 return E;
1009 }
1010 case Expr::BinaryOperatorClass: {
1011 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1012
1013 Expr *PExp = Exp->getLHS();
1014 Expr *IExp = Exp->getRHS();
1015 if (IExp->getType()->isPointerType())
1016 std::swap(PExp, IExp);
1017
1018 return FindExpressionBaseAddress(PExp);
1019 }
1020 case Expr::ImplicitCastExprClass: {
1021 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1022
1023 // Check for implicit promotion
1024 if (SubExpr->getType()->isFunctionType() ||
1025 SubExpr->getType()->isArrayType())
1026 return FindExpressionBaseAddressLValue(SubExpr);
1027
1028 // Check for pointer->pointer cast
1029 if (SubExpr->getType()->isPointerType())
1030 return FindExpressionBaseAddress(SubExpr);
1031
1032 // We assume that we have an arithmetic expression here;
1033 // if we don't, we'll figure it out later
1034 return 0;
1035 }
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001036 case Expr::ExplicitCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001037 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1038
1039 // Check for pointer->pointer cast
1040 if (SubExpr->getType()->isPointerType())
1041 return FindExpressionBaseAddress(SubExpr);
1042
1043 // We assume that we have an arithmetic expression here;
1044 // if we don't, we'll figure it out later
1045 return 0;
1046 }
1047 }
1048}
1049
Eli Friedmanc594b322008-05-20 13:48:25 +00001050bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1051 switch (Init->getStmtClass()) {
1052 default:
1053 Diag(Init->getExprLoc(),
1054 diag::err_init_element_not_constant, Init->getSourceRange());
1055 return true;
1056 case Expr::ParenExprClass: {
1057 const ParenExpr* PE = cast<ParenExpr>(Init);
1058 return CheckArithmeticConstantExpression(PE->getSubExpr());
1059 }
1060 case Expr::FloatingLiteralClass:
1061 case Expr::IntegerLiteralClass:
1062 case Expr::CharacterLiteralClass:
1063 case Expr::ImaginaryLiteralClass:
1064 case Expr::TypesCompatibleExprClass:
1065 case Expr::CXXBoolLiteralExprClass:
1066 return false;
1067 case Expr::CallExprClass: {
1068 const CallExpr *CE = cast<CallExpr>(Init);
1069 if (CE->isBuiltinConstantExpr())
1070 return false;
1071 Diag(Init->getExprLoc(),
1072 diag::err_init_element_not_constant, Init->getSourceRange());
1073 return true;
1074 }
1075 case Expr::DeclRefExprClass: {
1076 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1077 if (isa<EnumConstantDecl>(D))
1078 return false;
1079 Diag(Init->getExprLoc(),
1080 diag::err_init_element_not_constant, Init->getSourceRange());
1081 return true;
1082 }
1083 case Expr::CompoundLiteralExprClass:
1084 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1085 // but vectors are allowed to be magic.
1086 if (Init->getType()->isVectorType())
1087 return false;
1088 Diag(Init->getExprLoc(),
1089 diag::err_init_element_not_constant, Init->getSourceRange());
1090 return true;
1091 case Expr::UnaryOperatorClass: {
1092 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1093
1094 switch (Exp->getOpcode()) {
1095 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1096 // See C99 6.6p3.
1097 default:
1098 Diag(Init->getExprLoc(),
1099 diag::err_init_element_not_constant, Init->getSourceRange());
1100 return true;
1101 case UnaryOperator::SizeOf:
1102 case UnaryOperator::AlignOf:
1103 case UnaryOperator::OffsetOf:
1104 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1105 // See C99 6.5.3.4p2 and 6.6p3.
1106 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1107 return false;
1108 Diag(Init->getExprLoc(),
1109 diag::err_init_element_not_constant, Init->getSourceRange());
1110 return true;
1111 case UnaryOperator::Extension:
1112 case UnaryOperator::LNot:
1113 case UnaryOperator::Plus:
1114 case UnaryOperator::Minus:
1115 case UnaryOperator::Not:
1116 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1117 }
1118 }
1119 case Expr::SizeOfAlignOfTypeExprClass: {
1120 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1121 // Special check for void types, which are allowed as an extension
1122 if (Exp->getArgumentType()->isVoidType())
1123 return false;
1124 // alignof always evaluates to a constant.
1125 // FIXME: is sizeof(int[3.0]) a constant expression?
1126 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1127 Diag(Init->getExprLoc(),
1128 diag::err_init_element_not_constant, Init->getSourceRange());
1129 return true;
1130 }
1131 return false;
1132 }
1133 case Expr::BinaryOperatorClass: {
1134 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1135
1136 if (Exp->getLHS()->getType()->isArithmeticType() &&
1137 Exp->getRHS()->getType()->isArithmeticType()) {
1138 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1139 CheckArithmeticConstantExpression(Exp->getRHS());
1140 }
1141
Eli Friedman4caf0552008-06-09 05:05:07 +00001142 if (Exp->getLHS()->getType()->isPointerType() &&
1143 Exp->getRHS()->getType()->isPointerType()) {
1144 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1145 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1146
1147 // Only allow a null (constant integer) base; we could
1148 // allow some additional cases if necessary, but this
1149 // is sufficient to cover offsetof-like constructs.
1150 if (!LHSBase && !RHSBase) {
1151 return CheckAddressConstantExpression(Exp->getLHS()) ||
1152 CheckAddressConstantExpression(Exp->getRHS());
1153 }
1154 }
1155
Eli Friedmanc594b322008-05-20 13:48:25 +00001156 Diag(Init->getExprLoc(),
1157 diag::err_init_element_not_constant, Init->getSourceRange());
1158 return true;
1159 }
1160 case Expr::ImplicitCastExprClass:
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001161 case Expr::ExplicitCastExprClass: {
1162 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001163 if (SubExpr->getType()->isArithmeticType())
1164 return CheckArithmeticConstantExpression(SubExpr);
1165
Eli Friedmanb529d832008-09-02 09:37:00 +00001166 if (SubExpr->getType()->isPointerType()) {
1167 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1168 // If the pointer has a null base, this is an offsetof-like construct
1169 if (!Base)
1170 return CheckAddressConstantExpression(SubExpr);
1171 }
1172
Eli Friedman6d4abe12008-09-01 22:08:17 +00001173 Diag(Init->getExprLoc(),
1174 diag::err_init_element_not_constant, Init->getSourceRange());
1175 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001176 }
1177 case Expr::ConditionalOperatorClass: {
1178 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1179 if (CheckArithmeticConstantExpression(Exp->getCond()))
1180 return true;
1181 if (Exp->getLHS() &&
1182 CheckArithmeticConstantExpression(Exp->getLHS()))
1183 return true;
1184 return CheckArithmeticConstantExpression(Exp->getRHS());
1185 }
1186 }
1187}
1188
1189bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes9a979c32008-07-07 16:46:50 +00001190 Init = Init->IgnoreParens();
1191
Eli Friedmanc594b322008-05-20 13:48:25 +00001192 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1193 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1194 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1195
Nuno Lopes9a979c32008-07-07 16:46:50 +00001196 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1197 return CheckForConstantInitializer(e->getInitializer(), DclT);
1198
Eli Friedmanc594b322008-05-20 13:48:25 +00001199 if (Init->getType()->isReferenceType()) {
1200 // FIXME: Work out how the heck reference types work
1201 return false;
1202#if 0
1203 // A reference is constant if the address of the expression
1204 // is constant
1205 // We look through initlists here to simplify
1206 // CheckAddressConstantExpressionLValue.
1207 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1208 assert(Exp->getNumInits() > 0 &&
1209 "Refernce initializer cannot be empty");
1210 Init = Exp->getInit(0);
1211 }
1212 return CheckAddressConstantExpressionLValue(Init);
1213#endif
1214 }
1215
1216 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1217 unsigned numInits = Exp->getNumInits();
1218 for (unsigned i = 0; i < numInits; i++) {
1219 // FIXME: Need to get the type of the declaration for C++,
1220 // because it could be a reference?
1221 if (CheckForConstantInitializer(Exp->getInit(i),
1222 Exp->getInit(i)->getType()))
1223 return true;
1224 }
1225 return false;
1226 }
1227
1228 if (Init->isNullPointerConstant(Context))
1229 return false;
1230 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001231 QualType InitTy = Context.getCanonicalType(Init->getType())
1232 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001233 if (InitTy == Context.BoolTy) {
1234 // Special handling for pointers implicitly cast to bool;
1235 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1236 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1237 Expr* SubE = ICE->getSubExpr();
1238 if (SubE->getType()->isPointerType() ||
1239 SubE->getType()->isArrayType() ||
1240 SubE->getType()->isFunctionType()) {
1241 return CheckAddressConstantExpression(Init);
1242 }
1243 }
1244 } else if (InitTy->isIntegralType()) {
1245 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001246 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001247 SubE = CE->getSubExpr();
1248 // Special check for pointer cast to int; we allow as an extension
1249 // an address constant cast to an integer if the integer
1250 // is of an appropriate width (this sort of code is apparently used
1251 // in some places).
1252 // FIXME: Add pedwarn?
1253 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1254 if (SubE && (SubE->getType()->isPointerType() ||
1255 SubE->getType()->isArrayType() ||
1256 SubE->getType()->isFunctionType())) {
1257 unsigned IntWidth = Context.getTypeSize(Init->getType());
1258 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1259 if (IntWidth >= PointerWidth)
1260 return CheckAddressConstantExpression(Init);
1261 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001262 }
1263
1264 return CheckArithmeticConstantExpression(Init);
1265 }
1266
1267 if (Init->getType()->isPointerType())
1268 return CheckAddressConstantExpression(Init);
1269
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001270 // An array type at the top level that isn't an init-list must
1271 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001272 if (Init->getType()->isArrayType())
1273 return false;
1274
Nuno Lopes73419bf2008-09-01 18:42:41 +00001275 if (Init->getType()->isFunctionType())
1276 return false;
1277
Eli Friedmanc594b322008-05-20 13:48:25 +00001278 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1279 Init->getSourceRange());
1280 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001281}
1282
Steve Naroffbb204692007-09-12 14:07:44 +00001283void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001284 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001285 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001286 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001287
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001288 // If there is no declaration, there was an error parsing it. Just ignore
1289 // the initializer.
1290 if (RealDecl == 0) {
1291 delete Init;
1292 return;
1293 }
Steve Naroffbb204692007-09-12 14:07:44 +00001294
Steve Naroff410e3e22007-09-12 20:13:48 +00001295 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1296 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001297 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1298 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001299 RealDecl->setInvalidDecl();
1300 return;
1301 }
Steve Naroffbb204692007-09-12 14:07:44 +00001302 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001303 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001304 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001305 if (VDecl->isBlockVarDecl()) {
1306 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001307 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001308 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001309 VDecl->setInvalidDecl();
1310 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +00001311 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001312 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001313
1314 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1315 if (!getLangOptions().CPlusPlus) {
1316 if (SC == VarDecl::Static) // C99 6.7.8p4.
1317 CheckForConstantInitializer(Init, DclT);
1318 }
Steve Naroffbb204692007-09-12 14:07:44 +00001319 }
Steve Naroff248a7532008-04-15 22:42:06 +00001320 } else if (VDecl->isFileVarDecl()) {
1321 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001322 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001323 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +00001324 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001325 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001326
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001327 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1328 if (!getLangOptions().CPlusPlus) {
1329 // C99 6.7.8p4. All file scoped initializers need to be constant.
1330 CheckForConstantInitializer(Init, DclT);
1331 }
Steve Naroffbb204692007-09-12 14:07:44 +00001332 }
1333 // If the type changed, it means we had an incomplete type that was
1334 // completed by the initializer. For example:
1335 // int ary[] = { 1, 3, 5 };
1336 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001337 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001338 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001339 Init->setType(DclT);
1340 }
Steve Naroffbb204692007-09-12 14:07:44 +00001341
1342 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001343 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001344 return;
1345}
1346
Reid Spencer5f016e22007-07-11 17:01:13 +00001347/// The declarators are chained together backwards, reverse the list.
1348Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1349 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001350 Decl *GroupDecl = static_cast<Decl*>(group);
1351 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001352 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001353
1354 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1355 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001356 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001358 else { // reverse the list.
1359 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001360 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001361 Group->setNextDeclarator(NewGroup);
1362 NewGroup = Group;
1363 Group = Next;
1364 }
1365 }
1366 // Perform semantic analysis that depends on having fully processed both
1367 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001368 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001369 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1370 if (!IDecl)
1371 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001372 QualType T = IDecl->getType();
1373
1374 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1375 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001376 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1377 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001378 if (T->isVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001379 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1380 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001381 }
1382 }
1383 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1384 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001385 if (IDecl->isBlockVarDecl() &&
1386 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001387 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001388 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1389 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001390 IDecl->setInvalidDecl();
1391 }
1392 }
1393 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1394 // object that has file scope without an initializer, and without a
1395 // storage-class specifier or with the storage-class specifier "static",
1396 // constitutes a tentative definition. Note: A tentative definition with
1397 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001398 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001399 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001400 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1401 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001402 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001403 // C99 6.9.2p3: If the declaration of an identifier for an object is
1404 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1405 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001406 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1407 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001408 IDecl->setInvalidDecl();
1409 }
1410 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001411 if (IDecl->isFileVarDecl())
1412 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001413 }
1414 return NewGroup;
1415}
Steve Naroffe1223f72007-08-28 03:03:08 +00001416
Chris Lattner04421082008-04-08 04:40:51 +00001417/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1418/// to introduce parameters into function prototype scope.
1419Sema::DeclTy *
1420Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00001421 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001422
1423 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001424 VarDecl::StorageClass StorageClass = VarDecl::None;
1425 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1426 StorageClass = VarDecl::Register;
1427 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00001428 Diag(DS.getStorageClassSpecLoc(),
1429 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001430 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001431 }
1432 if (DS.isThreadSpecified()) {
1433 Diag(DS.getThreadSpecLoc(),
1434 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001435 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001436 }
1437
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001438 // Check that there are no default arguments inside the type of this
1439 // parameter (C++ only).
1440 if (getLangOptions().CPlusPlus)
1441 CheckExtraCXXDefaultArguments(D);
1442
Chris Lattner04421082008-04-08 04:40:51 +00001443 // In this context, we *do not* check D.getInvalidType(). If the declarator
1444 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1445 // though it will not reflect the user specified type.
1446 QualType parmDeclType = GetTypeForDeclarator(D, S);
1447
1448 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1449
Reid Spencer5f016e22007-07-11 17:01:13 +00001450 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1451 // Can this happen for params? We already checked that they don't conflict
1452 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001453 IdentifierInfo *II = D.getIdentifier();
1454 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1455 if (S->isDeclScope(PrevDecl)) {
1456 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1457 dyn_cast<NamedDecl>(PrevDecl)->getName());
1458
1459 // Recover by removing the name
1460 II = 0;
1461 D.SetIdentifier(0, D.getIdentifierLoc());
1462 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001463 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001464
1465 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1466 // Doing the promotion here has a win and a loss. The win is the type for
1467 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1468 // code generator). The loss is the orginal type isn't preserved. For example:
1469 //
1470 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1471 // int blockvardecl[5];
1472 // sizeof(parmvardecl); // size == 4
1473 // sizeof(blockvardecl); // size == 20
1474 // }
1475 //
1476 // For expressions, all implicit conversions are captured using the
1477 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1478 //
1479 // FIXME: If a source translation tool needs to see the original type, then
1480 // we need to consider storing both types (in ParmVarDecl)...
1481 //
Chris Lattnere6327742008-04-02 05:18:44 +00001482 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001483 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001484 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001485 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001486 parmDeclType = Context.getPointerType(parmDeclType);
1487
Chris Lattner04421082008-04-08 04:40:51 +00001488 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1489 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001490 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00001491 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001492
Chris Lattner04421082008-04-08 04:40:51 +00001493 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001494 New->setInvalidDecl();
1495
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001496 if (II)
1497 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001498
Chris Lattner3ff30c82008-06-29 00:02:00 +00001499 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001501
Reid Spencer5f016e22007-07-11 17:01:13 +00001502}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001503
Chris Lattnerb652cea2007-10-09 17:14:05 +00001504Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001505 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00001506 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1507 "Not a function declarator!");
1508 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001509
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1511 // for a K&R function.
1512 if (!FTI.hasPrototype) {
1513 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001514 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1516 FTI.ArgInfo[i].Ident->getName());
1517 // Implicitly declare the argument as type 'int' for lack of a better
1518 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001519 DeclSpec DS;
1520 const char* PrevSpec; // unused
1521 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1522 PrevSpec);
1523 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1524 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1525 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 }
1527 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001529 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 }
1531
1532 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001533
1534 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001535 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001536 GlobalScope);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001537 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1538 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1539 const FunctionDecl *Definition;
1540 if (FD->getBody(Definition)) {
1541 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1542 D.getIdentifier()->getName());
1543 Diag(Definition->getLocation(), diag::err_previous_definition);
1544 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001545 }
1546 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001547
1548 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00001549 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001550}
1551
1552Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1553 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00001554 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattnerb048c982008-04-06 04:47:34 +00001555 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001556
1557 // Check the validity of our function parameters
1558 CheckParmsForFunctionDef(FD);
1559
1560 // Introduce our parameters into the function scope
1561 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1562 ParmVarDecl *Param = FD->getParamDecl(p);
1563 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001564 if (Param->getIdentifier())
1565 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 }
Chris Lattner04421082008-04-08 04:40:51 +00001567
Reid Spencer5f016e22007-07-11 17:01:13 +00001568 return FD;
1569}
1570
Steve Naroffd6d054d2007-11-11 23:20:51 +00001571Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1572 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00001573 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001574 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001575 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00001576 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001577 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00001578 } else
1579 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00001580 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 // Verify and clean out per-function state.
1582
1583 // Check goto/label use.
1584 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1585 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1586 // Verify that we have no forward references left. If so, there was a goto
1587 // or address of a label taken, but no definition of it. Label fwd
1588 // definitions are indicated with a null substmt.
1589 if (I->second->getSubStmt() == 0) {
1590 LabelStmt *L = I->second;
1591 // Emit error.
1592 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1593
1594 // At this point, we have gotos that use the bogus label. Stitch it into
1595 // the function body so that they aren't leaked and that the AST is well
1596 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001597 if (Body) {
1598 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1599 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1600 } else {
1601 // The whole function wasn't parsed correctly, just delete this.
1602 delete L;
1603 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 }
1605 }
1606 LabelMap.clear();
1607
Steve Naroffd6d054d2007-11-11 23:20:51 +00001608 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001609}
1610
Reid Spencer5f016e22007-07-11 17:01:13 +00001611/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1612/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001613ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1614 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001615 // Extension in C99. Legal in C90, but warn about it.
1616 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001617 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001618 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001619 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1620
1621 // FIXME: handle stuff like:
1622 // void foo() { extern float X(); }
1623 // void bar() { X(); } <-- implicit decl for X in another scope.
1624
1625 // Set a Declarator for the implicit definition: int foo();
1626 const char *Dummy;
1627 DeclSpec DS;
1628 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1629 Error = Error; // Silence warning.
1630 assert(!Error && "Error setting up implicit decl!");
1631 Declarator D(DS, Declarator::BlockContext);
1632 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1633 D.SetIdentifier(&II, Loc);
1634
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001635 // Insert this function into translation-unit scope.
1636
1637 DeclContext *PrevDC = CurContext;
1638 CurContext = Context.getTranslationUnitDecl();
1639
Steve Naroffe2ef8152008-04-04 14:32:09 +00001640 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00001641 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001642 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001643
1644 CurContext = PrevDC;
1645
Steve Naroffe2ef8152008-04-04 14:32:09 +00001646 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001647}
1648
1649
Chris Lattner41af0932007-11-14 06:34:38 +00001650TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001651 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001652 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001653 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001654
1655 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001656 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1657 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001658 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001659 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001660 if (D.getInvalidType())
1661 NewTD->setInvalidDecl();
1662 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001663}
1664
Steve Naroff08d92e42007-09-15 18:49:24 +00001665/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001666/// former case, Name will be non-null. In the later case, Name will be null.
1667/// TagType indicates what kind of tag this is. TK indicates whether this is a
1668/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001669Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 SourceLocation KWLoc, IdentifierInfo *Name,
1671 SourceLocation NameLoc, AttributeList *Attr) {
1672 // If this is a use of an existing tag, it must have a name.
1673 assert((Name != 0 || TK == TK_Definition) &&
1674 "Nameless record must be a definition!");
1675
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001676 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00001677 switch (TagType) {
1678 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001679 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1680 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1681 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1682 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001683 }
1684
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001685 // Two code paths: a new one for structs/unions/classes where we create
1686 // separate decls for forward declarations, and an old (eventually to
1687 // be removed) code path for enums.
1688 if (Kind != TagDecl::TK_enum)
1689 return ActOnTagStruct(S, Kind, TK, KWLoc, Name, NameLoc, Attr);
1690
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 // If this is a named struct, check to see if there was a previous forward
1692 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001693 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
Ted Kremenek7e8cc572008-09-02 21:26:19 +00001694 ScopedDecl *PrevDecl =
1695 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
1696
1697 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001698 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1699 "unexpected Decl type");
1700 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00001701 // If this is a use of a previous tag, or if the tag is already declared
1702 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001703 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001704 if (TK == TK_Reference ||
1705 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00001706 // Make sure that this wasn't declared as an enum and now used as a
1707 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001708 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001709 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1710 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00001711 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001712 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00001713 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001714 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00001715 // If this is a use or a forward declaration, we're good.
1716 if (TK != TK_Definition)
1717 return PrevDecl;
1718
1719 // Diagnose attempts to redefine a tag.
1720 if (PrevTagDecl->isDefinition()) {
1721 Diag(NameLoc, diag::err_redefinition, Name->getName());
1722 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1723 // If this is a redefinition, recover by making this struct be
1724 // anonymous, which will make any later references get the previous
1725 // definition.
1726 Name = 0;
1727 } else {
1728 // Okay, this is definition of a previously declared or referenced
1729 // tag. Move the location of the decl to be the definition site.
1730 PrevDecl->setLocation(NameLoc);
1731 return PrevDecl;
1732 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001733 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001734 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001735 // If we get here, this is a definition of a new struct type in a nested
1736 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1737 // type.
1738 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00001739 // PrevDecl is a namespace.
1740 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00001741 // The tag name clashes with a namespace name, issue an error and
1742 // recover by making this tag be anonymous.
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00001743 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1744 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1745 Name = 0;
1746 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001748 }
1749
1750 // If there is an identifier, use the location of the identifier as the
1751 // location of the decl, otherwise use the location of the struct/union
1752 // keyword.
1753 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1754
1755 // Otherwise, if this is the first time we've seen this tag, create the decl.
1756 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001757 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1759 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001760 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001761 // If this is an undefined enum, warn.
1762 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001763 } else {
1764 // struct/union/class
1765
Reid Spencer5f016e22007-07-11 17:01:13 +00001766 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1767 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001768 if (getLangOptions().CPlusPlus)
Ted Kremenekdf042e62008-09-05 01:34:33 +00001769 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001770 else
Ted Kremenekdf042e62008-09-05 01:34:33 +00001771 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001772 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001773
1774 // If this has an identifier, add it to the scope stack.
1775 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001776 // The scope passed in may not be a decl scope. Zip up the scope tree until
1777 // we find one that is.
1778 while ((S->getFlags() & Scope::DeclScope) == 0)
1779 S = S->getParent();
1780
1781 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001782 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001783 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001784
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00001785 if (Attr)
1786 ProcessDeclAttributeList(New, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001787 return New;
1788}
1789
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001790/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
1791/// the logic for enums, we create separate decls for forward declarations.
1792/// This is called by ActOnTag, but eventually will replace its logic.
1793Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
1794 SourceLocation KWLoc, IdentifierInfo *Name,
1795 SourceLocation NameLoc, AttributeList *Attr) {
1796
1797 // If this is a named struct, check to see if there was a previous forward
1798 // declaration or definition.
1799 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1800 ScopedDecl *PrevDecl =
1801 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
1802
1803 if (PrevDecl) {
1804 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1805 "unexpected Decl type");
1806
1807 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1808 // If this is a use of a previous tag, or if the tag is already declared
1809 // in the same scope (so that the definition/declaration completes or
1810 // rementions the tag), reuse the decl.
1811 if (TK == TK_Reference ||
1812 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1813 // Make sure that this wasn't declared as an enum and now used as a
1814 // struct or something similar.
1815 if (PrevTagDecl->getTagKind() != Kind) {
1816 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1817 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1818 // Recover by making this an anonymous redefinition.
1819 Name = 0;
1820 PrevDecl = 0;
1821 } else {
1822 // If this is a use, return the original decl.
1823
1824 // FIXME: In the future, return a variant or some other clue
1825 // for the consumer of this Decl to know it doesn't own it.
1826 // For our current ASTs this shouldn't be a problem, but will
1827 // need to be changed with DeclGroups.
1828 if (TK == TK_Reference)
1829 return PrevDecl;
1830
1831 // The new decl is a definition?
1832 if (TK == TK_Definition) {
1833 // Diagnose attempts to redefine a tag.
1834 if (RecordDecl* DefRecord =
1835 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
1836 Diag(NameLoc, diag::err_redefinition, Name->getName());
1837 Diag(DefRecord->getLocation(), diag::err_previous_definition);
1838 // If this is a redefinition, recover by making this struct be
1839 // anonymous, which will make any later references get the previous
1840 // definition.
1841 Name = 0;
1842 PrevDecl = 0;
1843 }
1844 // Okay, this is definition of a previously declared or referenced
1845 // tag. We're going to create a new Decl.
1846 }
1847 }
1848 // If we get here we have (another) forward declaration. Just create
1849 // a new decl.
1850 }
1851 else {
1852 // If we get here, this is a definition of a new struct type in a nested
1853 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
1854 // new decl/type. We set PrevDecl to NULL so that the Records
1855 // have distinct types.
1856 PrevDecl = 0;
1857 }
1858 } else {
1859 // PrevDecl is a namespace.
1860 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1861 // The tag name clashes with a namespace name, issue an error and
1862 // recover by making this tag be anonymous.
1863 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1864 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1865 Name = 0;
1866 }
1867 }
1868 }
1869
1870 // If there is an identifier, use the location of the identifier as the
1871 // location of the decl, otherwise use the location of the struct/union
1872 // keyword.
1873 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1874
1875 // Otherwise, if this is the first time we've seen this tag, create the decl.
1876 TagDecl *New;
1877
1878 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1879 // struct X { int A; } D; D should chain to X.
1880 if (getLangOptions().CPlusPlus)
1881 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name,
1882 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
1883 else
1884 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name,
1885 dyn_cast_or_null<RecordDecl>(PrevDecl));
1886
1887 // If this has an identifier, add it to the scope stack.
1888 if ((TK == TK_Definition || !PrevDecl) && Name) {
1889 // The scope passed in may not be a decl scope. Zip up the scope tree until
1890 // we find one that is.
1891 while ((S->getFlags() & Scope::DeclScope) == 0)
1892 S = S->getParent();
1893
1894 // Add it to the decl chain.
1895 PushOnScopeChains(New, S);
1896 }
1897
1898 if (Attr)
1899 ProcessDeclAttributeList(New, Attr);
1900
1901 return New;
1902}
1903
1904
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001905/// Collect the instance variables declared in an Objective-C object. Used in
1906/// the creation of structures from objects using the @defs directive.
Ted Kremenek01e67792008-08-20 03:26:33 +00001907static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattner7caeabd2008-07-21 22:17:28 +00001908 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001909 if (Class->getSuperClass())
Ted Kremenek01e67792008-08-20 03:26:33 +00001910 CollectIvars(Class->getSuperClass(), Ctx, ivars);
1911
1912 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremeneka89d1972008-09-03 18:03:35 +00001913 for (ObjCInterfaceDecl::ivar_iterator
1914 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
1915
Ted Kremenek01e67792008-08-20 03:26:33 +00001916 ObjCIvarDecl* ID = *I;
1917 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
1918 ID->getIdentifier(),
1919 ID->getType(),
1920 ID->getBitWidth()));
1921 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001922}
1923
1924/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1925/// instance variables of ClassName into Decls.
1926void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1927 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00001928 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001929 // Check that ClassName is a valid class
1930 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1931 if (!Class) {
1932 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1933 return;
1934 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001935 // Collect the instance variables
Ted Kremenek01e67792008-08-20 03:26:33 +00001936 CollectIvars(Class, Context, Decls);
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001937}
1938
Eli Friedman1b76ada2008-06-03 21:01:11 +00001939QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1940 // This method tries to turn a variable array into a constant
1941 // array even when the size isn't an ICE. This is necessary
1942 // for compatibility with code that depends on gcc's buggy
1943 // constant expression folding, like struct {char x[(int)(char*)2];}
1944 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc44eec62008-07-03 04:20:39 +00001945 APValue Result;
Eli Friedman1b76ada2008-06-03 21:01:11 +00001946 if (VLATy->getSizeExpr() &&
Chris Lattnercf0f51d2008-07-11 19:19:21 +00001947 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
1948 llvm::APSInt &Res = Result.getInt();
1949 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1950 return Context.getConstantArrayType(VLATy->getElementType(),
1951 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00001952 }
1953 }
1954 return QualType();
1955}
1956
Steve Naroff08d92e42007-09-15 18:49:24 +00001957/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001958/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001959Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001960 SourceLocation DeclStart,
1961 Declarator &D, ExprTy *BitfieldWidth) {
1962 IdentifierInfo *II = D.getIdentifier();
1963 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001964 SourceLocation Loc = DeclStart;
1965 if (II) Loc = D.getIdentifierLoc();
1966
1967 // FIXME: Unnamed fields can be handled in various different ways, for
1968 // example, unnamed unions inject all members into the struct namespace!
Ted Kremeneka89d1972008-09-03 18:03:35 +00001969
Reid Spencer5f016e22007-07-11 17:01:13 +00001970 if (BitWidth) {
1971 // TODO: Validate.
1972 //printf("WARNING: BITFIELDS IGNORED!\n");
1973
1974 // 6.7.2.1p3
1975 // 6.7.2.1p4
1976
1977 } else {
1978 // Not a bitfield.
1979
1980 // validate II.
1981
1982 }
1983
1984 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001985 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1986 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001987
Reid Spencer5f016e22007-07-11 17:01:13 +00001988 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1989 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001990 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00001991 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1992 if (!FixedTy.isNull()) {
1993 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1994 T = FixedTy;
1995 } else {
1996 // FIXME: This diagnostic needs work
1997 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1998 InvalidDecl = true;
1999 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002000 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002001 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002002 FieldDecl *NewFD;
2003
2004 if (getLangOptions().CPlusPlus) {
2005 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2006 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2007 Loc, II, T, BitWidth);
2008 if (II)
2009 PushOnScopeChains(NewFD, S);
2010 }
2011 else
2012 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00002013
Chris Lattner3ff30c82008-06-29 00:02:00 +00002014 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002015
Steve Naroff5912a352007-08-28 20:14:24 +00002016 if (D.getInvalidType() || InvalidDecl)
2017 NewFD->setInvalidDecl();
2018 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002019}
2020
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002021/// TranslateIvarVisibility - Translate visibility from a token ID to an
2022/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002023static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002024TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002025 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002026 case tok::objc_private: return ObjCIvarDecl::Private;
2027 case tok::objc_public: return ObjCIvarDecl::Public;
2028 case tok::objc_protected: return ObjCIvarDecl::Protected;
2029 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002030 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00002031 }
2032}
2033
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002034/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2035/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002036Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002037 SourceLocation DeclStart,
2038 Declarator &D, ExprTy *BitfieldWidth,
2039 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002040 IdentifierInfo *II = D.getIdentifier();
2041 Expr *BitWidth = (Expr*)BitfieldWidth;
2042 SourceLocation Loc = DeclStart;
2043 if (II) Loc = D.getIdentifierLoc();
2044
2045 // FIXME: Unnamed fields can be handled in various different ways, for
2046 // example, unnamed unions inject all members into the struct namespace!
2047
2048
2049 if (BitWidth) {
2050 // TODO: Validate.
2051 //printf("WARNING: BITFIELDS IGNORED!\n");
2052
2053 // 6.7.2.1p3
2054 // 6.7.2.1p4
2055
2056 } else {
2057 // Not a bitfield.
2058
2059 // validate II.
2060
2061 }
2062
2063 QualType T = GetTypeForDeclarator(D, S);
2064 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2065 bool InvalidDecl = false;
2066
2067 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2068 // than a variably modified type.
2069 if (T->isVariablyModifiedType()) {
2070 // FIXME: This diagnostic needs work
2071 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2072 InvalidDecl = true;
2073 }
2074
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002075 // Get the visibility (access control) for this ivar.
2076 ObjCIvarDecl::AccessControl ac =
2077 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2078 : ObjCIvarDecl::None;
2079
2080 // Construct the decl.
2081 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002082 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002083
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002084 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002085 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002086
2087 if (D.getInvalidType() || InvalidDecl)
2088 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002089
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002090 return NewID;
2091}
2092
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002093void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002094 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002095 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002096 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00002097 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2098 assert(EnclosingDecl && "missing record or interface decl");
2099 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2100
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002101 if (Record)
2102 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2103 // Diagnose code like:
2104 // struct S { struct S {} X; };
2105 // We discover this when we complete the outer S. Reject and ignore the
2106 // outer S.
2107 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2108 DefRecord->getKindName());
2109 Diag(RecLoc, diag::err_previous_definition);
2110 Record->setInvalidDecl();
2111 return;
2112 }
2113
Reid Spencer5f016e22007-07-11 17:01:13 +00002114 // Verify that all the fields are okay.
2115 unsigned NumNamedMembers = 0;
2116 llvm::SmallVector<FieldDecl*, 32> RecFields;
2117 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002118
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002120
Steve Naroff74216642007-09-14 22:20:54 +00002121 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2122 assert(FD && "missing field decl");
2123
2124 // Remember all fields.
2125 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002126
2127 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002128 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002129
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002131 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00002132 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002134 FD->setInvalidDecl();
2135 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002136 continue;
2137 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002138 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2139 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002140 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002141 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002142 FD->setInvalidDecl();
2143 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002144 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002145 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002146 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002147 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002148 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002149 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002150 FD->setInvalidDecl();
2151 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002152 continue;
2153 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002154 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002155 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2156 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002157 FD->setInvalidDecl();
2158 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002159 continue;
2160 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002161 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002162 if (Record)
2163 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002164 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002165 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2166 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002167 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002168 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2169 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002170 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002171 Record->setHasFlexibleArrayMember(true);
2172 } else {
2173 // If this is a struct/class and this is not the last element, reject
2174 // it. Note that GCC supports variable sized arrays in the middle of
2175 // structures.
2176 if (i != NumFields-1) {
2177 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2178 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002179 FD->setInvalidDecl();
2180 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002181 continue;
2182 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002183 // We support flexible arrays at the end of structs in other structs
2184 // as an extension.
2185 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2186 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002187 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002188 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002189 }
2190 }
2191 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002192 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002193 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002194 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2195 FD->getName());
2196 FD->setInvalidDecl();
2197 EnclosingDecl->setInvalidDecl();
2198 continue;
2199 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002200 // Keep track of the number of named members.
2201 if (IdentifierInfo *II = FD->getIdentifier()) {
2202 // Detect duplicate member names.
2203 if (!FieldIDs.insert(II)) {
2204 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2205 // Find the previous decl.
2206 SourceLocation PrevLoc;
2207 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2208 assert(i != e && "Didn't find previous def!");
2209 if (RecFields[i]->getIdentifier() == II) {
2210 PrevLoc = RecFields[i]->getLocation();
2211 break;
2212 }
2213 }
2214 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002215 FD->setInvalidDecl();
2216 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002217 continue;
2218 }
2219 ++NumNamedMembers;
2220 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002221 }
2222
Reid Spencer5f016e22007-07-11 17:01:13 +00002223 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002224 if (Record) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002225 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00002226 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2227 // Sema::ActOnFinishCXXClassDef.
2228 if (!isa<CXXRecordDecl>(Record))
2229 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00002230 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002231 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2232 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2233 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2234 else if (ObjCImplementationDecl *IMPDecl =
2235 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002236 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2237 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002238 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002239 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002240 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002241}
2242
Steve Naroff08d92e42007-09-15 18:49:24 +00002243Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002244 DeclTy *lastEnumConst,
2245 SourceLocation IdLoc, IdentifierInfo *Id,
2246 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002247 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002248 EnumConstantDecl *LastEnumConst =
2249 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2250 Expr *Val = static_cast<Expr*>(val);
2251
Chris Lattner31e05722007-08-26 06:24:45 +00002252 // The scope passed in may not be a decl scope. Zip up the scope tree until
2253 // we find one that is.
2254 while ((S->getFlags() & Scope::DeclScope) == 0)
2255 S = S->getParent();
2256
Reid Spencer5f016e22007-07-11 17:01:13 +00002257 // Verify that there isn't already something declared with this name in this
2258 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002259 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002260 // When in C++, we may get a TagDecl with the same name; in this case the
2261 // enum constant will 'hide' the tag.
2262 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2263 "Received TagDecl when not in C++!");
2264 if (!isa<TagDecl>(PrevDecl) &&
2265 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002266 if (isa<EnumConstantDecl>(PrevDecl))
2267 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2268 else
2269 Diag(IdLoc, diag::err_redefinition, Id->getName());
2270 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002271 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002272 return 0;
2273 }
2274 }
2275
2276 llvm::APSInt EnumVal(32);
2277 QualType EltTy;
2278 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002279 // Make sure to promote the operand type to int.
2280 UsualUnaryConversions(Val);
2281
Reid Spencer5f016e22007-07-11 17:01:13 +00002282 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2283 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002284 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002285 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2286 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002287 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002288 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002289 } else {
2290 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002291 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002292 }
2293
2294 if (!Val) {
2295 if (LastEnumConst) {
2296 // Assign the last value + 1.
2297 EnumVal = LastEnumConst->getInitVal();
2298 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002299
2300 // Check for overflow on increment.
2301 if (EnumVal < LastEnumConst->getInitVal())
2302 Diag(IdLoc, diag::warn_enum_value_overflow);
2303
Chris Lattnerb7416f92007-08-27 17:37:24 +00002304 EltTy = LastEnumConst->getType();
2305 } else {
2306 // First value, set to zero.
2307 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002308 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002309 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002310 }
2311
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002312 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002313 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2314 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002315 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002316
2317 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002318 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002319 return New;
2320}
2321
Steve Naroff02408c62008-08-07 14:08:16 +00002322// FIXME: For consistency with ActOnFields(), we should have the parser
2323// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00002324void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002325 DeclTy **Elements, unsigned NumElements) {
2326 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00002327
Steve Naroff02408c62008-08-07 14:08:16 +00002328 if (Enum && Enum->isDefinition()) {
2329 // Diagnose code like:
2330 // enum e0 {
2331 // E0 = sizeof(enum e0 { E1 })
2332 // };
2333 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2334 Enum->getName());
2335 Diag(EnumLoc, diag::err_previous_definition);
2336 Enum->setInvalidDecl();
2337 return;
2338 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00002339 // TODO: If the result value doesn't fit in an int, it must be a long or long
2340 // long value. ISO C does not support this, but GCC does as an extension,
2341 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002342 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002343
Chris Lattnerac609682007-08-28 06:15:15 +00002344 // Verify that all the values are okay, compute the size of the values, and
2345 // reverse the list.
2346 unsigned NumNegativeBits = 0;
2347 unsigned NumPositiveBits = 0;
2348
2349 // Keep track of whether all elements have type int.
2350 bool AllElementsInt = true;
2351
Reid Spencer5f016e22007-07-11 17:01:13 +00002352 EnumConstantDecl *EltList = 0;
2353 for (unsigned i = 0; i != NumElements; ++i) {
2354 EnumConstantDecl *ECD =
2355 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2356 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002357
2358 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002359 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002360 assert(InitVal.getBitWidth() >= IntWidth &&
2361 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002362 if (InitVal.getBitWidth() > IntWidth) {
2363 llvm::APSInt V(InitVal);
2364 V.trunc(IntWidth);
2365 V.extend(InitVal.getBitWidth());
2366 if (V != InitVal)
2367 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattner9aa77f12008-08-17 07:19:51 +00002368 InitVal.toString(10));
Chris Lattner211a30e2007-08-28 05:27:00 +00002369 }
Chris Lattnerac609682007-08-28 06:15:15 +00002370
2371 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002372 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002373 NumPositiveBits = std::max(NumPositiveBits,
2374 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002375 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002376 NumNegativeBits = std::max(NumNegativeBits,
2377 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002378
Chris Lattnerac609682007-08-28 06:15:15 +00002379 // Keep track of whether every enum element has type int (very commmon).
2380 if (AllElementsInt)
2381 AllElementsInt = ECD->getType() == Context.IntTy;
2382
Reid Spencer5f016e22007-07-11 17:01:13 +00002383 ECD->setNextDeclarator(EltList);
2384 EltList = ECD;
2385 }
2386
Chris Lattnerac609682007-08-28 06:15:15 +00002387 // Figure out the type that should be used for this enum.
2388 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2389 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002390 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002391
2392 if (NumNegativeBits) {
2393 // If there is a negative value, figure out the smallest integer type (of
2394 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002395 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002396 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002397 BestWidth = IntWidth;
2398 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002399 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002400
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002401 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002402 BestType = Context.LongTy;
2403 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002404 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002405
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002406 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002407 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2408 BestType = Context.LongLongTy;
2409 }
2410 }
2411 } else {
2412 // If there is no negative value, figure out which of uint, ulong, ulonglong
2413 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002414 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002415 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002416 BestWidth = IntWidth;
2417 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002418 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002419 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002420 } else {
2421 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002422 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002423 "How could an initializer get larger than ULL?");
2424 BestType = Context.UnsignedLongLongTy;
2425 }
2426 }
2427
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002428 // Loop over all of the enumerator constants, changing their types to match
2429 // the type of the enum if needed.
2430 for (unsigned i = 0; i != NumElements; ++i) {
2431 EnumConstantDecl *ECD =
2432 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2433 if (!ECD) continue; // Already issued a diagnostic.
2434
2435 // Standard C says the enumerators have int type, but we allow, as an
2436 // extension, the enumerators to be larger than int size. If each
2437 // enumerator value fits in an int, type it as an int, otherwise type it the
2438 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2439 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002440 if (ECD->getType() == Context.IntTy) {
2441 // Make sure the init value is signed.
2442 llvm::APSInt IV = ECD->getInitVal();
2443 IV.setIsSigned(true);
2444 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002445 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002446 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002447
2448 // Determine whether the value fits into an int.
2449 llvm::APSInt InitVal = ECD->getInitVal();
2450 bool FitsInInt;
2451 if (InitVal.isUnsigned() || !InitVal.isNegative())
2452 FitsInInt = InitVal.getActiveBits() < IntWidth;
2453 else
2454 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2455
2456 // If it fits into an integer type, force it. Otherwise force it to match
2457 // the enum decl type.
2458 QualType NewTy;
2459 unsigned NewWidth;
2460 bool NewSign;
2461 if (FitsInInt) {
2462 NewTy = Context.IntTy;
2463 NewWidth = IntWidth;
2464 NewSign = true;
2465 } else if (ECD->getType() == BestType) {
2466 // Already the right type!
2467 continue;
2468 } else {
2469 NewTy = BestType;
2470 NewWidth = BestWidth;
2471 NewSign = BestType->isSignedIntegerType();
2472 }
2473
2474 // Adjust the APSInt value.
2475 InitVal.extOrTrunc(NewWidth);
2476 InitVal.setIsSigned(NewSign);
2477 ECD->setInitVal(InitVal);
2478
2479 // Adjust the Expr initializer and type.
2480 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2481 ECD->setType(NewTy);
2482 }
Chris Lattnerac609682007-08-28 06:15:15 +00002483
Chris Lattnere00b18c2007-08-28 18:24:31 +00002484 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002485 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002486}
2487
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002488Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2489 ExprTy *expr) {
2490 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2491
Chris Lattner8e25d862008-03-16 00:16:02 +00002492 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002493}
2494
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002495Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002496 SourceLocation LBrace,
2497 SourceLocation RBrace,
2498 const char *Lang,
2499 unsigned StrSize,
2500 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002501 LinkageSpecDecl::LanguageIDs Language;
2502 Decl *dcl = static_cast<Decl *>(D);
2503 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2504 Language = LinkageSpecDecl::lang_c;
2505 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2506 Language = LinkageSpecDecl::lang_cxx;
2507 else {
2508 Diag(Loc, diag::err_bad_language);
2509 return 0;
2510 }
2511
2512 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002513 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002514}