blob: b792b525cc494417c66ea7ebc2b59b0fec41d9fb [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Builtins.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/Type.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Parse/Scope.h"
22#include "clang/Lex/IdentifierTable.h"
23#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
25#include "llvm/ADT/SmallSet.h"
26using namespace clang;
27
Reid Spencer5f016e22007-07-11 17:01:13 +000028Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Steve Naroff3536b442007-09-06 21:24:23 +000029 Decl *IIDecl = II.getFETokenInfo<Decl>();
30 if (dyn_cast_or_null<TypedefDecl>(IIDecl) ||
31 dyn_cast_or_null<ObjcInterfaceDecl>(IIDecl))
32 return IIDecl;
33 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000034}
35
36void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000037 if (S->decl_empty()) return;
38 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
39
Reid Spencer5f016e22007-07-11 17:01:13 +000040 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
41 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000042 Decl *TmpD = static_cast<Decl*>(*I);
43 assert(TmpD && "This decl didn't get pushed??");
44 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
45 assert(D && "This decl isn't a ScopedDecl?");
46
Reid Spencer5f016e22007-07-11 17:01:13 +000047 IdentifierInfo *II = D->getIdentifier();
48 if (!II) continue;
49
50 // Unlink this decl from the identifier. Because the scope contains decls
51 // in an unordered collection, and because we have multiple identifier
52 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
53 if (II->getFETokenInfo<Decl>() == D) {
54 // Normal case, no multiple decls in different namespaces.
55 II->setFETokenInfo(D->getNext());
56 } else {
57 // Scan ahead. There are only three namespaces in C, so this loop can
58 // never execute more than 3 times.
Steve Naroffc752d042007-09-13 18:10:37 +000059 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +000060 while (SomeDecl->getNext() != D) {
61 SomeDecl = SomeDecl->getNext();
62 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
63 }
64 SomeDecl->setNext(D->getNext());
65 }
66
67 // This will have to be revisited for C++: there we want to nest stuff in
68 // namespace decls etc. Even for C, we might want a top-level translation
69 // unit decl or something.
70 if (!CurFunctionDecl)
71 continue;
72
73 // Chain this decl to the containing function, it now owns the memory for
74 // the decl.
75 D->setNext(CurFunctionDecl->getDeclChain());
76 CurFunctionDecl->setDeclChain(D);
77 }
78}
79
80/// LookupScopedDecl - Look up the inner-most declaration in the specified
81/// namespace.
Steve Naroffc752d042007-09-13 18:10:37 +000082ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
83 SourceLocation IdLoc, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +000084 if (II == 0) return 0;
85 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
86
87 // Scan up the scope chain looking for a decl that matches this identifier
88 // that is in the appropriate namespace. This search should not take long, as
89 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffc752d042007-09-13 18:10:37 +000090 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +000091 if (D->getIdentifierNamespace() == NS)
92 return D;
93
94 // If we didn't find a use of this identifier, and if the identifier
95 // corresponds to a compiler builtin, create the decl object for the builtin
96 // now, injecting it into translation unit scope, and return it.
97 if (NS == Decl::IDNS_Ordinary) {
98 // If this is a builtin on some other target, or if this builtin varies
99 // across targets (e.g. in type), emit a diagnostic and mark the translation
100 // unit non-portable for using it.
101 if (II->isNonPortableBuiltin()) {
102 // Only emit this diagnostic once for this builtin.
103 II->setNonPortableBuiltin(false);
104 Context.Target.DiagnoseNonPortability(IdLoc,
105 diag::port_target_builtin_use);
106 }
107 // If this is a builtin on this (or all) targets, create the decl.
108 if (unsigned BuiltinID = II->getBuiltinID())
109 return LazilyCreateBuiltin(II, BuiltinID, S);
110 }
111 return 0;
112}
113
114/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
115/// lazily create a decl for it.
Steve Naroffc752d042007-09-13 18:10:37 +0000116ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 Builtin::ID BID = (Builtin::ID)bid;
118
119 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
120 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000121 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000122
123 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000124 if (Scope *FnS = S->getFnParent())
125 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000126 while (S->getParent())
127 S = S->getParent();
128 S->AddDecl(New);
129
130 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000131 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 // Scan until we find the last (outermost) decl in the id chain.
133 while (LastDecl->getNext())
134 LastDecl = LastDecl->getNext();
135 // Insert before (outside) it.
136 LastDecl->setNext(New);
137 } else {
138 II->setFETokenInfo(New);
139 }
140 // Make sure clients iterating over decls see this.
141 LastInGroupList.push_back(New);
142
143 return New;
144}
145
146/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
147/// and scope as a previous declaration 'Old'. Figure out how to resolve this
148/// situation, merging decls or emitting diagnostics as appropriate.
149///
Steve Naroff8e74c932007-09-13 21:41:19 +0000150TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000151 // Verify the old decl was also a typedef.
152 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
153 if (!Old) {
154 Diag(New->getLocation(), diag::err_redefinition_different_kind,
155 New->getName());
156 Diag(OldD->getLocation(), diag::err_previous_definition);
157 return New;
158 }
159
160 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
161 // TODO: This is totally simplistic. It should handle merging functions
162 // together etc, merging extern int X; int X; ...
163 Diag(New->getLocation(), diag::err_redefinition, New->getName());
164 Diag(Old->getLocation(), diag::err_previous_definition);
165 return New;
166}
167
168/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
169/// and scope as a previous declaration 'Old'. Figure out how to resolve this
170/// situation, merging decls or emitting diagnostics as appropriate.
171///
Steve Naroff8e74c932007-09-13 21:41:19 +0000172FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000173 // Verify the old decl was also a function.
174 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
175 if (!Old) {
176 Diag(New->getLocation(), diag::err_redefinition_different_kind,
177 New->getName());
178 Diag(OldD->getLocation(), diag::err_previous_definition);
179 return New;
180 }
181
182 // This is not right, but it's a start. If 'Old' is a function prototype with
183 // the same type as 'New', silently allow this. FIXME: We should link up decl
184 // objects here.
185 if (Old->getBody() == 0 &&
186 Old->getCanonicalType() == New->getCanonicalType()) {
187 return New;
188 }
189
190 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
191 // TODO: This is totally simplistic. It should handle merging functions
192 // together etc, merging extern int X; int X; ...
193 Diag(New->getLocation(), diag::err_redefinition, New->getName());
194 Diag(Old->getLocation(), diag::err_previous_definition);
195 return New;
196}
197
198/// MergeVarDecl - We just parsed a variable 'New' which has the same name
199/// and scope as a previous declaration 'Old'. Figure out how to resolve this
200/// situation, merging decls or emitting diagnostics as appropriate.
201///
202/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
203/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
204///
Steve Naroff8e74c932007-09-13 21:41:19 +0000205VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 // Verify the old decl was also a variable.
207 VarDecl *Old = dyn_cast<VarDecl>(OldD);
208 if (!Old) {
209 Diag(New->getLocation(), diag::err_redefinition_different_kind,
210 New->getName());
211 Diag(OldD->getLocation(), diag::err_previous_definition);
212 return New;
213 }
Steve Narofffb22d962007-08-30 01:06:46 +0000214 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
215 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
216 bool OldIsTentative = false;
217
218 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
219 // Handle C "tentative" external object definitions. FIXME: finish!
220 if (!OldFSDecl->getInit() &&
221 (OldFSDecl->getStorageClass() == VarDecl::None ||
222 OldFSDecl->getStorageClass() == VarDecl::Static))
223 OldIsTentative = true;
224 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000225 // Verify the types match.
226 if (Old->getCanonicalType() != New->getCanonicalType()) {
227 Diag(New->getLocation(), diag::err_redefinition, New->getName());
228 Diag(Old->getLocation(), diag::err_previous_definition);
229 return New;
230 }
231 // We've verified the types match, now check if Old is "extern".
232 if (Old->getStorageClass() != VarDecl::Extern) {
233 Diag(New->getLocation(), diag::err_redefinition, New->getName());
234 Diag(Old->getLocation(), diag::err_previous_definition);
235 }
236 return New;
237}
238
239/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
240/// no declarator (e.g. "struct foo;") is parsed.
241Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
242 // TODO: emit error on 'int;' or 'const enum foo;'.
243 // TODO: emit error on 'typedef int;'
244 // if (!DS.isMissingDeclaratorOk()) Diag(...);
245
246 return 0;
247}
248
Steve Naroff9e8925e2007-09-04 14:36:54 +0000249bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000250 AssignmentCheckResult result;
251 SourceLocation loc = Init->getLocStart();
252 // Get the type before calling CheckSingleAssignmentConstraints(), since
253 // it can promote the expression.
254 QualType rhsType = Init->getType();
255
256 result = CheckSingleAssignmentConstraints(DeclType, Init);
257
258 // decode the result (notice that extensions still return a type).
259 switch (result) {
260 case Compatible:
261 break;
262 case Incompatible:
Steve Naroff6f9f3072007-09-02 15:34:30 +0000263 // FIXME: tighten up this check which should allow:
264 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
265 if (rhsType == Context.getPointerType(Context.CharTy))
266 break;
Steve Narofff0090632007-09-02 02:04:30 +0000267 Diag(loc, diag::err_typecheck_assign_incompatible,
268 DeclType.getAsString(), rhsType.getAsString(),
269 Init->getSourceRange());
270 return true;
271 case PointerFromInt:
272 // check for null pointer constant (C99 6.3.2.3p3)
273 if (!Init->isNullPointerConstant(Context)) {
274 Diag(loc, diag::ext_typecheck_assign_pointer_int,
275 DeclType.getAsString(), rhsType.getAsString(),
276 Init->getSourceRange());
277 return true;
278 }
279 break;
280 case IntFromPointer:
281 Diag(loc, diag::ext_typecheck_assign_pointer_int,
282 DeclType.getAsString(), rhsType.getAsString(),
283 Init->getSourceRange());
284 break;
285 case IncompatiblePointer:
286 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
287 DeclType.getAsString(), rhsType.getAsString(),
288 Init->getSourceRange());
289 break;
290 case CompatiblePointerDiscardsQualifiers:
291 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
292 DeclType.getAsString(), rhsType.getAsString(),
293 Init->getSourceRange());
294 break;
295 }
296 return false;
297}
298
Steve Naroff9e8925e2007-09-04 14:36:54 +0000299bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
300 bool isStatic, QualType ElementType) {
Steve Naroff371227d2007-09-04 02:20:04 +0000301 SourceLocation loc;
Steve Naroff9e8925e2007-09-04 14:36:54 +0000302 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff371227d2007-09-04 02:20:04 +0000303
304 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
305 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
306 return true;
307 } else if (CheckSingleInitializer(expr, ElementType)) {
308 return true; // types weren't compatible.
309 }
Steve Naroff9e8925e2007-09-04 14:36:54 +0000310 if (savExpr != expr) // The type was promoted, update initializer list.
311 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000312 return false;
313}
314
315void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
316 QualType ElementType, bool isStatic,
317 int &nInitializers, bool &hadError) {
Steve Naroff6f9f3072007-09-02 15:34:30 +0000318 for (unsigned i = 0; i < IList->getNumInits(); i++) {
319 Expr *expr = IList->getInit(i);
320
Steve Naroff371227d2007-09-04 02:20:04 +0000321 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
322 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000323 int maxElements = CAT->getMaximumElements();
Steve Naroff371227d2007-09-04 02:20:04 +0000324 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
325 maxElements, hadError);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000326 }
Steve Naroff371227d2007-09-04 02:20:04 +0000327 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000328 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000329 }
Steve Naroff371227d2007-09-04 02:20:04 +0000330 nInitializers++;
331 }
332 return;
333}
334
335// FIXME: Doesn't deal with arrays of structures yet.
336void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
337 QualType ElementType, bool isStatic,
338 int &totalInits, bool &hadError) {
339 int maxElementsAtThisLevel = 0;
340 int nInitsAtLevel = 0;
341
342 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
343 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff7cf8c442007-09-04 21:13:33 +0000344 maxElementsAtThisLevel = CAT->getMaximumElements();
345 // Set DeclType, used below to recurse (for multi-dimensional arrays).
346 DeclType = CAT->getElementType();
Steve Naroff371227d2007-09-04 02:20:04 +0000347 } else if (DeclType->isScalarType()) {
348 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
349 IList->getSourceRange());
350 maxElementsAtThisLevel = 1;
351 }
352 // The empty init list "{ }" is treated specially below.
353 unsigned numInits = IList->getNumInits();
354 if (numInits) {
355 for (unsigned i = 0; i < numInits; i++) {
356 Expr *expr = IList->getInit(i);
357
358 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
359 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
360 totalInits, hadError);
361 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000362 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff371227d2007-09-04 02:20:04 +0000363 nInitsAtLevel++; // increment the number of initializers at this level.
364 totalInits--; // decrement the total number of initializers.
365
366 // Check if we have space for another initializer.
367 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
368 Diag(expr->getLocStart(), diag::warn_excess_initializers,
369 expr->getSourceRange());
370 }
371 }
372 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
373 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
374 } else {
375 // we have an initializer list with no elements.
376 totalInits -= maxElementsAtThisLevel;
377 if (totalInits < 0)
378 Diag(IList->getLocStart(), diag::warn_excess_initializers,
379 IList->getSourceRange());
Steve Naroff6f9f3072007-09-02 15:34:30 +0000380 }
Steve Naroffd35005e2007-09-03 01:24:23 +0000381 return;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000382}
383
Steve Naroff9e8925e2007-09-04 14:36:54 +0000384bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Narofff0090632007-09-02 02:04:30 +0000385 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroffd35005e2007-09-03 01:24:23 +0000386 if (!InitList)
387 return CheckSingleInitializer(Init, DeclType);
388
Steve Narofff0090632007-09-02 02:04:30 +0000389 // We have an InitListExpr, make sure we set the type.
390 Init->setType(DeclType);
Steve Naroffd35005e2007-09-03 01:24:23 +0000391
392 bool hadError = false;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000393
Steve Naroff38374b02007-09-02 20:30:18 +0000394 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
395 // of unknown size ("[]") or an object type that is not a variable array type.
396 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
397 Expr *expr = VAT->getSizeExpr();
Steve Naroffd35005e2007-09-03 01:24:23 +0000398 if (expr)
399 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
400 expr->getSourceRange());
401
Steve Naroff7cf8c442007-09-04 21:13:33 +0000402 // We have a VariableArrayType with unknown size. Note that only the first
403 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff371227d2007-09-04 02:20:04 +0000404 int numInits = 0;
Steve Naroff7cf8c442007-09-04 21:13:33 +0000405 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
406 isStatic, numInits, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000407 if (!hadError) {
408 // Return a new array type from the number of initializers (C99 6.7.8p22).
409 llvm::APSInt ConstVal(32);
Steve Naroff371227d2007-09-04 02:20:04 +0000410 ConstVal = numInits;
411 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroffd35005e2007-09-03 01:24:23 +0000412 ArrayType::Normal, 0);
413 }
414 return hadError;
415 }
416 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000417 int maxElements = CAT->getMaximumElements();
418 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
419 isStatic, maxElements, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000420 return hadError;
421 }
Steve Naroff371227d2007-09-04 02:20:04 +0000422 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
423 int maxElements = 1;
424 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
425 hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000426 return hadError;
Steve Naroff38374b02007-09-02 20:30:18 +0000427 }
428 // FIXME: Handle struct/union types.
Steve Naroffd35005e2007-09-03 01:24:23 +0000429 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +0000430}
431
Reid Spencer5f016e22007-07-11 17:01:13 +0000432Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000433Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000434 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000435 IdentifierInfo *II = D.getIdentifier();
436
Chris Lattnere80a59c2007-07-25 00:24:17 +0000437 // All of these full declarators require an identifier. If it doesn't have
438 // one, the ParsedFreeStandingDeclSpec action should be used.
439 if (II == 0) {
Chris Lattner98e08632007-08-28 06:17:15 +0000440 Diag(D.getDeclSpec().getSourceRange().Begin(),
441 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000442 D.getDeclSpec().getSourceRange(), D.getSourceRange());
443 return 0;
444 }
445
Chris Lattner31e05722007-08-26 06:24:45 +0000446 // The scope passed in may not be a decl scope. Zip up the scope tree until
447 // we find one that is.
448 while ((S->getFlags() & Scope::DeclScope) == 0)
449 S = S->getParent();
450
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000452 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
453 D.getIdentifierLoc(), S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 if (PrevDecl && !S->isDeclScope(PrevDecl))
455 PrevDecl = 0; // If in outer scope, it isn't the same thing.
456
Steve Naroffc752d042007-09-13 18:10:37 +0000457 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000458 bool InvalidDecl = false;
459
Reid Spencer5f016e22007-07-11 17:01:13 +0000460 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
461 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
462 if (!NewTD) return 0;
463
464 // Handle attributes prior to checking for duplicates in MergeVarDecl
465 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
466 D.getAttributes());
467 // Merge the decl with the existing one if appropriate.
468 if (PrevDecl) {
469 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
470 if (NewTD == 0) return 0;
471 }
472 New = NewTD;
473 if (S->getParent() == 0) {
474 // C99 6.7.7p2: If a typedef name specifies a variably modified type
475 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000476 if (const VariableArrayType *VAT =
477 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
478 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
479 VAT->getSizeExpr()->getSourceRange());
480 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000481 }
482 }
483 } else if (D.isFunctionDeclarator()) {
484 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000485 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000486
Reid Spencer5f016e22007-07-11 17:01:13 +0000487 FunctionDecl::StorageClass SC;
488 switch (D.getDeclSpec().getStorageClassSpec()) {
489 default: assert(0 && "Unknown storage class!");
490 case DeclSpec::SCS_auto:
491 case DeclSpec::SCS_register:
492 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
493 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000494 InvalidDecl = true;
495 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000496 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
497 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
498 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
499 }
500
501 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000502 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000503 LastDeclarator);
504
505 // Merge the decl with the existing one if appropriate.
506 if (PrevDecl) {
507 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
508 if (NewFD == 0) return 0;
509 }
510 New = NewFD;
511 } else {
512 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff53a32342007-08-28 18:45:29 +0000513 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000514
515 VarDecl *NewVD;
516 VarDecl::StorageClass SC;
517 switch (D.getDeclSpec().getStorageClassSpec()) {
518 default: assert(0 && "Unknown storage class!");
519 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
520 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
521 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
522 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
523 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
524 }
525 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000526 // C99 6.9p2: The storage-class specifiers auto and register shall not
527 // appear in the declaration specifiers in an external declaration.
528 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
529 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
530 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000531 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000533 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000534 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000535 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000536 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000537 // Handle attributes prior to checking for duplicates in MergeVarDecl
538 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
539 D.getAttributes());
540
541 // Merge the decl with the existing one if appropriate.
542 if (PrevDecl) {
543 NewVD = MergeVarDecl(NewVD, PrevDecl);
544 if (NewVD == 0) return 0;
545 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 New = NewVD;
547 }
548
549 // If this has an identifier, add it to the scope stack.
550 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000551 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000552 II->setFETokenInfo(New);
553 S->AddDecl(New);
554 }
555
556 if (S->getParent() == 0)
557 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +0000558
559 // If any semantic error occurred, mark the decl as invalid.
560 if (D.getInvalidType() || InvalidDecl)
561 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000562
563 return New;
564}
565
Steve Naroffbb204692007-09-12 14:07:44 +0000566void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000567 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000568 Expr *Init = static_cast<Expr *>(init);
569
Steve Naroff410e3e22007-09-12 20:13:48 +0000570 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000571
Steve Naroff410e3e22007-09-12 20:13:48 +0000572 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
573 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000574 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
575 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000576 RealDecl->setInvalidDecl();
577 return;
578 }
Steve Naroffbb204692007-09-12 14:07:44 +0000579 // Get the decls type and save a reference for later, since
580 // CheckInitializer may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000581 QualType DclT = VDecl->getType(), SavT = DclT;
582 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000583 VarDecl::StorageClass SC = BVD->getStorageClass();
584 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000585 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000586 BVD->setInvalidDecl();
587 } else if (!BVD->isInvalidDecl()) {
588 CheckInitializer(Init, DclT, SC == VarDecl::Static);
589 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000590 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000591 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000592 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000593 if (!FVD->isInvalidDecl())
594 CheckInitializer(Init, DclT, true);
595 }
596 // If the type changed, it means we had an incomplete type that was
597 // completed by the initializer. For example:
598 // int ary[] = { 1, 3, 5 };
599 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff410e3e22007-09-12 20:13:48 +0000600 if (!VDecl->isInvalidDecl() && (DclT != SavT))
601 VDecl->setType(DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000602
603 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000604 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000605 return;
606}
607
Reid Spencer5f016e22007-07-11 17:01:13 +0000608/// The declarators are chained together backwards, reverse the list.
609Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
610 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000611 Decl *GroupDecl = static_cast<Decl*>(group);
612 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000613 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000614
615 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
616 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000617 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000618 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000619 else { // reverse the list.
620 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000621 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000622 Group->setNextDeclarator(NewGroup);
623 NewGroup = Group;
624 Group = Next;
625 }
626 }
627 // Perform semantic analysis that depends on having fully processed both
628 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000629 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000630 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
631 if (!IDecl)
632 continue;
633 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
634 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
635 QualType T = IDecl->getType();
636
637 // C99 6.7.5.2p2: If an identifier is declared to be an object with
638 // static storage duration, it shall not have a variable length array.
639 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
640 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
641 if (VLA->getSizeExpr()) {
642 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
643 IDecl->setInvalidDecl();
644 }
645 }
646 }
647 // Block scope. C99 6.7p7: If an identifier for an object is declared with
648 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
649 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
650 if (T->isIncompleteType()) {
651 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
652 T.getAsString());
653 IDecl->setInvalidDecl();
654 }
655 }
656 // File scope. C99 6.9.2p2: A declaration of an identifier for and
657 // object that has file scope without an initializer, and without a
658 // storage-class specifier or with the storage-class specifier "static",
659 // constitutes a tentative definition. Note: A tentative definition with
660 // external linkage is valid (C99 6.2.2p5).
661 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
662 // C99 6.9.2p3: If the declaration of an identifier for an object is
663 // a tentative definition and has internal linkage (C99 6.2.2p3), the
664 // declared type shall not be an incomplete type.
665 if (T->isIncompleteType()) {
666 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
667 T.getAsString());
668 IDecl->setInvalidDecl();
669 }
670 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000671 }
672 return NewGroup;
673}
Steve Naroffe1223f72007-08-28 03:03:08 +0000674
675// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000676ParmVarDecl *
677Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
678 Scope *FnScope) {
679 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
680
681 IdentifierInfo *II = PI.Ident;
682 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
683 // Can this happen for params? We already checked that they don't conflict
684 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000685 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000686 PI.IdentLoc, FnScope)) {
687
688 }
689
690 // FIXME: Handle storage class (auto, register). No declarator?
691 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000692
693 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
694 // Doing the promotion here has a win and a loss. The win is the type for
695 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
696 // code generator). The loss is the orginal type isn't preserved. For example:
697 //
698 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
699 // int blockvardecl[5];
700 // sizeof(parmvardecl); // size == 4
701 // sizeof(blockvardecl); // size == 20
702 // }
703 //
704 // For expressions, all implicit conversions are captured using the
705 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
706 //
707 // FIXME: If a source translation tool needs to see the original type, then
708 // we need to consider storing both types (in ParmVarDecl)...
709 //
710 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
711 if (const ArrayType *AT = parmDeclType->getAsArrayType())
712 parmDeclType = Context.getPointerType(AT->getElementType());
713 else if (parmDeclType->isFunctionType())
714 parmDeclType = Context.getPointerType(parmDeclType);
715
716 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff53a32342007-08-28 18:45:29 +0000717 VarDecl::None, 0);
718 if (PI.InvalidType)
719 New->setInvalidDecl();
720
Reid Spencer5f016e22007-07-11 17:01:13 +0000721 // If this has an identifier, add it to the scope stack.
722 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000723 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000724 II->setFETokenInfo(New);
725 FnScope->AddDecl(New);
726 }
727
728 return New;
729}
730
731
732Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
733 assert(CurFunctionDecl == 0 && "Function parsing confused");
734 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
735 "Not a function declarator!");
736 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
737
738 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
739 // for a K&R function.
740 if (!FTI.hasPrototype) {
741 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
742 if (FTI.ArgInfo[i].TypeInfo == 0) {
743 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
744 FTI.ArgInfo[i].Ident->getName());
745 // Implicitly declare the argument as type 'int' for lack of a better
746 // type.
747 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
748 }
749 }
750
751 // Since this is a function definition, act as though we have information
752 // about the arguments.
753 FTI.hasPrototype = true;
754 } else {
755 // FIXME: Diagnose arguments without names in C.
756
757 }
758
759 Scope *GlobalScope = FnBodyScope->getParent();
760
761 FunctionDecl *FD =
Steve Naroff08d92e42007-09-15 18:49:24 +0000762 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 CurFunctionDecl = FD;
764
765 // Create Decl objects for each parameter, adding them to the FunctionDecl.
766 llvm::SmallVector<ParmVarDecl*, 16> Params;
767
768 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
769 // no arguments, not a function that takes a single void argument.
770 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
771 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
772 // empty arg list, don't push any params.
773 } else {
774 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
775 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
776 }
777
778 FD->setParams(&Params[0], Params.size());
779
780 return FD;
781}
782
783Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
784 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
785 FD->setBody((Stmt*)Body);
786
787 assert(FD == CurFunctionDecl && "Function parsing confused");
788 CurFunctionDecl = 0;
789
790 // Verify and clean out per-function state.
791
792 // Check goto/label use.
793 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
794 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
795 // Verify that we have no forward references left. If so, there was a goto
796 // or address of a label taken, but no definition of it. Label fwd
797 // definitions are indicated with a null substmt.
798 if (I->second->getSubStmt() == 0) {
799 LabelStmt *L = I->second;
800 // Emit error.
801 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
802
803 // At this point, we have gotos that use the bogus label. Stitch it into
804 // the function body so that they aren't leaked and that the AST is well
805 // formed.
806 L->setSubStmt(new NullStmt(L->getIdentLoc()));
807 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
808 }
809 }
810 LabelMap.clear();
811
812 return FD;
813}
814
815
816/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
817/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
818Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
819 Scope *S) {
820 if (getLangOptions().C99) // Extension in C99.
821 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
822 else // Legal in C90, but warn about it.
823 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
824
825 // FIXME: handle stuff like:
826 // void foo() { extern float X(); }
827 // void bar() { X(); } <-- implicit decl for X in another scope.
828
829 // Set a Declarator for the implicit definition: int foo();
830 const char *Dummy;
831 DeclSpec DS;
832 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
833 Error = Error; // Silence warning.
834 assert(!Error && "Error setting up implicit decl!");
835 Declarator D(DS, Declarator::BlockContext);
836 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
837 D.SetIdentifier(&II, Loc);
838
839 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000840 if (Scope *FnS = S->getFnParent())
841 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000842 while (S->getParent())
843 S = S->getParent();
844
Steve Naroff08d92e42007-09-15 18:49:24 +0000845 return static_cast<Decl*>(ActOnDeclarator(S, D, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000846}
847
848
849TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
Steve Naroff94745042007-09-13 23:52:58 +0000850 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000851 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
852
853 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000854 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000855
856 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +0000857 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
858 T, LastDeclarator);
859 if (D.getInvalidType())
860 NewTD->setInvalidDecl();
861 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000862}
863
Steve Naroff3536b442007-09-06 21:24:23 +0000864Sema::DeclTy *Sema::ObjcStartClassInterface(SourceLocation AtInterfaceLoc,
865 IdentifierInfo *ClassName, SourceLocation ClassLoc,
866 IdentifierInfo *SuperName, SourceLocation SuperLoc,
867 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
868 AttributeList *AttrList) {
869 assert(ClassName && "Missing class identifier");
870 ObjcInterfaceDecl *IDecl;
871
872 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, ClassName);
873
874 // Chain & install the interface decl into the identifier.
Steve Naroffc752d042007-09-13 18:10:37 +0000875 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
Steve Naroff3536b442007-09-06 21:24:23 +0000876 ClassName->setFETokenInfo(IDecl);
877 return IDecl;
878}
879
880/// ObjcClassDeclaration -
881/// Scope will always be top level file scope.
882Action::DeclTy *
883Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
884 IdentifierInfo **IdentList, unsigned NumElts) {
885 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
886
887 for (unsigned i = 0; i != NumElts; ++i) {
888 ObjcInterfaceDecl *IDecl;
889
Steve Naroff2bd42fa2007-09-10 20:51:04 +0000890 // FIXME: before we create one, look up the interface decl in a hash table.
Steve Naroff3536b442007-09-06 21:24:23 +0000891 IDecl = new ObjcInterfaceDecl(SourceLocation(), IdentList[i], true);
892 // Chain & install the interface decl into the identifier.
Steve Naroffc752d042007-09-13 18:10:37 +0000893 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
Steve Naroff3536b442007-09-06 21:24:23 +0000894 IdentList[i]->setFETokenInfo(IDecl);
895
896 // Remember that this needs to be removed when the scope is popped.
897 S->AddDecl(IdentList[i]);
898
899 CDecl->setInterfaceDecl((int)i, IDecl);
900 }
901 return CDecl;
902}
903
Reid Spencer5f016e22007-07-11 17:01:13 +0000904
Steve Naroff08d92e42007-09-15 18:49:24 +0000905/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +0000906/// former case, Name will be non-null. In the later case, Name will be null.
907/// TagType indicates what kind of tag this is. TK indicates whether this is a
908/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +0000909Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +0000910 SourceLocation KWLoc, IdentifierInfo *Name,
911 SourceLocation NameLoc, AttributeList *Attr) {
912 // If this is a use of an existing tag, it must have a name.
913 assert((Name != 0 || TK == TK_Definition) &&
914 "Nameless record must be a definition!");
915
916 Decl::Kind Kind;
917 switch (TagType) {
918 default: assert(0 && "Unknown tag type!");
919 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
920 case DeclSpec::TST_union: Kind = Decl::Union; break;
921//case DeclSpec::TST_class: Kind = Decl::Class; break;
922 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
923 }
924
925 // If this is a named struct, check to see if there was a previous forward
926 // declaration or definition.
927 if (TagDecl *PrevDecl =
928 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
929 NameLoc, S))) {
930
931 // If this is a use of a previous tag, or if the tag is already declared in
932 // the same scope (so that the definition/declaration completes or
933 // rementions the tag), reuse the decl.
934 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
935 // Make sure that this wasn't declared as an enum and now used as a struct
936 // or something similar.
937 if (PrevDecl->getKind() != Kind) {
938 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
939 Diag(PrevDecl->getLocation(), diag::err_previous_use);
940 }
941
942 // If this is a use or a forward declaration, we're good.
943 if (TK != TK_Definition)
944 return PrevDecl;
945
946 // Diagnose attempts to redefine a tag.
947 if (PrevDecl->isDefinition()) {
948 Diag(NameLoc, diag::err_redefinition, Name->getName());
949 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
950 // If this is a redefinition, recover by making this struct be
951 // anonymous, which will make any later references get the previous
952 // definition.
953 Name = 0;
954 } else {
955 // Okay, this is definition of a previously declared or referenced tag.
956 // Move the location of the decl to be the definition site.
957 PrevDecl->setLocation(NameLoc);
958 return PrevDecl;
959 }
960 }
961 // If we get here, this is a definition of a new struct type in a nested
962 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
963 // type.
964 }
965
966 // If there is an identifier, use the location of the identifier as the
967 // location of the decl, otherwise use the location of the struct/union
968 // keyword.
969 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
970
971 // Otherwise, if this is the first time we've seen this tag, create the decl.
972 TagDecl *New;
973 switch (Kind) {
974 default: assert(0 && "Unknown tag kind!");
975 case Decl::Enum:
976 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
977 // enum X { A, B, C } D; D should chain to X.
978 New = new EnumDecl(Loc, Name, 0);
979 // If this is an undefined enum, warn.
980 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
981 break;
982 case Decl::Union:
983 case Decl::Struct:
984 case Decl::Class:
985 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
986 // struct X { int A; } D; D should chain to X.
987 New = new RecordDecl(Kind, Loc, Name, 0);
988 break;
989 }
990
991 // If this has an identifier, add it to the scope stack.
992 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +0000993 // The scope passed in may not be a decl scope. Zip up the scope tree until
994 // we find one that is.
995 while ((S->getFlags() & Scope::DeclScope) == 0)
996 S = S->getParent();
997
998 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +0000999 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 Name->setFETokenInfo(New);
1001 S->AddDecl(New);
1002 }
1003
1004 return New;
1005}
1006
Steve Naroff08d92e42007-09-15 18:49:24 +00001007/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001008/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001009Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001010 SourceLocation DeclStart,
1011 Declarator &D, ExprTy *BitfieldWidth) {
1012 IdentifierInfo *II = D.getIdentifier();
1013 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001014 SourceLocation Loc = DeclStart;
1015 if (II) Loc = D.getIdentifierLoc();
1016
1017 // FIXME: Unnamed fields can be handled in various different ways, for
1018 // example, unnamed unions inject all members into the struct namespace!
1019
1020
1021 if (BitWidth) {
1022 // TODO: Validate.
1023 //printf("WARNING: BITFIELDS IGNORED!\n");
1024
1025 // 6.7.2.1p3
1026 // 6.7.2.1p4
1027
1028 } else {
1029 // Not a bitfield.
1030
1031 // validate II.
1032
1033 }
1034
1035 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001036 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1037 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001038
Reid Spencer5f016e22007-07-11 17:01:13 +00001039 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1040 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001041 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1042 Diag(Loc, diag::err_typecheck_illegal_vla,
1043 VAT->getSizeExpr()->getSourceRange());
1044 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001045 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001046 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001047 FieldDecl *NewFD;
1048
1049 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001050 NewFD = new FieldDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001051 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001052 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001053 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001054 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001055
Steve Naroff5912a352007-08-28 20:14:24 +00001056 if (D.getInvalidType() || InvalidDecl)
1057 NewFD->setInvalidDecl();
1058 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001059}
1060
Steve Narofff13271f2007-09-14 23:09:53 +00001061static void ObjcSetIvarVisibility(ObjcIvarDecl *OIvar,
1062 tok::ObjCKeywordKind ivarVisibility) {
1063 assert(OIvar && "missing instance variable");
1064 switch (ivarVisibility) {
1065 case tok::objc_private:
1066 OIvar->setAccessControl(ObjcIvarDecl::Private);
1067 break;
1068 case tok::objc_public:
1069 OIvar->setAccessControl(ObjcIvarDecl::Public);
1070 break;
1071 case tok::objc_protected:
1072 OIvar->setAccessControl(ObjcIvarDecl::Protected);
1073 break;
1074 case tok::objc_package:
1075 OIvar->setAccessControl(ObjcIvarDecl::Package);
1076 break;
1077 default:
1078 OIvar->setAccessControl(ObjcIvarDecl::None);
1079 break;
1080 }
1081}
1082
Steve Naroff08d92e42007-09-15 18:49:24 +00001083void Sema::ActOnFields(SourceLocation RecLoc, DeclTy *RecDecl,
1084 DeclTy **Fields, unsigned NumFields,
1085 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001086 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1087 assert(EnclosingDecl && "missing record or interface decl");
1088 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1089
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001090 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001091 // Diagnose code like:
1092 // struct S { struct S {} X; };
1093 // We discover this when we complete the outer S. Reject and ignore the
1094 // outer S.
1095 Diag(Record->getLocation(), diag::err_nested_redefinition,
1096 Record->getKindName());
1097 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001098 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001099 return;
1100 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001101 // Verify that all the fields are okay.
1102 unsigned NumNamedMembers = 0;
1103 llvm::SmallVector<FieldDecl*, 32> RecFields;
1104 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001105
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001107
Steve Naroff74216642007-09-14 22:20:54 +00001108 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1109 assert(FD && "missing field decl");
1110
1111 // Remember all fields.
1112 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001113
1114 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001115 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001116
Steve Narofff13271f2007-09-14 23:09:53 +00001117 // If we have visibility info, make sure the AST is set accordingly.
1118 if (visibility)
1119 ObjcSetIvarVisibility(dyn_cast<ObjcIvarDecl>(FD), visibility[i]);
1120
Reid Spencer5f016e22007-07-11 17:01:13 +00001121 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001122 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001123 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001124 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001125 FD->setInvalidDecl();
1126 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001127 continue;
1128 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1130 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001131 if (!Record) { // Incomplete ivar type is always an error.
1132 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001133 FD->setInvalidDecl();
1134 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001135 continue;
1136 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001137 if (i != NumFields-1 || // ... that the last member ...
1138 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001139 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001141 FD->setInvalidDecl();
1142 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 continue;
1144 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001145 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001146 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1147 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001148 FD->setInvalidDecl();
1149 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001150 continue;
1151 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001152 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001153 if (Record)
1154 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001156 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1157 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001158 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001159 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1160 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001161 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 Record->setHasFlexibleArrayMember(true);
1163 } else {
1164 // If this is a struct/class and this is not the last element, reject
1165 // it. Note that GCC supports variable sized arrays in the middle of
1166 // structures.
1167 if (i != NumFields-1) {
1168 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1169 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001170 FD->setInvalidDecl();
1171 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001172 continue;
1173 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001174 // We support flexible arrays at the end of structs in other structs
1175 // as an extension.
1176 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1177 FD->getName());
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001178 if (Record)
1179 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 }
1181 }
1182 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001183 // Keep track of the number of named members.
1184 if (IdentifierInfo *II = FD->getIdentifier()) {
1185 // Detect duplicate member names.
1186 if (!FieldIDs.insert(II)) {
1187 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1188 // Find the previous decl.
1189 SourceLocation PrevLoc;
1190 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1191 assert(i != e && "Didn't find previous def!");
1192 if (RecFields[i]->getIdentifier() == II) {
1193 PrevLoc = RecFields[i]->getLocation();
1194 break;
1195 }
1196 }
1197 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001198 FD->setInvalidDecl();
1199 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 continue;
1201 }
1202 ++NumNamedMembers;
1203 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 }
1205
Reid Spencer5f016e22007-07-11 17:01:13 +00001206 // Okay, we successfully defined 'Record'.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001207 if (Record)
1208 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001209 else {
1210 ObjcIvarDecl **ClsFields =
1211 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
1212 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1213 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1214 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001215}
1216
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001217void Sema::ObjcAddMethodsToClass(DeclTy *ClassDecl,
1218 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001219 // FIXME: Fix this when we can handle methods declared in protocols.
1220 // See Parser::ParseObjCAtProtocolDeclaration
1221 if (!ClassDecl)
1222 return;
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001223 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1224 static_cast<Decl*>(ClassDecl));
1225 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1226 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1227
1228 for (unsigned i = 0; i < allNum; i++ ) {
1229 ObjcMethodDecl *Method =
1230 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1231 if (!Method) continue; // Already issued a diagnostic.
1232 if (Method->isInstance())
1233 insMethods.push_back(Method);
1234 else
1235 clsMethods.push_back(Method);
1236 }
1237 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1238 &clsMethods[0], clsMethods.size());
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001239 return;
1240}
1241
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001242Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
1243 tok::TokenKind MethodType, TypeTy *ReturnType,
1244 ObjcKeywordInfo *Keywords, unsigned NumKeywords,
1245 AttributeList *AttrList) {
1246 assert(NumKeywords && "Selector must be specified");
1247 // FIXME: SelectorName to be changed to comform to objc's abi for method names
1248 IdentifierInfo *SelectorName = Keywords[0].SelectorName;
1249 llvm::SmallVector<ParmVarDecl*, 16> Params;
1250
1251 for (unsigned i = 0; i < NumKeywords; i++) {
1252 ObjcKeywordInfo *arg = &Keywords[i];
1253 // FIXME: arg->AttrList must be stored too!
1254 ParmVarDecl* Param = new ParmVarDecl(arg->ColonLoc, arg->ArgumentName,
1255 QualType::getFromOpaquePtr(arg->TypeInfo),
1256 VarDecl::None, 0);
1257 // FIXME: 'InvalidType' does not get set by caller yet.
1258 if (arg->InvalidType)
1259 Param->setInvalidDecl();
1260 Params.push_back(Param);
1261 }
1262 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
1263 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc,
1264 SelectorName, resultDeclType,
1265 0, -1, AttrList, MethodType == tok::minus);
1266 ObjcMethod->setMethodParams(&Params[0], NumKeywords);
1267 return ObjcMethod;
1268}
1269
1270Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
1271 tok::TokenKind MethodType, TypeTy *ReturnType,
1272 IdentifierInfo *SelectorName, AttributeList *AttrList) {
1273 // FIXME: SelectorName to be changed to comform to objc's abi for method names
1274 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
1275 return new ObjcMethodDecl(MethodLoc, SelectorName, resultDeclType, 0, -1,
1276 AttrList, MethodType == tok::minus);
1277}
1278
Steve Naroff08d92e42007-09-15 18:49:24 +00001279Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001280 DeclTy *lastEnumConst,
1281 SourceLocation IdLoc, IdentifierInfo *Id,
1282 SourceLocation EqualLoc, ExprTy *val) {
1283 theEnumDecl = theEnumDecl; // silence unused warning.
1284 EnumConstantDecl *LastEnumConst =
1285 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1286 Expr *Val = static_cast<Expr*>(val);
1287
Chris Lattner31e05722007-08-26 06:24:45 +00001288 // The scope passed in may not be a decl scope. Zip up the scope tree until
1289 // we find one that is.
1290 while ((S->getFlags() & Scope::DeclScope) == 0)
1291 S = S->getParent();
1292
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 // Verify that there isn't already something declared with this name in this
1294 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001295 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1296 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 if (S->isDeclScope(PrevDecl)) {
1298 if (isa<EnumConstantDecl>(PrevDecl))
1299 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1300 else
1301 Diag(IdLoc, diag::err_redefinition, Id->getName());
1302 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1303 // FIXME: Don't leak memory: delete Val;
1304 return 0;
1305 }
1306 }
1307
1308 llvm::APSInt EnumVal(32);
1309 QualType EltTy;
1310 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001311 // Make sure to promote the operand type to int.
1312 UsualUnaryConversions(Val);
1313
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1315 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001316 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1318 Id->getName());
1319 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001320 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001321 } else {
1322 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001323 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001324 }
1325
1326 if (!Val) {
1327 if (LastEnumConst) {
1328 // Assign the last value + 1.
1329 EnumVal = LastEnumConst->getInitVal();
1330 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001331
1332 // Check for overflow on increment.
1333 if (EnumVal < LastEnumConst->getInitVal())
1334 Diag(IdLoc, diag::warn_enum_value_overflow);
1335
Chris Lattnerb7416f92007-08-27 17:37:24 +00001336 EltTy = LastEnumConst->getType();
1337 } else {
1338 // First value, set to zero.
1339 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001340 EnumVal.zextOrTrunc(
1341 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001342 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001343 }
1344
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1346 LastEnumConst);
1347
1348 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001349 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 Id->setFETokenInfo(New);
1351 S->AddDecl(New);
1352 return New;
1353}
1354
Steve Naroff08d92e42007-09-15 18:49:24 +00001355void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 DeclTy **Elements, unsigned NumElements) {
1357 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1358 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1359
Chris Lattnere37f0be2007-08-28 05:10:31 +00001360 // TODO: If the result value doesn't fit in an int, it must be a long or long
1361 // long value. ISO C does not support this, but GCC does as an extension,
1362 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001363 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001364
1365
Chris Lattnerac609682007-08-28 06:15:15 +00001366 // Verify that all the values are okay, compute the size of the values, and
1367 // reverse the list.
1368 unsigned NumNegativeBits = 0;
1369 unsigned NumPositiveBits = 0;
1370
1371 // Keep track of whether all elements have type int.
1372 bool AllElementsInt = true;
1373
Reid Spencer5f016e22007-07-11 17:01:13 +00001374 EnumConstantDecl *EltList = 0;
1375 for (unsigned i = 0; i != NumElements; ++i) {
1376 EnumConstantDecl *ECD =
1377 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1378 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001379
1380 // If the enum value doesn't fit in an int, emit an extension warning.
1381 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1382 "Should have promoted value to int");
1383 const llvm::APSInt &InitVal = ECD->getInitVal();
1384 if (InitVal.getBitWidth() > IntWidth) {
1385 llvm::APSInt V(InitVal);
1386 V.trunc(IntWidth);
1387 V.extend(InitVal.getBitWidth());
1388 if (V != InitVal)
1389 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1390 InitVal.toString());
1391 }
Chris Lattnerac609682007-08-28 06:15:15 +00001392
1393 // Keep track of the size of positive and negative values.
1394 if (InitVal.isUnsigned() || !InitVal.isNegative())
1395 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1396 else
1397 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001398
Chris Lattnerac609682007-08-28 06:15:15 +00001399 // Keep track of whether every enum element has type int (very commmon).
1400 if (AllElementsInt)
1401 AllElementsInt = ECD->getType() == Context.IntTy;
1402
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 ECD->setNextDeclarator(EltList);
1404 EltList = ECD;
1405 }
1406
Chris Lattnerac609682007-08-28 06:15:15 +00001407 // Figure out the type that should be used for this enum.
1408 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1409 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001410 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001411
1412 if (NumNegativeBits) {
1413 // If there is a negative value, figure out the smallest integer type (of
1414 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001415 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001416 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001417 BestWidth = IntWidth;
1418 } else {
1419 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1420 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001421 BestType = Context.LongTy;
1422 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001423 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1424 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001425 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1426 BestType = Context.LongLongTy;
1427 }
1428 }
1429 } else {
1430 // If there is no negative value, figure out which of uint, ulong, ulonglong
1431 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001432 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001433 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001434 BestWidth = IntWidth;
1435 } else if (NumPositiveBits <=
1436 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001437 BestType = Context.UnsignedLongTy;
1438 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001439 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1440 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001441 "How could an initializer get larger than ULL?");
1442 BestType = Context.UnsignedLongLongTy;
1443 }
1444 }
1445
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001446 // Loop over all of the enumerator constants, changing their types to match
1447 // the type of the enum if needed.
1448 for (unsigned i = 0; i != NumElements; ++i) {
1449 EnumConstantDecl *ECD =
1450 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1451 if (!ECD) continue; // Already issued a diagnostic.
1452
1453 // Standard C says the enumerators have int type, but we allow, as an
1454 // extension, the enumerators to be larger than int size. If each
1455 // enumerator value fits in an int, type it as an int, otherwise type it the
1456 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1457 // that X has type 'int', not 'unsigned'.
1458 if (ECD->getType() == Context.IntTy)
1459 continue; // Already int type.
1460
1461 // Determine whether the value fits into an int.
1462 llvm::APSInt InitVal = ECD->getInitVal();
1463 bool FitsInInt;
1464 if (InitVal.isUnsigned() || !InitVal.isNegative())
1465 FitsInInt = InitVal.getActiveBits() < IntWidth;
1466 else
1467 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1468
1469 // If it fits into an integer type, force it. Otherwise force it to match
1470 // the enum decl type.
1471 QualType NewTy;
1472 unsigned NewWidth;
1473 bool NewSign;
1474 if (FitsInInt) {
1475 NewTy = Context.IntTy;
1476 NewWidth = IntWidth;
1477 NewSign = true;
1478 } else if (ECD->getType() == BestType) {
1479 // Already the right type!
1480 continue;
1481 } else {
1482 NewTy = BestType;
1483 NewWidth = BestWidth;
1484 NewSign = BestType->isSignedIntegerType();
1485 }
1486
1487 // Adjust the APSInt value.
1488 InitVal.extOrTrunc(NewWidth);
1489 InitVal.setIsSigned(NewSign);
1490 ECD->setInitVal(InitVal);
1491
1492 // Adjust the Expr initializer and type.
1493 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1494 ECD->setType(NewTy);
1495 }
Chris Lattnerac609682007-08-28 06:15:15 +00001496
Chris Lattnere00b18c2007-08-28 18:24:31 +00001497 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001498}
1499
1500void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1501 if (!current) return;
1502
1503 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1504 // remember this in the LastInGroupList list.
1505 if (last)
1506 LastInGroupList.push_back((Decl*)last);
1507}
1508
1509void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1510 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1511 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1512 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1513 if (!newType.isNull()) // install the new vector type into the decl
1514 vDecl->setType(newType);
1515 }
1516 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1517 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1518 rawAttr);
1519 if (!newType.isNull()) // install the new vector type into the decl
1520 tDecl->setUnderlyingType(newType);
1521 }
1522 }
Steve Naroff73322922007-07-18 18:00:27 +00001523 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001524 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1525 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1526 else
Steve Naroff73322922007-07-18 18:00:27 +00001527 Diag(rawAttr->getAttributeLoc(),
1528 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00001529 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 // FIXME: add other attributes...
1531}
1532
1533void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1534 AttributeList *declarator_postfix) {
1535 while (declspec_prefix) {
1536 HandleDeclAttribute(New, declspec_prefix);
1537 declspec_prefix = declspec_prefix->getNext();
1538 }
1539 while (declarator_postfix) {
1540 HandleDeclAttribute(New, declarator_postfix);
1541 declarator_postfix = declarator_postfix->getNext();
1542 }
1543}
1544
Steve Naroffbea0b342007-07-29 16:33:31 +00001545void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1546 AttributeList *rawAttr) {
1547 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00001548 // check the attribute arugments.
1549 if (rawAttr->getNumArgs() != 1) {
1550 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1551 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001552 return;
Steve Naroff73322922007-07-18 18:00:27 +00001553 }
1554 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1555 llvm::APSInt vecSize(32);
1556 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1557 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1558 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001559 return;
Steve Naroff73322922007-07-18 18:00:27 +00001560 }
1561 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1562 // in conjunction with complex types (pointers, arrays, functions, etc.).
1563 Type *canonType = curType.getCanonicalType().getTypePtr();
1564 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1565 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1566 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001567 return;
Steve Naroff73322922007-07-18 18:00:27 +00001568 }
1569 // unlike gcc's vector_size attribute, the size is specified as the
1570 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001571 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001572
1573 if (vectorSize == 0) {
1574 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1575 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001576 return;
Steve Naroff73322922007-07-18 18:00:27 +00001577 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001578 // Instantiate/Install the vector type, the number of elements is > 0.
1579 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1580 // Remember this typedef decl, we will need it later for diagnostics.
1581 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001582}
1583
Reid Spencer5f016e22007-07-11 17:01:13 +00001584QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001585 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 // check the attribute arugments.
1587 if (rawAttr->getNumArgs() != 1) {
1588 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1589 std::string("1"));
1590 return QualType();
1591 }
1592 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1593 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001594 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001595 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1596 sizeExpr->getSourceRange());
1597 return QualType();
1598 }
1599 // navigate to the base type - we need to provide for vector pointers,
1600 // vector arrays, and functions returning vectors.
1601 Type *canonType = curType.getCanonicalType().getTypePtr();
1602
Steve Naroff73322922007-07-18 18:00:27 +00001603 if (canonType->isPointerType() || canonType->isArrayType() ||
1604 canonType->isFunctionType()) {
1605 assert(1 && "HandleVector(): Complex type construction unimplemented");
1606 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1607 do {
1608 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1609 canonType = PT->getPointeeType().getTypePtr();
1610 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1611 canonType = AT->getElementType().getTypePtr();
1612 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1613 canonType = FT->getResultType().getTypePtr();
1614 } while (canonType->isPointerType() || canonType->isArrayType() ||
1615 canonType->isFunctionType());
1616 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001617 }
1618 // the base type must be integer or float.
1619 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1620 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1621 curType.getCanonicalType().getAsString());
1622 return QualType();
1623 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00001624 unsigned typeSize = static_cast<unsigned>(
1625 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001627 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00001628
1629 // the vector size needs to be an integral multiple of the type size.
1630 if (vectorSize % typeSize) {
1631 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1632 sizeExpr->getSourceRange());
1633 return QualType();
1634 }
1635 if (vectorSize == 0) {
1636 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1637 sizeExpr->getSourceRange());
1638 return QualType();
1639 }
1640 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1641 // the number of elements to be a power of two (unlike GCC).
1642 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00001643 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001644}
1645