blob: f92bee64dcb617b2bd7db8ce004894e5692b3686 [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"
Steve Naroff980e5082007-10-01 19:00:59 +000018#include "clang/AST/DeclObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/Type.h"
21#include "clang/Parse/DeclSpec.h"
22#include "clang/Parse/Scope.h"
23#include "clang/Lex/IdentifierTable.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroff563477d2007-09-18 23:55:05 +000026#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
28using namespace clang;
29
Reid Spencer5f016e22007-07-11 17:01:13 +000030Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Chris Lattner5c0fa302007-09-30 08:31:00 +000031 if (Decl *IIDecl = II.getFETokenInfo<Decl>())
32 if (isa<TypedefDecl>(IIDecl) || isa<ObjcInterfaceDecl>(IIDecl))
33 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000034 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000035}
36
37void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000038 if (S->decl_empty()) return;
39 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
40
Reid Spencer5f016e22007-07-11 17:01:13 +000041 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
42 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000043 Decl *TmpD = static_cast<Decl*>(*I);
44 assert(TmpD && "This decl didn't get pushed??");
45 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
46 assert(D && "This decl isn't a ScopedDecl?");
47
Reid Spencer5f016e22007-07-11 17:01:13 +000048 IdentifierInfo *II = D->getIdentifier();
49 if (!II) continue;
50
51 // Unlink this decl from the identifier. Because the scope contains decls
52 // in an unordered collection, and because we have multiple identifier
53 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
54 if (II->getFETokenInfo<Decl>() == D) {
55 // Normal case, no multiple decls in different namespaces.
56 II->setFETokenInfo(D->getNext());
57 } else {
58 // Scan ahead. There are only three namespaces in C, so this loop can
59 // never execute more than 3 times.
Steve Naroffc752d042007-09-13 18:10:37 +000060 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +000061 while (SomeDecl->getNext() != D) {
62 SomeDecl = SomeDecl->getNext();
63 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
64 }
65 SomeDecl->setNext(D->getNext());
66 }
67
68 // This will have to be revisited for C++: there we want to nest stuff in
69 // namespace decls etc. Even for C, we might want a top-level translation
70 // unit decl or something.
71 if (!CurFunctionDecl)
72 continue;
73
74 // Chain this decl to the containing function, it now owns the memory for
75 // the decl.
76 D->setNext(CurFunctionDecl->getDeclChain());
77 CurFunctionDecl->setDeclChain(D);
78 }
79}
80
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +000081/// getObjcInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +000082/// return 0 if one not found.
83ObjcInterfaceDecl *Sema::getObjCInterfaceDecl(Scope *S,
84 IdentifierInfo *Id,
85 SourceLocation IdLoc) {
86 ScopedDecl *IdDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
87 IdLoc, S);
88 if (IdDecl && !isa<ObjcInterfaceDecl>(IdDecl))
89 IdDecl = 0;
90 return cast_or_null<ObjcInterfaceDecl>(static_cast<Decl*>(IdDecl));
91}
92
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +000093/// getObjcProtocolDecl - Look up a for a protocol declaration in the scope.
94/// return 0 if one not found.
95ObjcProtocolDecl *Sema::getObjCProtocolDecl(Scope *S,
96 IdentifierInfo *Id,
97 SourceLocation IdLoc) {
98 // Note that Protocols have their own namespace.
99 ScopedDecl *PrDecl = LookupScopedDecl(Id, Decl::IDNS_Protocol,
100 IdLoc, S);
101 if (PrDecl && !isa<ObjcProtocolDecl>(PrDecl))
102 PrDecl = 0;
103 return cast_or_null<ObjcProtocolDecl>(static_cast<Decl*>(PrDecl));
104}
105
Reid Spencer5f016e22007-07-11 17:01:13 +0000106/// LookupScopedDecl - Look up the inner-most declaration in the specified
107/// namespace.
Steve Naroffc752d042007-09-13 18:10:37 +0000108ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
109 SourceLocation IdLoc, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000110 if (II == 0) return 0;
111 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
112
113 // Scan up the scope chain looking for a decl that matches this identifier
114 // that is in the appropriate namespace. This search should not take long, as
115 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffc752d042007-09-13 18:10:37 +0000116 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 if (D->getIdentifierNamespace() == NS)
118 return D;
119
120 // If we didn't find a use of this identifier, and if the identifier
121 // corresponds to a compiler builtin, create the decl object for the builtin
122 // now, injecting it into translation unit scope, and return it.
123 if (NS == Decl::IDNS_Ordinary) {
124 // If this is a builtin on some other target, or if this builtin varies
125 // across targets (e.g. in type), emit a diagnostic and mark the translation
126 // unit non-portable for using it.
127 if (II->isNonPortableBuiltin()) {
128 // Only emit this diagnostic once for this builtin.
129 II->setNonPortableBuiltin(false);
130 Context.Target.DiagnoseNonPortability(IdLoc,
131 diag::port_target_builtin_use);
132 }
133 // If this is a builtin on this (or all) targets, create the decl.
134 if (unsigned BuiltinID = II->getBuiltinID())
135 return LazilyCreateBuiltin(II, BuiltinID, S);
136 }
137 return 0;
138}
139
140/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
141/// lazily create a decl for it.
Steve Naroffc752d042007-09-13 18:10:37 +0000142ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 Builtin::ID BID = (Builtin::ID)bid;
144
145 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
146 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000147 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000148
149 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000150 if (Scope *FnS = S->getFnParent())
151 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 while (S->getParent())
153 S = S->getParent();
154 S->AddDecl(New);
155
156 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000157 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000158 // Scan until we find the last (outermost) decl in the id chain.
159 while (LastDecl->getNext())
160 LastDecl = LastDecl->getNext();
161 // Insert before (outside) it.
162 LastDecl->setNext(New);
163 } else {
164 II->setFETokenInfo(New);
165 }
166 // Make sure clients iterating over decls see this.
167 LastInGroupList.push_back(New);
168
169 return New;
170}
171
172/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
173/// and scope as a previous declaration 'Old'. Figure out how to resolve this
174/// situation, merging decls or emitting diagnostics as appropriate.
175///
Steve Naroff8e74c932007-09-13 21:41:19 +0000176TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000177 // Verify the old decl was also a typedef.
178 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
179 if (!Old) {
180 Diag(New->getLocation(), diag::err_redefinition_different_kind,
181 New->getName());
182 Diag(OldD->getLocation(), diag::err_previous_definition);
183 return New;
184 }
185
186 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
187 // TODO: This is totally simplistic. It should handle merging functions
188 // together etc, merging extern int X; int X; ...
189 Diag(New->getLocation(), diag::err_redefinition, New->getName());
190 Diag(Old->getLocation(), diag::err_previous_definition);
191 return New;
192}
193
194/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
195/// and scope as a previous declaration 'Old'. Figure out how to resolve this
196/// situation, merging decls or emitting diagnostics as appropriate.
197///
Steve Naroff8e74c932007-09-13 21:41:19 +0000198FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000199 // Verify the old decl was also a function.
200 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
201 if (!Old) {
202 Diag(New->getLocation(), diag::err_redefinition_different_kind,
203 New->getName());
204 Diag(OldD->getLocation(), diag::err_previous_definition);
205 return New;
206 }
207
208 // This is not right, but it's a start. If 'Old' is a function prototype with
209 // the same type as 'New', silently allow this. FIXME: We should link up decl
210 // objects here.
211 if (Old->getBody() == 0 &&
212 Old->getCanonicalType() == New->getCanonicalType()) {
213 return New;
214 }
215
216 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
217 // TODO: This is totally simplistic. It should handle merging functions
218 // together etc, merging extern int X; int X; ...
219 Diag(New->getLocation(), diag::err_redefinition, New->getName());
220 Diag(Old->getLocation(), diag::err_previous_definition);
221 return New;
222}
223
224/// MergeVarDecl - We just parsed a variable 'New' which has the same name
225/// and scope as a previous declaration 'Old'. Figure out how to resolve this
226/// situation, merging decls or emitting diagnostics as appropriate.
227///
228/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
229/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
230///
Steve Naroff8e74c932007-09-13 21:41:19 +0000231VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000232 // Verify the old decl was also a variable.
233 VarDecl *Old = dyn_cast<VarDecl>(OldD);
234 if (!Old) {
235 Diag(New->getLocation(), diag::err_redefinition_different_kind,
236 New->getName());
237 Diag(OldD->getLocation(), diag::err_previous_definition);
238 return New;
239 }
Steve Narofffb22d962007-08-30 01:06:46 +0000240 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
241 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
242 bool OldIsTentative = false;
243
244 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
245 // Handle C "tentative" external object definitions. FIXME: finish!
246 if (!OldFSDecl->getInit() &&
247 (OldFSDecl->getStorageClass() == VarDecl::None ||
248 OldFSDecl->getStorageClass() == VarDecl::Static))
249 OldIsTentative = true;
250 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000251 // Verify the types match.
252 if (Old->getCanonicalType() != New->getCanonicalType()) {
253 Diag(New->getLocation(), diag::err_redefinition, New->getName());
254 Diag(Old->getLocation(), diag::err_previous_definition);
255 return New;
256 }
257 // We've verified the types match, now check if Old is "extern".
258 if (Old->getStorageClass() != VarDecl::Extern) {
259 Diag(New->getLocation(), diag::err_redefinition, New->getName());
260 Diag(Old->getLocation(), diag::err_previous_definition);
261 }
262 return New;
263}
264
265/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
266/// no declarator (e.g. "struct foo;") is parsed.
267Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
268 // TODO: emit error on 'int;' or 'const enum foo;'.
269 // TODO: emit error on 'typedef int;'
270 // if (!DS.isMissingDeclaratorOk()) Diag(...);
271
272 return 0;
273}
274
Steve Naroff9e8925e2007-09-04 14:36:54 +0000275bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000276 AssignmentCheckResult result;
277 SourceLocation loc = Init->getLocStart();
278 // Get the type before calling CheckSingleAssignmentConstraints(), since
279 // it can promote the expression.
280 QualType rhsType = Init->getType();
281
282 result = CheckSingleAssignmentConstraints(DeclType, Init);
283
284 // decode the result (notice that extensions still return a type).
285 switch (result) {
286 case Compatible:
287 break;
288 case Incompatible:
Steve Naroff6f9f3072007-09-02 15:34:30 +0000289 // FIXME: tighten up this check which should allow:
290 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
291 if (rhsType == Context.getPointerType(Context.CharTy))
292 break;
Steve Narofff0090632007-09-02 02:04:30 +0000293 Diag(loc, diag::err_typecheck_assign_incompatible,
294 DeclType.getAsString(), rhsType.getAsString(),
295 Init->getSourceRange());
296 return true;
297 case PointerFromInt:
298 // check for null pointer constant (C99 6.3.2.3p3)
299 if (!Init->isNullPointerConstant(Context)) {
300 Diag(loc, diag::ext_typecheck_assign_pointer_int,
301 DeclType.getAsString(), rhsType.getAsString(),
302 Init->getSourceRange());
303 return true;
304 }
305 break;
306 case IntFromPointer:
307 Diag(loc, diag::ext_typecheck_assign_pointer_int,
308 DeclType.getAsString(), rhsType.getAsString(),
309 Init->getSourceRange());
310 break;
311 case IncompatiblePointer:
312 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
313 DeclType.getAsString(), rhsType.getAsString(),
314 Init->getSourceRange());
315 break;
316 case CompatiblePointerDiscardsQualifiers:
317 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
318 DeclType.getAsString(), rhsType.getAsString(),
319 Init->getSourceRange());
320 break;
321 }
322 return false;
323}
324
Steve Naroff9e8925e2007-09-04 14:36:54 +0000325bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
326 bool isStatic, QualType ElementType) {
Steve Naroff371227d2007-09-04 02:20:04 +0000327 SourceLocation loc;
Steve Naroff9e8925e2007-09-04 14:36:54 +0000328 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff371227d2007-09-04 02:20:04 +0000329
330 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
331 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
332 return true;
333 } else if (CheckSingleInitializer(expr, ElementType)) {
334 return true; // types weren't compatible.
335 }
Steve Naroff9e8925e2007-09-04 14:36:54 +0000336 if (savExpr != expr) // The type was promoted, update initializer list.
337 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000338 return false;
339}
340
341void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
342 QualType ElementType, bool isStatic,
343 int &nInitializers, bool &hadError) {
Steve Naroff6f9f3072007-09-02 15:34:30 +0000344 for (unsigned i = 0; i < IList->getNumInits(); i++) {
345 Expr *expr = IList->getInit(i);
346
Steve Naroff371227d2007-09-04 02:20:04 +0000347 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
348 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000349 int maxElements = CAT->getMaximumElements();
Steve Naroff371227d2007-09-04 02:20:04 +0000350 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
351 maxElements, hadError);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000352 }
Steve Naroff371227d2007-09-04 02:20:04 +0000353 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000354 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000355 }
Steve Naroff371227d2007-09-04 02:20:04 +0000356 nInitializers++;
357 }
358 return;
359}
360
361// FIXME: Doesn't deal with arrays of structures yet.
362void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
363 QualType ElementType, bool isStatic,
364 int &totalInits, bool &hadError) {
365 int maxElementsAtThisLevel = 0;
366 int nInitsAtLevel = 0;
367
368 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
369 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff7cf8c442007-09-04 21:13:33 +0000370 maxElementsAtThisLevel = CAT->getMaximumElements();
371 // Set DeclType, used below to recurse (for multi-dimensional arrays).
372 DeclType = CAT->getElementType();
Steve Naroff371227d2007-09-04 02:20:04 +0000373 } else if (DeclType->isScalarType()) {
374 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
375 IList->getSourceRange());
376 maxElementsAtThisLevel = 1;
377 }
378 // The empty init list "{ }" is treated specially below.
379 unsigned numInits = IList->getNumInits();
380 if (numInits) {
381 for (unsigned i = 0; i < numInits; i++) {
382 Expr *expr = IList->getInit(i);
383
384 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
385 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
386 totalInits, hadError);
387 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000388 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff371227d2007-09-04 02:20:04 +0000389 nInitsAtLevel++; // increment the number of initializers at this level.
390 totalInits--; // decrement the total number of initializers.
391
392 // Check if we have space for another initializer.
393 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
394 Diag(expr->getLocStart(), diag::warn_excess_initializers,
395 expr->getSourceRange());
396 }
397 }
398 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
399 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
400 } else {
401 // we have an initializer list with no elements.
402 totalInits -= maxElementsAtThisLevel;
403 if (totalInits < 0)
404 Diag(IList->getLocStart(), diag::warn_excess_initializers,
405 IList->getSourceRange());
Steve Naroff6f9f3072007-09-02 15:34:30 +0000406 }
Steve Naroffd35005e2007-09-03 01:24:23 +0000407 return;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000408}
409
Steve Naroff9e8925e2007-09-04 14:36:54 +0000410bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Narofff0090632007-09-02 02:04:30 +0000411 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroffd35005e2007-09-03 01:24:23 +0000412 if (!InitList)
413 return CheckSingleInitializer(Init, DeclType);
414
Steve Narofff0090632007-09-02 02:04:30 +0000415 // We have an InitListExpr, make sure we set the type.
416 Init->setType(DeclType);
Steve Naroffd35005e2007-09-03 01:24:23 +0000417
418 bool hadError = false;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000419
Steve Naroff38374b02007-09-02 20:30:18 +0000420 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
421 // of unknown size ("[]") or an object type that is not a variable array type.
422 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
423 Expr *expr = VAT->getSizeExpr();
Steve Naroffd35005e2007-09-03 01:24:23 +0000424 if (expr)
425 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
426 expr->getSourceRange());
427
Steve Naroff7cf8c442007-09-04 21:13:33 +0000428 // We have a VariableArrayType with unknown size. Note that only the first
429 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff371227d2007-09-04 02:20:04 +0000430 int numInits = 0;
Steve Naroff7cf8c442007-09-04 21:13:33 +0000431 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
432 isStatic, numInits, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000433 if (!hadError) {
434 // Return a new array type from the number of initializers (C99 6.7.8p22).
435 llvm::APSInt ConstVal(32);
Steve Naroff371227d2007-09-04 02:20:04 +0000436 ConstVal = numInits;
437 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroffd35005e2007-09-03 01:24:23 +0000438 ArrayType::Normal, 0);
439 }
440 return hadError;
441 }
442 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000443 int maxElements = CAT->getMaximumElements();
444 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
445 isStatic, maxElements, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000446 return hadError;
447 }
Steve Naroff371227d2007-09-04 02:20:04 +0000448 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
449 int maxElements = 1;
450 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
451 hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000452 return hadError;
Steve Naroff38374b02007-09-02 20:30:18 +0000453 }
454 // FIXME: Handle struct/union types.
Steve Naroffd35005e2007-09-03 01:24:23 +0000455 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +0000456}
457
Reid Spencer5f016e22007-07-11 17:01:13 +0000458Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000459Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000460 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000461 IdentifierInfo *II = D.getIdentifier();
462
Chris Lattnere80a59c2007-07-25 00:24:17 +0000463 // All of these full declarators require an identifier. If it doesn't have
464 // one, the ParsedFreeStandingDeclSpec action should be used.
465 if (II == 0) {
Chris Lattner98e08632007-08-28 06:17:15 +0000466 Diag(D.getDeclSpec().getSourceRange().Begin(),
467 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000468 D.getDeclSpec().getSourceRange(), D.getSourceRange());
469 return 0;
470 }
471
Chris Lattner31e05722007-08-26 06:24:45 +0000472 // The scope passed in may not be a decl scope. Zip up the scope tree until
473 // we find one that is.
474 while ((S->getFlags() & Scope::DeclScope) == 0)
475 S = S->getParent();
476
Reid Spencer5f016e22007-07-11 17:01:13 +0000477 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000478 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
479 D.getIdentifierLoc(), S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000480 if (PrevDecl && !S->isDeclScope(PrevDecl))
481 PrevDecl = 0; // If in outer scope, it isn't the same thing.
482
Steve Naroffc752d042007-09-13 18:10:37 +0000483 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000484 bool InvalidDecl = false;
485
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
487 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
488 if (!NewTD) return 0;
489
490 // Handle attributes prior to checking for duplicates in MergeVarDecl
491 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
492 D.getAttributes());
493 // Merge the decl with the existing one if appropriate.
494 if (PrevDecl) {
495 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
496 if (NewTD == 0) return 0;
497 }
498 New = NewTD;
499 if (S->getParent() == 0) {
500 // C99 6.7.7p2: If a typedef name specifies a variably modified type
501 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000502 if (const VariableArrayType *VAT =
503 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
504 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
505 VAT->getSizeExpr()->getSourceRange());
506 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000507 }
508 }
509 } else if (D.isFunctionDeclarator()) {
510 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000511 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000512
Chris Lattner271f1a62007-09-27 15:15:46 +0000513 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000514 switch (D.getDeclSpec().getStorageClassSpec()) {
515 default: assert(0 && "Unknown storage class!");
516 case DeclSpec::SCS_auto:
517 case DeclSpec::SCS_register:
518 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
519 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000520 InvalidDecl = true;
521 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000522 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
523 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
524 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
525 }
526
527 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000528 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000529 LastDeclarator);
530
531 // Merge the decl with the existing one if appropriate.
532 if (PrevDecl) {
533 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
534 if (NewFD == 0) return 0;
535 }
536 New = NewFD;
537 } else {
538 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff53a32342007-08-28 18:45:29 +0000539 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000540
541 VarDecl *NewVD;
542 VarDecl::StorageClass SC;
543 switch (D.getDeclSpec().getStorageClassSpec()) {
544 default: assert(0 && "Unknown storage class!");
545 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
546 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
547 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
548 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
549 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
550 }
551 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000552 // C99 6.9p2: The storage-class specifiers auto and register shall not
553 // appear in the declaration specifiers in an external declaration.
554 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
555 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
556 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000557 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000558 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000560 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000562 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000563 // Handle attributes prior to checking for duplicates in MergeVarDecl
564 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
565 D.getAttributes());
566
567 // Merge the decl with the existing one if appropriate.
568 if (PrevDecl) {
569 NewVD = MergeVarDecl(NewVD, PrevDecl);
570 if (NewVD == 0) return 0;
571 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 New = NewVD;
573 }
574
575 // If this has an identifier, add it to the scope stack.
576 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000577 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 II->setFETokenInfo(New);
579 S->AddDecl(New);
580 }
581
582 if (S->getParent() == 0)
583 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +0000584
585 // If any semantic error occurred, mark the decl as invalid.
586 if (D.getInvalidType() || InvalidDecl)
587 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000588
589 return New;
590}
591
Steve Naroffbb204692007-09-12 14:07:44 +0000592void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000593 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000594 Expr *Init = static_cast<Expr *>(init);
595
Steve Naroff410e3e22007-09-12 20:13:48 +0000596 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000597
Steve Naroff410e3e22007-09-12 20:13:48 +0000598 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
599 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000600 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
601 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000602 RealDecl->setInvalidDecl();
603 return;
604 }
Steve Naroffbb204692007-09-12 14:07:44 +0000605 // Get the decls type and save a reference for later, since
606 // CheckInitializer may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000607 QualType DclT = VDecl->getType(), SavT = DclT;
608 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000609 VarDecl::StorageClass SC = BVD->getStorageClass();
610 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000611 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000612 BVD->setInvalidDecl();
613 } else if (!BVD->isInvalidDecl()) {
614 CheckInitializer(Init, DclT, SC == VarDecl::Static);
615 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000616 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000617 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000618 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000619 if (!FVD->isInvalidDecl())
620 CheckInitializer(Init, DclT, true);
621 }
622 // If the type changed, it means we had an incomplete type that was
623 // completed by the initializer. For example:
624 // int ary[] = { 1, 3, 5 };
625 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff410e3e22007-09-12 20:13:48 +0000626 if (!VDecl->isInvalidDecl() && (DclT != SavT))
627 VDecl->setType(DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000628
629 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000630 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000631 return;
632}
633
Reid Spencer5f016e22007-07-11 17:01:13 +0000634/// The declarators are chained together backwards, reverse the list.
635Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
636 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000637 Decl *GroupDecl = static_cast<Decl*>(group);
638 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000639 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000640
641 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
642 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000643 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000644 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000645 else { // reverse the list.
646 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000647 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000648 Group->setNextDeclarator(NewGroup);
649 NewGroup = Group;
650 Group = Next;
651 }
652 }
653 // Perform semantic analysis that depends on having fully processed both
654 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000655 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000656 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
657 if (!IDecl)
658 continue;
659 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
660 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
661 QualType T = IDecl->getType();
662
663 // C99 6.7.5.2p2: If an identifier is declared to be an object with
664 // static storage duration, it shall not have a variable length array.
665 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
666 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
667 if (VLA->getSizeExpr()) {
668 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
669 IDecl->setInvalidDecl();
670 }
671 }
672 }
673 // Block scope. C99 6.7p7: If an identifier for an object is declared with
674 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
675 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
676 if (T->isIncompleteType()) {
677 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
678 T.getAsString());
679 IDecl->setInvalidDecl();
680 }
681 }
682 // File scope. C99 6.9.2p2: A declaration of an identifier for and
683 // object that has file scope without an initializer, and without a
684 // storage-class specifier or with the storage-class specifier "static",
685 // constitutes a tentative definition. Note: A tentative definition with
686 // external linkage is valid (C99 6.2.2p5).
687 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
688 // C99 6.9.2p3: If the declaration of an identifier for an object is
689 // a tentative definition and has internal linkage (C99 6.2.2p3), the
690 // declared type shall not be an incomplete type.
691 if (T->isIncompleteType()) {
692 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
693 T.getAsString());
694 IDecl->setInvalidDecl();
695 }
696 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 }
698 return NewGroup;
699}
Steve Naroffe1223f72007-08-28 03:03:08 +0000700
701// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000702ParmVarDecl *
703Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
704 Scope *FnScope) {
705 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
706
707 IdentifierInfo *II = PI.Ident;
708 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
709 // Can this happen for params? We already checked that they don't conflict
710 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000711 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000712 PI.IdentLoc, FnScope)) {
713
714 }
715
716 // FIXME: Handle storage class (auto, register). No declarator?
717 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000718
719 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
720 // Doing the promotion here has a win and a loss. The win is the type for
721 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
722 // code generator). The loss is the orginal type isn't preserved. For example:
723 //
724 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
725 // int blockvardecl[5];
726 // sizeof(parmvardecl); // size == 4
727 // sizeof(blockvardecl); // size == 20
728 // }
729 //
730 // For expressions, all implicit conversions are captured using the
731 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
732 //
733 // FIXME: If a source translation tool needs to see the original type, then
734 // we need to consider storing both types (in ParmVarDecl)...
735 //
736 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
737 if (const ArrayType *AT = parmDeclType->getAsArrayType())
738 parmDeclType = Context.getPointerType(AT->getElementType());
739 else if (parmDeclType->isFunctionType())
740 parmDeclType = Context.getPointerType(parmDeclType);
741
742 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff53a32342007-08-28 18:45:29 +0000743 VarDecl::None, 0);
744 if (PI.InvalidType)
745 New->setInvalidDecl();
746
Reid Spencer5f016e22007-07-11 17:01:13 +0000747 // If this has an identifier, add it to the scope stack.
748 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000749 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 II->setFETokenInfo(New);
751 FnScope->AddDecl(New);
752 }
753
754 return New;
755}
756
757
758Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
759 assert(CurFunctionDecl == 0 && "Function parsing confused");
760 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
761 "Not a function declarator!");
762 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
763
764 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
765 // for a K&R function.
766 if (!FTI.hasPrototype) {
767 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
768 if (FTI.ArgInfo[i].TypeInfo == 0) {
769 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
770 FTI.ArgInfo[i].Ident->getName());
771 // Implicitly declare the argument as type 'int' for lack of a better
772 // type.
773 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
774 }
775 }
776
777 // Since this is a function definition, act as though we have information
778 // about the arguments.
779 FTI.hasPrototype = true;
780 } else {
781 // FIXME: Diagnose arguments without names in C.
782
783 }
784
785 Scope *GlobalScope = FnBodyScope->getParent();
786
787 FunctionDecl *FD =
Steve Naroff08d92e42007-09-15 18:49:24 +0000788 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000789 CurFunctionDecl = FD;
790
791 // Create Decl objects for each parameter, adding them to the FunctionDecl.
792 llvm::SmallVector<ParmVarDecl*, 16> Params;
793
794 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
795 // no arguments, not a function that takes a single void argument.
796 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
797 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
798 // empty arg list, don't push any params.
799 } else {
800 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
801 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
802 }
803
804 FD->setParams(&Params[0], Params.size());
805
806 return FD;
807}
808
809Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
810 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
811 FD->setBody((Stmt*)Body);
812
813 assert(FD == CurFunctionDecl && "Function parsing confused");
814 CurFunctionDecl = 0;
815
816 // Verify and clean out per-function state.
817
818 // Check goto/label use.
819 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
820 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
821 // Verify that we have no forward references left. If so, there was a goto
822 // or address of a label taken, but no definition of it. Label fwd
823 // definitions are indicated with a null substmt.
824 if (I->second->getSubStmt() == 0) {
825 LabelStmt *L = I->second;
826 // Emit error.
827 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
828
829 // At this point, we have gotos that use the bogus label. Stitch it into
830 // the function body so that they aren't leaked and that the AST is well
831 // formed.
832 L->setSubStmt(new NullStmt(L->getIdentLoc()));
833 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
834 }
835 }
836 LabelMap.clear();
837
838 return FD;
839}
840
841
842/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
843/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000844ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
845 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000846 if (getLangOptions().C99) // Extension in C99.
847 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
848 else // Legal in C90, but warn about it.
849 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
850
851 // FIXME: handle stuff like:
852 // void foo() { extern float X(); }
853 // void bar() { X(); } <-- implicit decl for X in another scope.
854
855 // Set a Declarator for the implicit definition: int foo();
856 const char *Dummy;
857 DeclSpec DS;
858 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
859 Error = Error; // Silence warning.
860 assert(!Error && "Error setting up implicit decl!");
861 Declarator D(DS, Declarator::BlockContext);
862 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
863 D.SetIdentifier(&II, Loc);
864
865 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000866 if (Scope *FnS = S->getFnParent())
867 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000868 while (S->getParent())
869 S = S->getParent();
870
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000871 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +0000872}
873
874
875TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
Steve Naroff94745042007-09-13 23:52:58 +0000876 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000877 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
878
879 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000880 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000881
882 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +0000883 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
884 T, LastDeclarator);
885 if (D.getInvalidType())
886 NewTD->setInvalidDecl();
887 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000888}
889
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000890Sema::DeclTy *Sema::ObjcStartClassInterface(Scope* S,
891 SourceLocation AtInterfaceLoc,
Steve Naroff3536b442007-09-06 21:24:23 +0000892 IdentifierInfo *ClassName, SourceLocation ClassLoc,
893 IdentifierInfo *SuperName, SourceLocation SuperLoc,
894 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
895 AttributeList *AttrList) {
896 assert(ClassName && "Missing class identifier");
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000897
898 // Check for another declaration kind with the same name.
899 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
900 ClassLoc, S);
901 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
902 && !isa<ObjcProtocolDecl>(PrevDecl)) {
903 Diag(ClassLoc, diag::err_redefinition_different_kind,
904 ClassName->getName());
905 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
906 }
907
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +0000908 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(S, ClassName, ClassLoc);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000909 if (IDecl) {
910 // Class already seen. Is it a forward declaration?
911 if (!IDecl->getIsForwardDecl())
912 Diag(AtInterfaceLoc, diag::err_duplicate_class_def, ClassName->getName());
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000913 else {
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000914 IDecl->setIsForwardDecl(false);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000915 IDecl->AllocIntfRefProtocols(NumProtocols);
916 }
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000917 }
918 else {
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000919 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, NumProtocols, ClassName);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000920
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000921 // Chain & install the interface decl into the identifier.
922 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
923 ClassName->setFETokenInfo(IDecl);
924 }
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000925
926 if (SuperName) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000927 ObjcInterfaceDecl* SuperClassEntry = 0;
928 // Check if a different kind of symbol declared in this scope.
929 PrevDecl = LookupScopedDecl(SuperName, Decl::IDNS_Ordinary,
930 SuperLoc, S);
931 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
932 && !isa<ObjcProtocolDecl>(PrevDecl)) {
933 Diag(SuperLoc, diag::err_redefinition_different_kind,
934 SuperName->getName());
935 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000936 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000937 else {
938 // Check that super class is previously defined
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +0000939 SuperClassEntry = getObjCInterfaceDecl(S, SuperName, SuperLoc);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000940
941 if (!SuperClassEntry || SuperClassEntry->getIsForwardDecl()) {
942 Diag(AtInterfaceLoc, diag::err_undef_superclass, SuperName->getName(),
943 ClassName->getName());
944 }
945 }
946 IDecl->setSuperClass(SuperClassEntry);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000947 }
948
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000949 /// Check then save referenced protocols
950 for (unsigned int i = 0; i != NumProtocols; i++) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000951 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtocolNames[i],
952 ClassLoc);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000953 if (!RefPDecl || RefPDecl->getIsForwardProtoDecl())
954 Diag(ClassLoc, diag::err_undef_protocolref,
955 ProtocolNames[i]->getName(),
956 ClassName->getName());
957 IDecl->setIntfRefProtocols((int)i, RefPDecl);
958 }
959
Steve Naroff3536b442007-09-06 21:24:23 +0000960 return IDecl;
961}
962
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000963Sema::DeclTy *Sema::ObjcStartProtoInterface(Scope* S,
964 SourceLocation AtProtoInterfaceLoc,
Fariborz Jahanian25e077d2007-09-17 21:07:36 +0000965 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
966 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
967 assert(ProtocolName && "Missing protocol identifier");
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000968 ObjcProtocolDecl *PDecl = getObjCProtocolDecl(S, ProtocolName, ProtocolLoc);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000969 if (PDecl) {
970 // Protocol already seen. Better be a forward protocol declaration
971 if (!PDecl->getIsForwardProtoDecl())
972 Diag(ProtocolLoc, diag::err_duplicate_protocol_def,
973 ProtocolName->getName());
974 else {
975 PDecl->setIsForwardProtoDecl(false);
976 PDecl->AllocReferencedProtocols(NumProtoRefs);
977 }
978 }
979 else {
980 PDecl = new ObjcProtocolDecl(AtProtoInterfaceLoc, NumProtoRefs,
981 ProtocolName);
982 PDecl->setIsForwardProtoDecl(false);
983 // Chain & install the protocol decl into the identifier.
984 PDecl->setNext(ProtocolName->getFETokenInfo<ScopedDecl>());
985 ProtocolName->setFETokenInfo(PDecl);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000986 }
987
988 /// Check then save referenced protocols
989 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000990 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtoRefNames[i],
991 ProtocolLoc);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000992 if (!RefPDecl || RefPDecl->getIsForwardProtoDecl())
993 Diag(ProtocolLoc, diag::err_undef_protocolref,
994 ProtoRefNames[i]->getName(),
995 ProtocolName->getName());
996 PDecl->setReferencedProtocols((int)i, RefPDecl);
997 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +0000998
Fariborz Jahanian25e077d2007-09-17 21:07:36 +0000999 return PDecl;
1000}
1001
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001002/// ObjcForwardProtocolDeclaration -
1003/// Scope will always be top level file scope.
1004Action::DeclTy *
1005Sema::ObjcForwardProtocolDeclaration(Scope *S, SourceLocation AtProtocolLoc,
1006 IdentifierInfo **IdentList, unsigned NumElts) {
1007 ObjcForwardProtocolDecl *FDecl = new ObjcForwardProtocolDecl(AtProtocolLoc,
1008 NumElts);
1009
1010 for (unsigned i = 0; i != NumElts; ++i) {
1011 ObjcProtocolDecl *PDecl;
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +00001012 PDecl = getObjCProtocolDecl(S, IdentList[i], AtProtocolLoc);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001013 if (!PDecl) {// Already seen?
1014 PDecl = new ObjcProtocolDecl(SourceLocation(), 0, IdentList[i], true);
1015 // Chain & install the protocol decl into the identifier.
1016 PDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1017 IdentList[i]->setFETokenInfo(PDecl);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001018 }
1019 // Remember that this needs to be removed when the scope is popped.
1020 S->AddDecl(IdentList[i]);
1021
1022 FDecl->setForwardProtocolDecl((int)i, PDecl);
1023 }
1024 return FDecl;
1025}
1026
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001027Sema::DeclTy *Sema::ObjcStartCatInterface(Scope* S,
1028 SourceLocation AtInterfaceLoc,
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001029 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1030 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1031 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
1032 ObjcCategoryDecl *CDecl;
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001033 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(S, ClassName, ClassLoc);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001034 CDecl = new ObjcCategoryDecl(AtInterfaceLoc, NumProtoRefs, ClassName);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001035 CDecl->setClassInterface(IDecl);
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +00001036
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001037 /// Check that class of this category is already completely declared.
1038 if (!IDecl || IDecl->getIsForwardDecl())
1039 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
1040 else {
1041 /// Check for duplicate interface declaration for this category
1042 ObjcCategoryDecl *CDeclChain;
1043 for (CDeclChain = IDecl->getListCategories(); CDeclChain;
1044 CDeclChain = CDeclChain->getNextClassCategory()) {
1045 if (CDeclChain->getCatName() == CategoryName) {
1046 Diag(CategoryLoc, diag::err_dup_category_def, ClassName->getName(),
1047 CategoryName->getName());
1048 break;
1049 }
1050 }
1051 if (!CDeclChain) {
1052 CDecl->setCatName(CategoryName);
1053 CDecl->insertNextClassCategory();
1054 }
1055 }
1056
1057 /// Check then save referenced protocols
1058 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +00001059 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtoRefNames[i],
1060 CategoryLoc);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001061 if (!RefPDecl || RefPDecl->getIsForwardProtoDecl())
1062 Diag(CategoryLoc, diag::err_undef_protocolref,
1063 ProtoRefNames[i]->getName(),
1064 CategoryName->getName());
1065 CDecl->setCatReferencedProtocols((int)i, RefPDecl);
1066 }
1067
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001068 return CDecl;
1069}
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001070
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001071/// ObjcStartCategoryImplementation - Perform semantic checks on the
1072/// category implementation declaration and build an ObjcCategoryImplDecl
1073/// object.
1074Sema::DeclTy *Sema::ObjcStartCategoryImplementation(Scope* S,
1075 SourceLocation AtCatImplLoc,
1076 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1077 IdentifierInfo *CatName, SourceLocation CatLoc) {
1078 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(S, ClassName, ClassLoc);
1079 ObjcCategoryImplDecl *CDecl = new ObjcCategoryImplDecl(AtCatImplLoc,
1080 ClassName, IDecl,
1081 CatName);
1082 /// Check that class of this category is already completely declared.
1083 if (!IDecl || IDecl->getIsForwardDecl())
1084 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
1085 /// TODO: Check that CatName, category name, is not used in another
1086 // implementation.
1087 return CDecl;
1088}
1089
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001090Sema::DeclTy *Sema::ObjcStartClassImplementation(Scope *S,
1091 SourceLocation AtClassImplLoc,
1092 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1093 IdentifierInfo *SuperClassname,
1094 SourceLocation SuperClassLoc) {
1095 ObjcInterfaceDecl* IDecl = 0;
1096 // Check for another declaration kind with the same name.
1097 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
1098 ClassLoc, S);
1099 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
1100 Diag(ClassLoc, diag::err_redefinition_different_kind,
1101 ClassName->getName());
1102 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1103 }
1104 else {
1105 // Is there an interface declaration of this class; if not, warn!
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001106 IDecl = getObjCInterfaceDecl(S, ClassName, ClassLoc);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001107 if (!IDecl)
1108 Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
1109 }
1110
1111 // Check that super class name is valid class name
1112 ObjcInterfaceDecl* SDecl = 0;
1113 if (SuperClassname) {
1114 // Check if a different kind of symbol declared in this scope.
1115 PrevDecl = LookupScopedDecl(SuperClassname, Decl::IDNS_Ordinary,
1116 SuperClassLoc, S);
1117 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
1118 && !isa<ObjcProtocolDecl>(PrevDecl)) {
1119 Diag(SuperClassLoc, diag::err_redefinition_different_kind,
1120 SuperClassname->getName());
1121 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1122 }
1123 else {
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001124 SDecl = getObjCInterfaceDecl(S, SuperClassname, SuperClassLoc);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001125 if (!SDecl)
1126 Diag(SuperClassLoc, diag::err_undef_superclass,
1127 SuperClassname->getName(), ClassName->getName());
1128 else if (IDecl && IDecl->getSuperClass() != SDecl) {
1129 // This implementation and its interface do not have the same
1130 // super class.
1131 Diag(SuperClassLoc, diag::err_conflicting_super_class,
1132 SuperClassname->getName());
1133 Diag(SDecl->getLocation(), diag::err_previous_definition);
1134 }
1135 }
1136 }
1137
1138 ObjcImplementationDecl* IMPDecl =
1139 new ObjcImplementationDecl(AtClassImplLoc, ClassName, SDecl);
Fariborz Jahanian0da1c102007-09-25 21:00:20 +00001140 if (!IDecl) {
1141 // Legacy case of @implementation with no corresponding @interface.
1142 // Build, chain & install the interface decl into the identifier.
1143 IDecl = new ObjcInterfaceDecl(AtClassImplLoc, 0, ClassName);
1144 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
1145 ClassName->setFETokenInfo(IDecl);
1146
1147 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001148
1149 // Check that there is no duplicate implementation of this class.
1150 bool err = false;
1151 for (unsigned i = 0; i != Context.sizeObjcImplementationClass(); i++) {
1152 if (Context.getObjcImplementationClass(i)->getIdentifier() == ClassName) {
1153 Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
1154 err = true;
1155 break;
1156 }
1157 }
1158 if (!err)
1159 Context.setObjcImplementationClass(IMPDecl);
1160
1161 return IMPDecl;
1162}
1163
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001164void Sema::ActOnImpleIvarVsClassIvars(DeclTy *ClassDecl,
1165 DeclTy **Fields, unsigned numIvars) {
1166 ObjcInterfaceDecl* IDecl =
1167 cast<ObjcInterfaceDecl>(static_cast<Decl*>(ClassDecl));
1168 assert(IDecl && "missing named interface class decl");
1169 ObjcIvarDecl** ivars = reinterpret_cast<ObjcIvarDecl**>(Fields);
1170 assert(ivars && "missing @implementation ivars");
1171
1172 // Check interface's Ivar list against those in the implementation.
1173 // names and types must match.
1174 //
1175 ObjcIvarDecl** IntfIvars = IDecl->getIntfDeclIvars();
1176 int IntfNumIvars = IDecl->getIntfDeclNumIvars();
1177 unsigned j = 0;
1178 bool err = false;
1179 while (numIvars > 0 && IntfNumIvars > 0) {
1180 ObjcIvarDecl* ImplIvar = ivars[j];
1181 ObjcIvarDecl* ClsIvar = IntfIvars[j++];
1182 assert (ImplIvar && "missing implementation ivar");
1183 assert (ClsIvar && "missing class ivar");
1184 if (ImplIvar->getCanonicalType() != ClsIvar->getCanonicalType()) {
1185 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
1186 ImplIvar->getIdentifier()->getName());
1187 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1188 ClsIvar->getIdentifier()->getName());
1189 }
1190 // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
1191 // as error.
1192 else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1193 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
1194 ImplIvar->getIdentifier()->getName());
1195 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1196 ClsIvar->getIdentifier()->getName());
1197 err = true;
1198 break;
1199 }
1200 --numIvars;
1201 --IntfNumIvars;
1202 }
1203 if (!err && (numIvars > 0 || IntfNumIvars > 0))
1204 Diag(numIvars > 0 ? ivars[j]->getLocation() : IntfIvars[j]->getLocation(),
1205 diag::err_inconsistant_ivar);
1206
1207}
1208
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001209/// CheckProtocolMethodDefs - This routine checks unimpletented methods
1210/// Declared in protocol, and those referenced by it.
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001211void Sema::CheckProtocolMethodDefs(ObjcProtocolDecl *PDecl,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001212 const llvm::DenseMap<void *, char>& InsMap,
1213 const llvm::DenseMap<void *, char>& ClsMap) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001214 // check unimplemented instance methods.
1215 ObjcMethodDecl** methods = PDecl->getInsMethods();
1216 for (int j = 0; j < PDecl->getNumInsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001217 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001218 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001219 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1220 methods[j]->getSelector().getName(buf));
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001221 }
1222 // check unimplemented class methods
1223 methods = PDecl->getClsMethods();
1224 for (int j = 0; j < PDecl->getNumClsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001225 if (!ClsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001226 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001227 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1228 methods[j]->getSelector().getName(buf));
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001229 }
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001230
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001231 // Check on this protocols's referenced protocols, recursively
1232 ObjcProtocolDecl** RefPDecl = PDecl->getReferencedProtocols();
1233 for (int i = 0; i < PDecl->getNumReferencedProtocols(); i++)
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001234 CheckProtocolMethodDefs(RefPDecl[i], InsMap, ClsMap);
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001235}
1236
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001237void Sema::ImplMethodsVsClassMethods(ObjcImplementationDecl* IMPDecl,
1238 ObjcInterfaceDecl* IDecl) {
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001239 llvm::DenseMap<void *, char> InsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001240 // Check and see if instance methods in class interface have been
1241 // implemented in the implementation class.
1242 ObjcMethodDecl **methods = IMPDecl->getInsMethods();
1243 for (int i=0; i < IMPDecl->getNumInsMethods(); i++) {
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001244 InsMap[methods[i]->getSelector().getAsOpaquePtr()] = 'a';
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001245 }
1246
1247 methods = IDecl->getInsMethods();
1248 for (int j = 0; j < IDecl->getNumInsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001249 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001250 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001251 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1252 methods[j]->getSelector().getName(buf));
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001253 }
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001254 llvm::DenseMap<void *, char> ClsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001255 // Check and see if class methods in class interface have been
1256 // implemented in the implementation class.
1257 methods = IMPDecl->getClsMethods();
1258 for (int i=0; i < IMPDecl->getNumClsMethods(); i++) {
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001259 ClsMap[methods[i]->getSelector().getAsOpaquePtr()] = 'a';
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001260 }
1261
1262 methods = IDecl->getClsMethods();
1263 for (int j = 0; j < IDecl->getNumClsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001264 if (!ClsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001265 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001266 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1267 methods[j]->getSelector().getName(buf));
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001268 }
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001269
1270 // Check the protocol list for unimplemented methods in the @implementation
1271 // class.
1272 ObjcProtocolDecl** protocols = IDecl->getIntfRefProtocols();
1273 for (int i = 0; i < IDecl->getNumIntfRefProtocols(); i++) {
1274 ObjcProtocolDecl* PDecl = protocols[i];
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001275 CheckProtocolMethodDefs(PDecl, InsMap, ClsMap);
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001276 }
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001277}
1278
1279/// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
1280/// category interface is implemented in the category @implementation.
1281void Sema::ImplCategoryMethodsVsIntfMethods(ObjcCategoryImplDecl *CatImplDecl,
1282 ObjcCategoryDecl *CatClassDecl) {
1283 llvm::DenseMap<void *, char> InsMap;
1284 // Check and see if instance methods in category interface have been
1285 // implemented in its implementation class.
1286 ObjcMethodDecl **methods = CatImplDecl->getCatInsMethods();
1287 for (int i=0; i < CatImplDecl->getNumCatInsMethods(); i++) {
1288 InsMap[methods[i]->getSelector().getAsOpaquePtr()] = 'a';
1289 }
1290
1291 methods = CatClassDecl->getCatInsMethods();
1292 for (int j = 0; j < CatClassDecl->getNumCatInsMethods(); j++)
1293 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
1294 llvm::SmallString<128> buf;
1295 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1296 methods[j]->getSelector().getName(buf));
1297 }
1298 llvm::DenseMap<void *, char> ClsMap;
1299 // Check and see if class methods in category interface have been
1300 // implemented in its implementation class.
1301 methods = CatImplDecl->getCatClsMethods();
1302 for (int i=0; i < CatImplDecl->getNumCatClsMethods(); i++) {
1303 ClsMap[methods[i]->getSelector().getAsOpaquePtr()] = 'a';
1304 }
1305
1306 methods = CatClassDecl->getCatClsMethods();
1307 for (int j = 0; j < CatClassDecl->getNumCatClsMethods(); j++)
1308 if (!ClsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
1309 llvm::SmallString<128> buf;
1310 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1311 methods[j]->getSelector().getName(buf));
1312 }
1313
1314 // Check the protocol list for unimplemented methods in the @implementation
1315 // class.
1316 ObjcProtocolDecl** protocols = CatClassDecl->getCatReferencedProtocols();
1317 for (int i = 0; i < CatClassDecl->getNumCatReferencedProtocols(); i++) {
1318 ObjcProtocolDecl* PDecl = protocols[i];
1319 CheckProtocolMethodDefs(PDecl, InsMap, ClsMap);
1320 }
1321
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001322}
1323
Steve Naroff3536b442007-09-06 21:24:23 +00001324/// ObjcClassDeclaration -
1325/// Scope will always be top level file scope.
1326Action::DeclTy *
1327Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
1328 IdentifierInfo **IdentList, unsigned NumElts) {
1329 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
1330
1331 for (unsigned i = 0; i != NumElts; ++i) {
1332 ObjcInterfaceDecl *IDecl;
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001333 IDecl = getObjCInterfaceDecl(S, IdentList[i], AtClassLoc);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001334 if (!IDecl) {// Already seen?
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001335 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, IdentList[i], true);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001336 // Chain & install the interface decl into the identifier.
1337 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1338 IdentList[i]->setFETokenInfo(IDecl);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001339 }
Steve Naroff3536b442007-09-06 21:24:23 +00001340 // Remember that this needs to be removed when the scope is popped.
1341 S->AddDecl(IdentList[i]);
1342
1343 CDecl->setInterfaceDecl((int)i, IDecl);
1344 }
1345 return CDecl;
1346}
1347
Reid Spencer5f016e22007-07-11 17:01:13 +00001348
Steve Naroff08d92e42007-09-15 18:49:24 +00001349/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001350/// former case, Name will be non-null. In the later case, Name will be null.
1351/// TagType indicates what kind of tag this is. TK indicates whether this is a
1352/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001353Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001354 SourceLocation KWLoc, IdentifierInfo *Name,
1355 SourceLocation NameLoc, AttributeList *Attr) {
1356 // If this is a use of an existing tag, it must have a name.
1357 assert((Name != 0 || TK == TK_Definition) &&
1358 "Nameless record must be a definition!");
1359
1360 Decl::Kind Kind;
1361 switch (TagType) {
1362 default: assert(0 && "Unknown tag type!");
1363 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1364 case DeclSpec::TST_union: Kind = Decl::Union; break;
1365//case DeclSpec::TST_class: Kind = Decl::Class; break;
1366 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1367 }
1368
1369 // If this is a named struct, check to see if there was a previous forward
1370 // declaration or definition.
1371 if (TagDecl *PrevDecl =
1372 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1373 NameLoc, S))) {
1374
1375 // If this is a use of a previous tag, or if the tag is already declared in
1376 // the same scope (so that the definition/declaration completes or
1377 // rementions the tag), reuse the decl.
1378 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1379 // Make sure that this wasn't declared as an enum and now used as a struct
1380 // or something similar.
1381 if (PrevDecl->getKind() != Kind) {
1382 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1383 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1384 }
1385
1386 // If this is a use or a forward declaration, we're good.
1387 if (TK != TK_Definition)
1388 return PrevDecl;
1389
1390 // Diagnose attempts to redefine a tag.
1391 if (PrevDecl->isDefinition()) {
1392 Diag(NameLoc, diag::err_redefinition, Name->getName());
1393 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1394 // If this is a redefinition, recover by making this struct be
1395 // anonymous, which will make any later references get the previous
1396 // definition.
1397 Name = 0;
1398 } else {
1399 // Okay, this is definition of a previously declared or referenced tag.
1400 // Move the location of the decl to be the definition site.
1401 PrevDecl->setLocation(NameLoc);
1402 return PrevDecl;
1403 }
1404 }
1405 // If we get here, this is a definition of a new struct type in a nested
1406 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1407 // type.
1408 }
1409
1410 // If there is an identifier, use the location of the identifier as the
1411 // location of the decl, otherwise use the location of the struct/union
1412 // keyword.
1413 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1414
1415 // Otherwise, if this is the first time we've seen this tag, create the decl.
1416 TagDecl *New;
1417 switch (Kind) {
1418 default: assert(0 && "Unknown tag kind!");
1419 case Decl::Enum:
1420 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1421 // enum X { A, B, C } D; D should chain to X.
1422 New = new EnumDecl(Loc, Name, 0);
1423 // If this is an undefined enum, warn.
1424 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1425 break;
1426 case Decl::Union:
1427 case Decl::Struct:
1428 case Decl::Class:
1429 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1430 // struct X { int A; } D; D should chain to X.
1431 New = new RecordDecl(Kind, Loc, Name, 0);
1432 break;
1433 }
1434
1435 // If this has an identifier, add it to the scope stack.
1436 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001437 // The scope passed in may not be a decl scope. Zip up the scope tree until
1438 // we find one that is.
1439 while ((S->getFlags() & Scope::DeclScope) == 0)
1440 S = S->getParent();
1441
1442 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001443 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 Name->setFETokenInfo(New);
1445 S->AddDecl(New);
1446 }
1447
1448 return New;
1449}
1450
Steve Naroff08d92e42007-09-15 18:49:24 +00001451/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001452/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001453Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001454 SourceLocation DeclStart,
1455 Declarator &D, ExprTy *BitfieldWidth) {
1456 IdentifierInfo *II = D.getIdentifier();
1457 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 SourceLocation Loc = DeclStart;
1459 if (II) Loc = D.getIdentifierLoc();
1460
1461 // FIXME: Unnamed fields can be handled in various different ways, for
1462 // example, unnamed unions inject all members into the struct namespace!
1463
1464
1465 if (BitWidth) {
1466 // TODO: Validate.
1467 //printf("WARNING: BITFIELDS IGNORED!\n");
1468
1469 // 6.7.2.1p3
1470 // 6.7.2.1p4
1471
1472 } else {
1473 // Not a bitfield.
1474
1475 // validate II.
1476
1477 }
1478
1479 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001480 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1481 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001482
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1484 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001485 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1486 Diag(Loc, diag::err_typecheck_illegal_vla,
1487 VAT->getSizeExpr()->getSourceRange());
1488 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001491 FieldDecl *NewFD;
1492
1493 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001494 NewFD = new FieldDecl(Loc, II, T);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001495 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl))
1496 || isa<ObjcImplementationDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001497 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001498 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001499 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001500
Steve Naroff5912a352007-08-28 20:14:24 +00001501 if (D.getInvalidType() || InvalidDecl)
1502 NewFD->setInvalidDecl();
1503 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001504}
1505
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001506/// TranslateIvarVisibility - Translate visibility from a token ID to an
1507/// AST enum value.
1508static ObjcIvarDecl::AccessControl
1509TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001510 switch (ivarVisibility) {
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001511 case tok::objc_private: return ObjcIvarDecl::Private;
1512 case tok::objc_public: return ObjcIvarDecl::Public;
1513 case tok::objc_protected: return ObjcIvarDecl::Protected;
1514 case tok::objc_package: return ObjcIvarDecl::Package;
1515 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001516 }
1517}
1518
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001519void Sema::ActOnFields(Scope* S,
1520 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001521 DeclTy **Fields, unsigned NumFields,
1522 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001523 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1524 assert(EnclosingDecl && "missing record or interface decl");
1525 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1526
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001527 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 // Diagnose code like:
1529 // struct S { struct S {} X; };
1530 // We discover this when we complete the outer S. Reject and ignore the
1531 // outer S.
1532 Diag(Record->getLocation(), diag::err_nested_redefinition,
1533 Record->getKindName());
1534 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001535 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 return;
1537 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 // Verify that all the fields are okay.
1539 unsigned NumNamedMembers = 0;
1540 llvm::SmallVector<FieldDecl*, 32> RecFields;
1541 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001542
Reid Spencer5f016e22007-07-11 17:01:13 +00001543 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001544
Steve Naroff74216642007-09-14 22:20:54 +00001545 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1546 assert(FD && "missing field decl");
1547
1548 // Remember all fields.
1549 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001550
1551 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001552 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001553
Steve Narofff13271f2007-09-14 23:09:53 +00001554 // If we have visibility info, make sure the AST is set accordingly.
1555 if (visibility)
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001556 cast<ObjcIvarDecl>(FD)->setAccessControl(
1557 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001558
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001560 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001561 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001562 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001563 FD->setInvalidDecl();
1564 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 continue;
1566 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1568 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001569 if (!Record) { // Incomplete ivar type is always an error.
1570 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001571 FD->setInvalidDecl();
1572 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001573 continue;
1574 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 if (i != NumFields-1 || // ... that the last member ...
1576 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001577 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001579 FD->setInvalidDecl();
1580 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 continue;
1582 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001583 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001584 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1585 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001586 FD->setInvalidDecl();
1587 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001588 continue;
1589 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001590 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001591 if (Record)
1592 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1595 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001596 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1598 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001599 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 Record->setHasFlexibleArrayMember(true);
1601 } else {
1602 // If this is a struct/class and this is not the last element, reject
1603 // it. Note that GCC supports variable sized arrays in the middle of
1604 // structures.
1605 if (i != NumFields-1) {
1606 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1607 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001608 FD->setInvalidDecl();
1609 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 continue;
1611 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 // We support flexible arrays at the end of structs in other structs
1613 // as an extension.
1614 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1615 FD->getName());
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001616 if (Record)
1617 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 }
1619 }
1620 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001621 // Keep track of the number of named members.
1622 if (IdentifierInfo *II = FD->getIdentifier()) {
1623 // Detect duplicate member names.
1624 if (!FieldIDs.insert(II)) {
1625 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1626 // Find the previous decl.
1627 SourceLocation PrevLoc;
1628 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1629 assert(i != e && "Didn't find previous def!");
1630 if (RecFields[i]->getIdentifier() == II) {
1631 PrevLoc = RecFields[i]->getLocation();
1632 break;
1633 }
1634 }
1635 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001636 FD->setInvalidDecl();
1637 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 continue;
1639 }
1640 ++NumNamedMembers;
1641 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001642 }
1643
Reid Spencer5f016e22007-07-11 17:01:13 +00001644 // Okay, we successfully defined 'Record'.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001645 if (Record)
1646 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001647 else {
1648 ObjcIvarDecl **ClsFields =
1649 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001650 if (isa<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1651 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1652 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1653 else if (isa<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1654 ObjcImplementationDecl* IMPDecl =
1655 cast<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl));
1656 assert(IMPDecl && "ActOnFields - missing ObjcImplementationDecl");
1657 IMPDecl->ObjcAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001658 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(S,
1659 IMPDecl->getIdentifier(), RecLoc);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001660 if (IDecl)
1661 ActOnImpleIvarVsClassIvars(static_cast<DeclTy*>(IDecl),
1662 reinterpret_cast<DeclTy**>(&RecFields[0]), RecFields.size());
1663 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001664 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001665}
1666
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001667void Sema::ObjcAddMethodsToClass(Scope* S, DeclTy *ClassDecl,
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001668 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001669 // FIXME: Fix this when we can handle methods declared in protocols.
1670 // See Parser::ParseObjCAtProtocolDeclaration
1671 if (!ClassDecl)
1672 return;
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001673 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1674 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1675
1676 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001677 ObjcMethodDecl *Method =
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001678 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1679 if (!Method) continue; // Already issued a diagnostic.
1680 if (Method->isInstance())
1681 insMethods.push_back(Method);
1682 else
1683 clsMethods.push_back(Method);
1684 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001685 if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(ClassDecl))) {
1686 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1687 static_cast<Decl*>(ClassDecl));
1688 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1689 &clsMethods[0], clsMethods.size());
1690 }
1691 else if (isa<ObjcProtocolDecl>(static_cast<Decl *>(ClassDecl))) {
1692 ObjcProtocolDecl *Protocol = cast<ObjcProtocolDecl>(
1693 static_cast<Decl*>(ClassDecl));
1694 Protocol->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1695 &clsMethods[0], clsMethods.size());
1696 }
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001697 else if (isa<ObjcCategoryDecl>(static_cast<Decl *>(ClassDecl))) {
1698 ObjcCategoryDecl *Category = cast<ObjcCategoryDecl>(
1699 static_cast<Decl*>(ClassDecl));
1700 Category->ObjcAddCatMethods(&insMethods[0], insMethods.size(),
1701 &clsMethods[0], clsMethods.size());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001702 }
1703 else if (isa<ObjcImplementationDecl>(static_cast<Decl *>(ClassDecl))) {
1704 ObjcImplementationDecl* ImplClass = cast<ObjcImplementationDecl>(
1705 static_cast<Decl*>(ClassDecl));
1706 ImplClass->ObjcAddImplMethods(&insMethods[0], insMethods.size(),
1707 &clsMethods[0], clsMethods.size());
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001708 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(S,
1709 ImplClass->getIdentifier(), SourceLocation());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001710 if (IDecl)
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001711 ImplMethodsVsClassMethods(ImplClass, IDecl);
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001712 }
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001713 else if (isa<ObjcCategoryImplDecl>(static_cast<Decl *>(ClassDecl))) {
1714 ObjcCategoryImplDecl* CatImplClass = cast<ObjcCategoryImplDecl>(
1715 static_cast<Decl*>(ClassDecl));
1716 CatImplClass->ObjcAddCatImplMethods(&insMethods[0], insMethods.size(),
1717 &clsMethods[0], clsMethods.size());
1718 ObjcInterfaceDecl* IDecl = CatImplClass->getClassInterface();
1719 // Find category interface decl and then check that all methods declared
1720 // in this interface is implemented in the category @implementation.
1721 if (IDecl) {
1722 for (ObjcCategoryDecl *Categories = IDecl->getListCategories();
1723 Categories; Categories = Categories->getNextClassCategory()) {
1724 if (Categories->getCatName() == CatImplClass->getObjcCatName()) {
1725 ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
1726 break;
1727 }
1728 }
1729 }
1730 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001731 else
1732 assert(0 && "Sema::ObjcAddMethodsToClass(): Unknown DeclTy");
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001733 return;
1734}
1735
Fariborz Jahanian00933592007-09-18 00:25:23 +00001736Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001737 tok::TokenKind MethodType, TypeTy *ReturnType, Selector Sel,
Steve Naroff68d331a2007-09-27 14:38:14 +00001738 // optional arguments. The number of types/arguments is obtained
1739 // from the Sel.getNumArgs().
1740 TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1741 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001742 llvm::SmallVector<ParmVarDecl*, 16> Params;
1743
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001744 for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001745 // FIXME: arg->AttrList must be stored too!
Steve Naroff68d331a2007-09-27 14:38:14 +00001746 ParmVarDecl* Param = new ParmVarDecl(SourceLocation(/*FIXME*/), ArgNames[i],
1747 QualType::getFromOpaquePtr(ArgTypes[i]),
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001748 VarDecl::None, 0);
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001749 Params.push_back(Param);
1750 }
1751 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Steve Naroff68d331a2007-09-27 14:38:14 +00001752 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc, Sel,
1753 resultDeclType, 0, -1, AttrList,
Fariborz Jahanian3a63da72007-09-29 18:24:58 +00001754 MethodType == tok::minus,
1755 MethodDeclKind == tok::objc_optional ?
1756 ObjcMethodDecl::Optional :
1757 ObjcMethodDecl::Required);
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001758 ObjcMethod->setMethodParams(&Params[0], Sel.getNumArgs());
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001759 return ObjcMethod;
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001760}
1761
Steve Naroff08d92e42007-09-15 18:49:24 +00001762Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001763 DeclTy *lastEnumConst,
1764 SourceLocation IdLoc, IdentifierInfo *Id,
1765 SourceLocation EqualLoc, ExprTy *val) {
1766 theEnumDecl = theEnumDecl; // silence unused warning.
1767 EnumConstantDecl *LastEnumConst =
1768 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1769 Expr *Val = static_cast<Expr*>(val);
1770
Chris Lattner31e05722007-08-26 06:24:45 +00001771 // The scope passed in may not be a decl scope. Zip up the scope tree until
1772 // we find one that is.
1773 while ((S->getFlags() & Scope::DeclScope) == 0)
1774 S = S->getParent();
1775
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 // Verify that there isn't already something declared with this name in this
1777 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001778 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1779 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001780 if (S->isDeclScope(PrevDecl)) {
1781 if (isa<EnumConstantDecl>(PrevDecl))
1782 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1783 else
1784 Diag(IdLoc, diag::err_redefinition, Id->getName());
1785 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1786 // FIXME: Don't leak memory: delete Val;
1787 return 0;
1788 }
1789 }
1790
1791 llvm::APSInt EnumVal(32);
1792 QualType EltTy;
1793 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001794 // Make sure to promote the operand type to int.
1795 UsualUnaryConversions(Val);
1796
Reid Spencer5f016e22007-07-11 17:01:13 +00001797 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1798 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001799 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001800 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1801 Id->getName());
1802 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001803 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001804 } else {
1805 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001806 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001807 }
1808
1809 if (!Val) {
1810 if (LastEnumConst) {
1811 // Assign the last value + 1.
1812 EnumVal = LastEnumConst->getInitVal();
1813 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001814
1815 // Check for overflow on increment.
1816 if (EnumVal < LastEnumConst->getInitVal())
1817 Diag(IdLoc, diag::warn_enum_value_overflow);
1818
Chris Lattnerb7416f92007-08-27 17:37:24 +00001819 EltTy = LastEnumConst->getType();
1820 } else {
1821 // First value, set to zero.
1822 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001823 EnumVal.zextOrTrunc(
1824 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001825 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001826 }
1827
Reid Spencer5f016e22007-07-11 17:01:13 +00001828 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1829 LastEnumConst);
1830
1831 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001832 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001833 Id->setFETokenInfo(New);
1834 S->AddDecl(New);
1835 return New;
1836}
1837
Steve Naroff08d92e42007-09-15 18:49:24 +00001838void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001839 DeclTy **Elements, unsigned NumElements) {
1840 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1841 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1842
Chris Lattnere37f0be2007-08-28 05:10:31 +00001843 // TODO: If the result value doesn't fit in an int, it must be a long or long
1844 // long value. ISO C does not support this, but GCC does as an extension,
1845 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001846 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001847
1848
Chris Lattnerac609682007-08-28 06:15:15 +00001849 // Verify that all the values are okay, compute the size of the values, and
1850 // reverse the list.
1851 unsigned NumNegativeBits = 0;
1852 unsigned NumPositiveBits = 0;
1853
1854 // Keep track of whether all elements have type int.
1855 bool AllElementsInt = true;
1856
Reid Spencer5f016e22007-07-11 17:01:13 +00001857 EnumConstantDecl *EltList = 0;
1858 for (unsigned i = 0; i != NumElements; ++i) {
1859 EnumConstantDecl *ECD =
1860 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1861 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001862
1863 // If the enum value doesn't fit in an int, emit an extension warning.
1864 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1865 "Should have promoted value to int");
1866 const llvm::APSInt &InitVal = ECD->getInitVal();
1867 if (InitVal.getBitWidth() > IntWidth) {
1868 llvm::APSInt V(InitVal);
1869 V.trunc(IntWidth);
1870 V.extend(InitVal.getBitWidth());
1871 if (V != InitVal)
1872 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1873 InitVal.toString());
1874 }
Chris Lattnerac609682007-08-28 06:15:15 +00001875
1876 // Keep track of the size of positive and negative values.
1877 if (InitVal.isUnsigned() || !InitVal.isNegative())
1878 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1879 else
1880 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001881
Chris Lattnerac609682007-08-28 06:15:15 +00001882 // Keep track of whether every enum element has type int (very commmon).
1883 if (AllElementsInt)
1884 AllElementsInt = ECD->getType() == Context.IntTy;
1885
Reid Spencer5f016e22007-07-11 17:01:13 +00001886 ECD->setNextDeclarator(EltList);
1887 EltList = ECD;
1888 }
1889
Chris Lattnerac609682007-08-28 06:15:15 +00001890 // Figure out the type that should be used for this enum.
1891 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1892 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001893 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001894
1895 if (NumNegativeBits) {
1896 // If there is a negative value, figure out the smallest integer type (of
1897 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001898 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001899 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001900 BestWidth = IntWidth;
1901 } else {
1902 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1903 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001904 BestType = Context.LongTy;
1905 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001906 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1907 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001908 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1909 BestType = Context.LongLongTy;
1910 }
1911 }
1912 } else {
1913 // If there is no negative value, figure out which of uint, ulong, ulonglong
1914 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001915 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001916 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001917 BestWidth = IntWidth;
1918 } else if (NumPositiveBits <=
1919 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001920 BestType = Context.UnsignedLongTy;
1921 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001922 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1923 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001924 "How could an initializer get larger than ULL?");
1925 BestType = Context.UnsignedLongLongTy;
1926 }
1927 }
1928
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001929 // Loop over all of the enumerator constants, changing their types to match
1930 // the type of the enum if needed.
1931 for (unsigned i = 0; i != NumElements; ++i) {
1932 EnumConstantDecl *ECD =
1933 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1934 if (!ECD) continue; // Already issued a diagnostic.
1935
1936 // Standard C says the enumerators have int type, but we allow, as an
1937 // extension, the enumerators to be larger than int size. If each
1938 // enumerator value fits in an int, type it as an int, otherwise type it the
1939 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1940 // that X has type 'int', not 'unsigned'.
1941 if (ECD->getType() == Context.IntTy)
1942 continue; // Already int type.
1943
1944 // Determine whether the value fits into an int.
1945 llvm::APSInt InitVal = ECD->getInitVal();
1946 bool FitsInInt;
1947 if (InitVal.isUnsigned() || !InitVal.isNegative())
1948 FitsInInt = InitVal.getActiveBits() < IntWidth;
1949 else
1950 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1951
1952 // If it fits into an integer type, force it. Otherwise force it to match
1953 // the enum decl type.
1954 QualType NewTy;
1955 unsigned NewWidth;
1956 bool NewSign;
1957 if (FitsInInt) {
1958 NewTy = Context.IntTy;
1959 NewWidth = IntWidth;
1960 NewSign = true;
1961 } else if (ECD->getType() == BestType) {
1962 // Already the right type!
1963 continue;
1964 } else {
1965 NewTy = BestType;
1966 NewWidth = BestWidth;
1967 NewSign = BestType->isSignedIntegerType();
1968 }
1969
1970 // Adjust the APSInt value.
1971 InitVal.extOrTrunc(NewWidth);
1972 InitVal.setIsSigned(NewSign);
1973 ECD->setInitVal(InitVal);
1974
1975 // Adjust the Expr initializer and type.
1976 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1977 ECD->setType(NewTy);
1978 }
Chris Lattnerac609682007-08-28 06:15:15 +00001979
Chris Lattnere00b18c2007-08-28 18:24:31 +00001980 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001981}
1982
1983void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1984 if (!current) return;
1985
1986 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1987 // remember this in the LastInGroupList list.
1988 if (last)
1989 LastInGroupList.push_back((Decl*)last);
1990}
1991
1992void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1993 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1994 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1995 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1996 if (!newType.isNull()) // install the new vector type into the decl
1997 vDecl->setType(newType);
1998 }
1999 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2000 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
2001 rawAttr);
2002 if (!newType.isNull()) // install the new vector type into the decl
2003 tDecl->setUnderlyingType(newType);
2004 }
2005 }
Steve Naroff73322922007-07-18 18:00:27 +00002006 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00002007 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
2008 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
2009 else
Steve Naroff73322922007-07-18 18:00:27 +00002010 Diag(rawAttr->getAttributeLoc(),
2011 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00002012 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002013 // FIXME: add other attributes...
2014}
2015
2016void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2017 AttributeList *declarator_postfix) {
2018 while (declspec_prefix) {
2019 HandleDeclAttribute(New, declspec_prefix);
2020 declspec_prefix = declspec_prefix->getNext();
2021 }
2022 while (declarator_postfix) {
2023 HandleDeclAttribute(New, declarator_postfix);
2024 declarator_postfix = declarator_postfix->getNext();
2025 }
2026}
2027
Steve Naroffbea0b342007-07-29 16:33:31 +00002028void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2029 AttributeList *rawAttr) {
2030 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00002031 // check the attribute arugments.
2032 if (rawAttr->getNumArgs() != 1) {
2033 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2034 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002035 return;
Steve Naroff73322922007-07-18 18:00:27 +00002036 }
2037 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2038 llvm::APSInt vecSize(32);
2039 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
2040 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2041 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002042 return;
Steve Naroff73322922007-07-18 18:00:27 +00002043 }
2044 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2045 // in conjunction with complex types (pointers, arrays, functions, etc.).
2046 Type *canonType = curType.getCanonicalType().getTypePtr();
2047 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2048 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2049 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002050 return;
Steve Naroff73322922007-07-18 18:00:27 +00002051 }
2052 // unlike gcc's vector_size attribute, the size is specified as the
2053 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002054 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002055
2056 if (vectorSize == 0) {
2057 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2058 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002059 return;
Steve Naroff73322922007-07-18 18:00:27 +00002060 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002061 // Instantiate/Install the vector type, the number of elements is > 0.
2062 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2063 // Remember this typedef decl, we will need it later for diagnostics.
2064 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002065}
2066
Reid Spencer5f016e22007-07-11 17:01:13 +00002067QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002068 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002069 // check the attribute arugments.
2070 if (rawAttr->getNumArgs() != 1) {
2071 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2072 std::string("1"));
2073 return QualType();
2074 }
2075 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2076 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002077 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002078 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2079 sizeExpr->getSourceRange());
2080 return QualType();
2081 }
2082 // navigate to the base type - we need to provide for vector pointers,
2083 // vector arrays, and functions returning vectors.
2084 Type *canonType = curType.getCanonicalType().getTypePtr();
2085
Steve Naroff73322922007-07-18 18:00:27 +00002086 if (canonType->isPointerType() || canonType->isArrayType() ||
2087 canonType->isFunctionType()) {
2088 assert(1 && "HandleVector(): Complex type construction unimplemented");
2089 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2090 do {
2091 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2092 canonType = PT->getPointeeType().getTypePtr();
2093 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2094 canonType = AT->getElementType().getTypePtr();
2095 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2096 canonType = FT->getResultType().getTypePtr();
2097 } while (canonType->isPointerType() || canonType->isArrayType() ||
2098 canonType->isFunctionType());
2099 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002100 }
2101 // the base type must be integer or float.
2102 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2103 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2104 curType.getCanonicalType().getAsString());
2105 return QualType();
2106 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00002107 unsigned typeSize = static_cast<unsigned>(
2108 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002110 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002111
2112 // the vector size needs to be an integral multiple of the type size.
2113 if (vectorSize % typeSize) {
2114 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
2115 sizeExpr->getSourceRange());
2116 return QualType();
2117 }
2118 if (vectorSize == 0) {
2119 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2120 sizeExpr->getSourceRange());
2121 return QualType();
2122 }
2123 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
2124 // the number of elements to be a power of two (unlike GCC).
2125 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00002126 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002127}
2128