blob: c6c1b1ecc0c4d5f20d918da0be7eddf8df7ee61b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Builtins.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/Type.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Parse/Scope.h"
22#include "clang/Lex/IdentifierTable.h"
23#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
Steve Naroff563477d2007-09-18 23:55:05 +000025#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "llvm/ADT/SmallSet.h"
27using namespace clang;
28
Reid Spencer5f016e22007-07-11 17:01:13 +000029Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Steve Naroff3536b442007-09-06 21:24:23 +000030 Decl *IIDecl = II.getFETokenInfo<Decl>();
31 if (dyn_cast_or_null<TypedefDecl>(IIDecl) ||
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +000032 dyn_cast_or_null<ObjcInterfaceDecl>(IIDecl))
Steve Naroff3536b442007-09-06 21:24:23 +000033 return IIDecl;
34 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 Jahanianccb4f312007-09-25 18:38:09 +00001071Sema::DeclTy *Sema::ObjcStartClassImplementation(Scope *S,
1072 SourceLocation AtClassImplLoc,
1073 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1074 IdentifierInfo *SuperClassname,
1075 SourceLocation SuperClassLoc) {
1076 ObjcInterfaceDecl* IDecl = 0;
1077 // Check for another declaration kind with the same name.
1078 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
1079 ClassLoc, S);
1080 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
1081 Diag(ClassLoc, diag::err_redefinition_different_kind,
1082 ClassName->getName());
1083 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1084 }
1085 else {
1086 // Is there an interface declaration of this class; if not, warn!
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001087 IDecl = getObjCInterfaceDecl(S, ClassName, ClassLoc);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001088 if (!IDecl)
1089 Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
1090 }
1091
1092 // Check that super class name is valid class name
1093 ObjcInterfaceDecl* SDecl = 0;
1094 if (SuperClassname) {
1095 // Check if a different kind of symbol declared in this scope.
1096 PrevDecl = LookupScopedDecl(SuperClassname, Decl::IDNS_Ordinary,
1097 SuperClassLoc, S);
1098 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
1099 && !isa<ObjcProtocolDecl>(PrevDecl)) {
1100 Diag(SuperClassLoc, diag::err_redefinition_different_kind,
1101 SuperClassname->getName());
1102 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1103 }
1104 else {
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001105 SDecl = getObjCInterfaceDecl(S, SuperClassname, SuperClassLoc);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001106 if (!SDecl)
1107 Diag(SuperClassLoc, diag::err_undef_superclass,
1108 SuperClassname->getName(), ClassName->getName());
1109 else if (IDecl && IDecl->getSuperClass() != SDecl) {
1110 // This implementation and its interface do not have the same
1111 // super class.
1112 Diag(SuperClassLoc, diag::err_conflicting_super_class,
1113 SuperClassname->getName());
1114 Diag(SDecl->getLocation(), diag::err_previous_definition);
1115 }
1116 }
1117 }
1118
1119 ObjcImplementationDecl* IMPDecl =
1120 new ObjcImplementationDecl(AtClassImplLoc, ClassName, SDecl);
Fariborz Jahanian0da1c102007-09-25 21:00:20 +00001121 if (!IDecl) {
1122 // Legacy case of @implementation with no corresponding @interface.
1123 // Build, chain & install the interface decl into the identifier.
1124 IDecl = new ObjcInterfaceDecl(AtClassImplLoc, 0, ClassName);
1125 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
1126 ClassName->setFETokenInfo(IDecl);
1127
1128 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001129
1130 // Check that there is no duplicate implementation of this class.
1131 bool err = false;
1132 for (unsigned i = 0; i != Context.sizeObjcImplementationClass(); i++) {
1133 if (Context.getObjcImplementationClass(i)->getIdentifier() == ClassName) {
1134 Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
1135 err = true;
1136 break;
1137 }
1138 }
1139 if (!err)
1140 Context.setObjcImplementationClass(IMPDecl);
1141
1142 return IMPDecl;
1143}
1144
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001145void Sema::ActOnImpleIvarVsClassIvars(DeclTy *ClassDecl,
1146 DeclTy **Fields, unsigned numIvars) {
1147 ObjcInterfaceDecl* IDecl =
1148 cast<ObjcInterfaceDecl>(static_cast<Decl*>(ClassDecl));
1149 assert(IDecl && "missing named interface class decl");
1150 ObjcIvarDecl** ivars = reinterpret_cast<ObjcIvarDecl**>(Fields);
1151 assert(ivars && "missing @implementation ivars");
1152
1153 // Check interface's Ivar list against those in the implementation.
1154 // names and types must match.
1155 //
1156 ObjcIvarDecl** IntfIvars = IDecl->getIntfDeclIvars();
1157 int IntfNumIvars = IDecl->getIntfDeclNumIvars();
1158 unsigned j = 0;
1159 bool err = false;
1160 while (numIvars > 0 && IntfNumIvars > 0) {
1161 ObjcIvarDecl* ImplIvar = ivars[j];
1162 ObjcIvarDecl* ClsIvar = IntfIvars[j++];
1163 assert (ImplIvar && "missing implementation ivar");
1164 assert (ClsIvar && "missing class ivar");
1165 if (ImplIvar->getCanonicalType() != ClsIvar->getCanonicalType()) {
1166 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
1167 ImplIvar->getIdentifier()->getName());
1168 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1169 ClsIvar->getIdentifier()->getName());
1170 }
1171 // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
1172 // as error.
1173 else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1174 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
1175 ImplIvar->getIdentifier()->getName());
1176 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1177 ClsIvar->getIdentifier()->getName());
1178 err = true;
1179 break;
1180 }
1181 --numIvars;
1182 --IntfNumIvars;
1183 }
1184 if (!err && (numIvars > 0 || IntfNumIvars > 0))
1185 Diag(numIvars > 0 ? ivars[j]->getLocation() : IntfIvars[j]->getLocation(),
1186 diag::err_inconsistant_ivar);
1187
1188}
1189
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001190/// CheckProtocolMethodDefs - This routine checks unimpletented methods
1191/// Declared in protocol, and those referenced by it.
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001192void Sema::CheckProtocolMethodDefs(ObjcProtocolDecl *PDecl,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001193 const llvm::DenseMap<void *, char>& InsMap,
1194 const llvm::DenseMap<void *, char>& ClsMap) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001195 // check unimplemented instance methods.
1196 ObjcMethodDecl** methods = PDecl->getInsMethods();
1197 for (int j = 0; j < PDecl->getNumInsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001198 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001199 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001200 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1201 methods[j]->getSelector().getName(buf));
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001202 }
1203 // check unimplemented class methods
1204 methods = PDecl->getClsMethods();
1205 for (int j = 0; j < PDecl->getNumClsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001206 if (!ClsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001207 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001208 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1209 methods[j]->getSelector().getName(buf));
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001210 }
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001211
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001212 // Check on this protocols's referenced protocols, recursively
1213 ObjcProtocolDecl** RefPDecl = PDecl->getReferencedProtocols();
1214 for (int i = 0; i < PDecl->getNumReferencedProtocols(); i++)
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001215 CheckProtocolMethodDefs(RefPDecl[i], InsMap, ClsMap);
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001216}
1217
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001218void Sema::ImplMethodsVsClassMethods(ObjcImplementationDecl* IMPDecl,
1219 ObjcInterfaceDecl* IDecl) {
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001220 llvm::DenseMap<void *, char> InsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001221 // Check and see if instance methods in class interface have been
1222 // implemented in the implementation class.
1223 ObjcMethodDecl **methods = IMPDecl->getInsMethods();
1224 for (int i=0; i < IMPDecl->getNumInsMethods(); i++) {
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001225 InsMap[methods[i]->getSelector().getAsOpaquePtr()] = 'a';
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001226 }
1227
1228 methods = IDecl->getInsMethods();
1229 for (int j = 0; j < IDecl->getNumInsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001230 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001231 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001232 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1233 methods[j]->getSelector().getName(buf));
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001234 }
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001235 llvm::DenseMap<void *, char> ClsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001236 // Check and see if class methods in class interface have been
1237 // implemented in the implementation class.
1238 methods = IMPDecl->getClsMethods();
1239 for (int i=0; i < IMPDecl->getNumClsMethods(); i++) {
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001240 ClsMap[methods[i]->getSelector().getAsOpaquePtr()] = 'a';
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001241 }
1242
1243 methods = IDecl->getClsMethods();
1244 for (int j = 0; j < IDecl->getNumClsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001245 if (!ClsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001246 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001247 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1248 methods[j]->getSelector().getName(buf));
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001249 }
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001250
1251 // Check the protocol list for unimplemented methods in the @implementation
1252 // class.
1253 ObjcProtocolDecl** protocols = IDecl->getIntfRefProtocols();
1254 for (int i = 0; i < IDecl->getNumIntfRefProtocols(); i++) {
1255 ObjcProtocolDecl* PDecl = protocols[i];
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001256 CheckProtocolMethodDefs(PDecl, InsMap, ClsMap);
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001257 }
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001258 return;
1259}
1260
Steve Naroff3536b442007-09-06 21:24:23 +00001261/// ObjcClassDeclaration -
1262/// Scope will always be top level file scope.
1263Action::DeclTy *
1264Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
1265 IdentifierInfo **IdentList, unsigned NumElts) {
1266 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
1267
1268 for (unsigned i = 0; i != NumElts; ++i) {
1269 ObjcInterfaceDecl *IDecl;
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001270 IDecl = getObjCInterfaceDecl(S, IdentList[i], AtClassLoc);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001271 if (!IDecl) {// Already seen?
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001272 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, IdentList[i], true);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001273 // Chain & install the interface decl into the identifier.
1274 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1275 IdentList[i]->setFETokenInfo(IDecl);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001276 }
Steve Naroff3536b442007-09-06 21:24:23 +00001277 // Remember that this needs to be removed when the scope is popped.
1278 S->AddDecl(IdentList[i]);
1279
1280 CDecl->setInterfaceDecl((int)i, IDecl);
1281 }
1282 return CDecl;
1283}
1284
Reid Spencer5f016e22007-07-11 17:01:13 +00001285
Steve Naroff08d92e42007-09-15 18:49:24 +00001286/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001287/// former case, Name will be non-null. In the later case, Name will be null.
1288/// TagType indicates what kind of tag this is. TK indicates whether this is a
1289/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001290Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001291 SourceLocation KWLoc, IdentifierInfo *Name,
1292 SourceLocation NameLoc, AttributeList *Attr) {
1293 // If this is a use of an existing tag, it must have a name.
1294 assert((Name != 0 || TK == TK_Definition) &&
1295 "Nameless record must be a definition!");
1296
1297 Decl::Kind Kind;
1298 switch (TagType) {
1299 default: assert(0 && "Unknown tag type!");
1300 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1301 case DeclSpec::TST_union: Kind = Decl::Union; break;
1302//case DeclSpec::TST_class: Kind = Decl::Class; break;
1303 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1304 }
1305
1306 // If this is a named struct, check to see if there was a previous forward
1307 // declaration or definition.
1308 if (TagDecl *PrevDecl =
1309 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1310 NameLoc, S))) {
1311
1312 // If this is a use of a previous tag, or if the tag is already declared in
1313 // the same scope (so that the definition/declaration completes or
1314 // rementions the tag), reuse the decl.
1315 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1316 // Make sure that this wasn't declared as an enum and now used as a struct
1317 // or something similar.
1318 if (PrevDecl->getKind() != Kind) {
1319 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1320 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1321 }
1322
1323 // If this is a use or a forward declaration, we're good.
1324 if (TK != TK_Definition)
1325 return PrevDecl;
1326
1327 // Diagnose attempts to redefine a tag.
1328 if (PrevDecl->isDefinition()) {
1329 Diag(NameLoc, diag::err_redefinition, Name->getName());
1330 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1331 // If this is a redefinition, recover by making this struct be
1332 // anonymous, which will make any later references get the previous
1333 // definition.
1334 Name = 0;
1335 } else {
1336 // Okay, this is definition of a previously declared or referenced tag.
1337 // Move the location of the decl to be the definition site.
1338 PrevDecl->setLocation(NameLoc);
1339 return PrevDecl;
1340 }
1341 }
1342 // If we get here, this is a definition of a new struct type in a nested
1343 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1344 // type.
1345 }
1346
1347 // If there is an identifier, use the location of the identifier as the
1348 // location of the decl, otherwise use the location of the struct/union
1349 // keyword.
1350 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1351
1352 // Otherwise, if this is the first time we've seen this tag, create the decl.
1353 TagDecl *New;
1354 switch (Kind) {
1355 default: assert(0 && "Unknown tag kind!");
1356 case Decl::Enum:
1357 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1358 // enum X { A, B, C } D; D should chain to X.
1359 New = new EnumDecl(Loc, Name, 0);
1360 // If this is an undefined enum, warn.
1361 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1362 break;
1363 case Decl::Union:
1364 case Decl::Struct:
1365 case Decl::Class:
1366 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1367 // struct X { int A; } D; D should chain to X.
1368 New = new RecordDecl(Kind, Loc, Name, 0);
1369 break;
1370 }
1371
1372 // If this has an identifier, add it to the scope stack.
1373 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001374 // The scope passed in may not be a decl scope. Zip up the scope tree until
1375 // we find one that is.
1376 while ((S->getFlags() & Scope::DeclScope) == 0)
1377 S = S->getParent();
1378
1379 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001380 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001381 Name->setFETokenInfo(New);
1382 S->AddDecl(New);
1383 }
1384
1385 return New;
1386}
1387
Steve Naroff08d92e42007-09-15 18:49:24 +00001388/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001389/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001390Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 SourceLocation DeclStart,
1392 Declarator &D, ExprTy *BitfieldWidth) {
1393 IdentifierInfo *II = D.getIdentifier();
1394 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001395 SourceLocation Loc = DeclStart;
1396 if (II) Loc = D.getIdentifierLoc();
1397
1398 // FIXME: Unnamed fields can be handled in various different ways, for
1399 // example, unnamed unions inject all members into the struct namespace!
1400
1401
1402 if (BitWidth) {
1403 // TODO: Validate.
1404 //printf("WARNING: BITFIELDS IGNORED!\n");
1405
1406 // 6.7.2.1p3
1407 // 6.7.2.1p4
1408
1409 } else {
1410 // Not a bitfield.
1411
1412 // validate II.
1413
1414 }
1415
1416 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001417 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1418 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001419
Reid Spencer5f016e22007-07-11 17:01:13 +00001420 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1421 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001422 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1423 Diag(Loc, diag::err_typecheck_illegal_vla,
1424 VAT->getSizeExpr()->getSourceRange());
1425 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001427 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001428 FieldDecl *NewFD;
1429
1430 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001431 NewFD = new FieldDecl(Loc, II, T);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001432 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl))
1433 || isa<ObjcImplementationDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001434 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001435 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001436 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001437
Steve Naroff5912a352007-08-28 20:14:24 +00001438 if (D.getInvalidType() || InvalidDecl)
1439 NewFD->setInvalidDecl();
1440 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001441}
1442
Steve Narofff13271f2007-09-14 23:09:53 +00001443static void ObjcSetIvarVisibility(ObjcIvarDecl *OIvar,
1444 tok::ObjCKeywordKind ivarVisibility) {
1445 assert(OIvar && "missing instance variable");
1446 switch (ivarVisibility) {
1447 case tok::objc_private:
1448 OIvar->setAccessControl(ObjcIvarDecl::Private);
1449 break;
1450 case tok::objc_public:
1451 OIvar->setAccessControl(ObjcIvarDecl::Public);
1452 break;
1453 case tok::objc_protected:
1454 OIvar->setAccessControl(ObjcIvarDecl::Protected);
1455 break;
1456 case tok::objc_package:
1457 OIvar->setAccessControl(ObjcIvarDecl::Package);
1458 break;
1459 default:
1460 OIvar->setAccessControl(ObjcIvarDecl::None);
1461 break;
1462 }
1463}
1464
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001465void Sema::ActOnFields(Scope* S,
1466 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001467 DeclTy **Fields, unsigned NumFields,
1468 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001469 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1470 assert(EnclosingDecl && "missing record or interface decl");
1471 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1472
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001473 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001474 // Diagnose code like:
1475 // struct S { struct S {} X; };
1476 // We discover this when we complete the outer S. Reject and ignore the
1477 // outer S.
1478 Diag(Record->getLocation(), diag::err_nested_redefinition,
1479 Record->getKindName());
1480 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001481 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 return;
1483 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 // Verify that all the fields are okay.
1485 unsigned NumNamedMembers = 0;
1486 llvm::SmallVector<FieldDecl*, 32> RecFields;
1487 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001488
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001490
Steve Naroff74216642007-09-14 22:20:54 +00001491 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1492 assert(FD && "missing field decl");
1493
1494 // Remember all fields.
1495 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001496
1497 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001498 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001499
Steve Narofff13271f2007-09-14 23:09:53 +00001500 // If we have visibility info, make sure the AST is set accordingly.
1501 if (visibility)
1502 ObjcSetIvarVisibility(dyn_cast<ObjcIvarDecl>(FD), visibility[i]);
1503
Reid Spencer5f016e22007-07-11 17:01:13 +00001504 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001505 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001506 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001508 FD->setInvalidDecl();
1509 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 continue;
1511 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1513 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001514 if (!Record) { // Incomplete ivar type is always an error.
1515 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001516 FD->setInvalidDecl();
1517 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001518 continue;
1519 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001520 if (i != NumFields-1 || // ... that the last member ...
1521 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001522 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001524 FD->setInvalidDecl();
1525 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 continue;
1527 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001528 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001529 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1530 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001531 FD->setInvalidDecl();
1532 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 continue;
1534 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001536 if (Record)
1537 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1540 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001541 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1543 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001544 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 Record->setHasFlexibleArrayMember(true);
1546 } else {
1547 // If this is a struct/class and this is not the last element, reject
1548 // it. Note that GCC supports variable sized arrays in the middle of
1549 // structures.
1550 if (i != NumFields-1) {
1551 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1552 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001553 FD->setInvalidDecl();
1554 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 continue;
1556 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 // We support flexible arrays at the end of structs in other structs
1558 // as an extension.
1559 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1560 FD->getName());
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001561 if (Record)
1562 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 }
1564 }
1565 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 // Keep track of the number of named members.
1567 if (IdentifierInfo *II = FD->getIdentifier()) {
1568 // Detect duplicate member names.
1569 if (!FieldIDs.insert(II)) {
1570 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1571 // Find the previous decl.
1572 SourceLocation PrevLoc;
1573 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1574 assert(i != e && "Didn't find previous def!");
1575 if (RecFields[i]->getIdentifier() == II) {
1576 PrevLoc = RecFields[i]->getLocation();
1577 break;
1578 }
1579 }
1580 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001581 FD->setInvalidDecl();
1582 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 continue;
1584 }
1585 ++NumNamedMembers;
1586 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 }
1588
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 // Okay, we successfully defined 'Record'.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001590 if (Record)
1591 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001592 else {
1593 ObjcIvarDecl **ClsFields =
1594 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001595 if (isa<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1596 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1597 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1598 else if (isa<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1599 ObjcImplementationDecl* IMPDecl =
1600 cast<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl));
1601 assert(IMPDecl && "ActOnFields - missing ObjcImplementationDecl");
1602 IMPDecl->ObjcAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001603 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(S,
1604 IMPDecl->getIdentifier(), RecLoc);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001605 if (IDecl)
1606 ActOnImpleIvarVsClassIvars(static_cast<DeclTy*>(IDecl),
1607 reinterpret_cast<DeclTy**>(&RecFields[0]), RecFields.size());
1608 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001609 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001610}
1611
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001612void Sema::ObjcAddMethodsToClass(Scope* S, DeclTy *ClassDecl,
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001613 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001614 // FIXME: Fix this when we can handle methods declared in protocols.
1615 // See Parser::ParseObjCAtProtocolDeclaration
1616 if (!ClassDecl)
1617 return;
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001618 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1619 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1620
1621 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001622 ObjcMethodDecl *Method =
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001623 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1624 if (!Method) continue; // Already issued a diagnostic.
1625 if (Method->isInstance())
1626 insMethods.push_back(Method);
1627 else
1628 clsMethods.push_back(Method);
1629 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001630 if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(ClassDecl))) {
1631 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1632 static_cast<Decl*>(ClassDecl));
1633 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1634 &clsMethods[0], clsMethods.size());
1635 }
1636 else if (isa<ObjcProtocolDecl>(static_cast<Decl *>(ClassDecl))) {
1637 ObjcProtocolDecl *Protocol = cast<ObjcProtocolDecl>(
1638 static_cast<Decl*>(ClassDecl));
1639 Protocol->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1640 &clsMethods[0], clsMethods.size());
1641 }
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001642 else if (isa<ObjcCategoryDecl>(static_cast<Decl *>(ClassDecl))) {
1643 ObjcCategoryDecl *Category = cast<ObjcCategoryDecl>(
1644 static_cast<Decl*>(ClassDecl));
1645 Category->ObjcAddCatMethods(&insMethods[0], insMethods.size(),
1646 &clsMethods[0], clsMethods.size());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001647 }
1648 else if (isa<ObjcImplementationDecl>(static_cast<Decl *>(ClassDecl))) {
1649 ObjcImplementationDecl* ImplClass = cast<ObjcImplementationDecl>(
1650 static_cast<Decl*>(ClassDecl));
1651 ImplClass->ObjcAddImplMethods(&insMethods[0], insMethods.size(),
1652 &clsMethods[0], clsMethods.size());
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001653 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(S,
1654 ImplClass->getIdentifier(), SourceLocation());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001655 if (IDecl)
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001656 ImplMethodsVsClassMethods(ImplClass, IDecl);
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001657 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001658 else
1659 assert(0 && "Sema::ObjcAddMethodsToClass(): Unknown DeclTy");
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001660 return;
1661}
1662
Fariborz Jahanian00933592007-09-18 00:25:23 +00001663Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001664 tok::TokenKind MethodType, TypeTy *ReturnType, Selector Sel,
Steve Naroff68d331a2007-09-27 14:38:14 +00001665 // optional arguments. The number of types/arguments is obtained
1666 // from the Sel.getNumArgs().
1667 TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1668 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001669 llvm::SmallVector<ParmVarDecl*, 16> Params;
1670
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001671 for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001672 // FIXME: arg->AttrList must be stored too!
Steve Naroff68d331a2007-09-27 14:38:14 +00001673 ParmVarDecl* Param = new ParmVarDecl(SourceLocation(/*FIXME*/), ArgNames[i],
1674 QualType::getFromOpaquePtr(ArgTypes[i]),
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001675 VarDecl::None, 0);
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001676 Params.push_back(Param);
1677 }
1678 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Steve Naroff68d331a2007-09-27 14:38:14 +00001679 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc, Sel,
1680 resultDeclType, 0, -1, AttrList,
1681 MethodType == tok::minus);
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001682 ObjcMethod->setMethodParams(&Params[0], Sel.getNumArgs());
Fariborz Jahanian00933592007-09-18 00:25:23 +00001683 if (MethodDeclKind == tok::objc_optional)
Steve Naroff563477d2007-09-18 23:55:05 +00001684 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Optional);
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001685 else
Steve Naroff563477d2007-09-18 23:55:05 +00001686 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Required);
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001687 return ObjcMethod;
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001688}
1689
Steve Naroff08d92e42007-09-15 18:49:24 +00001690Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 DeclTy *lastEnumConst,
1692 SourceLocation IdLoc, IdentifierInfo *Id,
1693 SourceLocation EqualLoc, ExprTy *val) {
1694 theEnumDecl = theEnumDecl; // silence unused warning.
1695 EnumConstantDecl *LastEnumConst =
1696 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1697 Expr *Val = static_cast<Expr*>(val);
1698
Chris Lattner31e05722007-08-26 06:24:45 +00001699 // The scope passed in may not be a decl scope. Zip up the scope tree until
1700 // we find one that is.
1701 while ((S->getFlags() & Scope::DeclScope) == 0)
1702 S = S->getParent();
1703
Reid Spencer5f016e22007-07-11 17:01:13 +00001704 // Verify that there isn't already something declared with this name in this
1705 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001706 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1707 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 if (S->isDeclScope(PrevDecl)) {
1709 if (isa<EnumConstantDecl>(PrevDecl))
1710 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1711 else
1712 Diag(IdLoc, diag::err_redefinition, Id->getName());
1713 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1714 // FIXME: Don't leak memory: delete Val;
1715 return 0;
1716 }
1717 }
1718
1719 llvm::APSInt EnumVal(32);
1720 QualType EltTy;
1721 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001722 // Make sure to promote the operand type to int.
1723 UsualUnaryConversions(Val);
1724
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1726 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001727 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1729 Id->getName());
1730 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001731 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001732 } else {
1733 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001734 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001735 }
1736
1737 if (!Val) {
1738 if (LastEnumConst) {
1739 // Assign the last value + 1.
1740 EnumVal = LastEnumConst->getInitVal();
1741 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001742
1743 // Check for overflow on increment.
1744 if (EnumVal < LastEnumConst->getInitVal())
1745 Diag(IdLoc, diag::warn_enum_value_overflow);
1746
Chris Lattnerb7416f92007-08-27 17:37:24 +00001747 EltTy = LastEnumConst->getType();
1748 } else {
1749 // First value, set to zero.
1750 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001751 EnumVal.zextOrTrunc(
1752 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001753 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001754 }
1755
Reid Spencer5f016e22007-07-11 17:01:13 +00001756 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1757 LastEnumConst);
1758
1759 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001760 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001761 Id->setFETokenInfo(New);
1762 S->AddDecl(New);
1763 return New;
1764}
1765
Steve Naroff08d92e42007-09-15 18:49:24 +00001766void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 DeclTy **Elements, unsigned NumElements) {
1768 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1769 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1770
Chris Lattnere37f0be2007-08-28 05:10:31 +00001771 // TODO: If the result value doesn't fit in an int, it must be a long or long
1772 // long value. ISO C does not support this, but GCC does as an extension,
1773 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001774 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001775
1776
Chris Lattnerac609682007-08-28 06:15:15 +00001777 // Verify that all the values are okay, compute the size of the values, and
1778 // reverse the list.
1779 unsigned NumNegativeBits = 0;
1780 unsigned NumPositiveBits = 0;
1781
1782 // Keep track of whether all elements have type int.
1783 bool AllElementsInt = true;
1784
Reid Spencer5f016e22007-07-11 17:01:13 +00001785 EnumConstantDecl *EltList = 0;
1786 for (unsigned i = 0; i != NumElements; ++i) {
1787 EnumConstantDecl *ECD =
1788 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1789 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001790
1791 // If the enum value doesn't fit in an int, emit an extension warning.
1792 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1793 "Should have promoted value to int");
1794 const llvm::APSInt &InitVal = ECD->getInitVal();
1795 if (InitVal.getBitWidth() > IntWidth) {
1796 llvm::APSInt V(InitVal);
1797 V.trunc(IntWidth);
1798 V.extend(InitVal.getBitWidth());
1799 if (V != InitVal)
1800 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1801 InitVal.toString());
1802 }
Chris Lattnerac609682007-08-28 06:15:15 +00001803
1804 // Keep track of the size of positive and negative values.
1805 if (InitVal.isUnsigned() || !InitVal.isNegative())
1806 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1807 else
1808 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001809
Chris Lattnerac609682007-08-28 06:15:15 +00001810 // Keep track of whether every enum element has type int (very commmon).
1811 if (AllElementsInt)
1812 AllElementsInt = ECD->getType() == Context.IntTy;
1813
Reid Spencer5f016e22007-07-11 17:01:13 +00001814 ECD->setNextDeclarator(EltList);
1815 EltList = ECD;
1816 }
1817
Chris Lattnerac609682007-08-28 06:15:15 +00001818 // Figure out the type that should be used for this enum.
1819 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1820 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001821 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001822
1823 if (NumNegativeBits) {
1824 // If there is a negative value, figure out the smallest integer type (of
1825 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001826 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001827 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001828 BestWidth = IntWidth;
1829 } else {
1830 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1831 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001832 BestType = Context.LongTy;
1833 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001834 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1835 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001836 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1837 BestType = Context.LongLongTy;
1838 }
1839 }
1840 } else {
1841 // If there is no negative value, figure out which of uint, ulong, ulonglong
1842 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001843 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001844 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001845 BestWidth = IntWidth;
1846 } else if (NumPositiveBits <=
1847 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001848 BestType = Context.UnsignedLongTy;
1849 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001850 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1851 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001852 "How could an initializer get larger than ULL?");
1853 BestType = Context.UnsignedLongLongTy;
1854 }
1855 }
1856
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001857 // Loop over all of the enumerator constants, changing their types to match
1858 // the type of the enum if needed.
1859 for (unsigned i = 0; i != NumElements; ++i) {
1860 EnumConstantDecl *ECD =
1861 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1862 if (!ECD) continue; // Already issued a diagnostic.
1863
1864 // Standard C says the enumerators have int type, but we allow, as an
1865 // extension, the enumerators to be larger than int size. If each
1866 // enumerator value fits in an int, type it as an int, otherwise type it the
1867 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1868 // that X has type 'int', not 'unsigned'.
1869 if (ECD->getType() == Context.IntTy)
1870 continue; // Already int type.
1871
1872 // Determine whether the value fits into an int.
1873 llvm::APSInt InitVal = ECD->getInitVal();
1874 bool FitsInInt;
1875 if (InitVal.isUnsigned() || !InitVal.isNegative())
1876 FitsInInt = InitVal.getActiveBits() < IntWidth;
1877 else
1878 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1879
1880 // If it fits into an integer type, force it. Otherwise force it to match
1881 // the enum decl type.
1882 QualType NewTy;
1883 unsigned NewWidth;
1884 bool NewSign;
1885 if (FitsInInt) {
1886 NewTy = Context.IntTy;
1887 NewWidth = IntWidth;
1888 NewSign = true;
1889 } else if (ECD->getType() == BestType) {
1890 // Already the right type!
1891 continue;
1892 } else {
1893 NewTy = BestType;
1894 NewWidth = BestWidth;
1895 NewSign = BestType->isSignedIntegerType();
1896 }
1897
1898 // Adjust the APSInt value.
1899 InitVal.extOrTrunc(NewWidth);
1900 InitVal.setIsSigned(NewSign);
1901 ECD->setInitVal(InitVal);
1902
1903 // Adjust the Expr initializer and type.
1904 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1905 ECD->setType(NewTy);
1906 }
Chris Lattnerac609682007-08-28 06:15:15 +00001907
Chris Lattnere00b18c2007-08-28 18:24:31 +00001908 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001909}
1910
1911void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1912 if (!current) return;
1913
1914 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1915 // remember this in the LastInGroupList list.
1916 if (last)
1917 LastInGroupList.push_back((Decl*)last);
1918}
1919
1920void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1921 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1922 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1923 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1924 if (!newType.isNull()) // install the new vector type into the decl
1925 vDecl->setType(newType);
1926 }
1927 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1928 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1929 rawAttr);
1930 if (!newType.isNull()) // install the new vector type into the decl
1931 tDecl->setUnderlyingType(newType);
1932 }
1933 }
Steve Naroff73322922007-07-18 18:00:27 +00001934 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001935 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1936 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1937 else
Steve Naroff73322922007-07-18 18:00:27 +00001938 Diag(rawAttr->getAttributeLoc(),
1939 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00001940 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 // FIXME: add other attributes...
1942}
1943
1944void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1945 AttributeList *declarator_postfix) {
1946 while (declspec_prefix) {
1947 HandleDeclAttribute(New, declspec_prefix);
1948 declspec_prefix = declspec_prefix->getNext();
1949 }
1950 while (declarator_postfix) {
1951 HandleDeclAttribute(New, declarator_postfix);
1952 declarator_postfix = declarator_postfix->getNext();
1953 }
1954}
1955
Steve Naroffbea0b342007-07-29 16:33:31 +00001956void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1957 AttributeList *rawAttr) {
1958 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00001959 // check the attribute arugments.
1960 if (rawAttr->getNumArgs() != 1) {
1961 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1962 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001963 return;
Steve Naroff73322922007-07-18 18:00:27 +00001964 }
1965 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1966 llvm::APSInt vecSize(32);
1967 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1968 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1969 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001970 return;
Steve Naroff73322922007-07-18 18:00:27 +00001971 }
1972 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1973 // in conjunction with complex types (pointers, arrays, functions, etc.).
1974 Type *canonType = curType.getCanonicalType().getTypePtr();
1975 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1976 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1977 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001978 return;
Steve Naroff73322922007-07-18 18:00:27 +00001979 }
1980 // unlike gcc's vector_size attribute, the size is specified as the
1981 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001982 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001983
1984 if (vectorSize == 0) {
1985 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1986 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001987 return;
Steve Naroff73322922007-07-18 18:00:27 +00001988 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001989 // Instantiate/Install the vector type, the number of elements is > 0.
1990 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1991 // Remember this typedef decl, we will need it later for diagnostics.
1992 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001993}
1994
Reid Spencer5f016e22007-07-11 17:01:13 +00001995QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001996 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001997 // check the attribute arugments.
1998 if (rawAttr->getNumArgs() != 1) {
1999 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2000 std::string("1"));
2001 return QualType();
2002 }
2003 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2004 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002005 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002006 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2007 sizeExpr->getSourceRange());
2008 return QualType();
2009 }
2010 // navigate to the base type - we need to provide for vector pointers,
2011 // vector arrays, and functions returning vectors.
2012 Type *canonType = curType.getCanonicalType().getTypePtr();
2013
Steve Naroff73322922007-07-18 18:00:27 +00002014 if (canonType->isPointerType() || canonType->isArrayType() ||
2015 canonType->isFunctionType()) {
2016 assert(1 && "HandleVector(): Complex type construction unimplemented");
2017 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2018 do {
2019 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2020 canonType = PT->getPointeeType().getTypePtr();
2021 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2022 canonType = AT->getElementType().getTypePtr();
2023 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2024 canonType = FT->getResultType().getTypePtr();
2025 } while (canonType->isPointerType() || canonType->isArrayType() ||
2026 canonType->isFunctionType());
2027 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002028 }
2029 // the base type must be integer or float.
2030 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2031 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2032 curType.getCanonicalType().getAsString());
2033 return QualType();
2034 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00002035 unsigned typeSize = static_cast<unsigned>(
2036 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002037 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002038 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002039
2040 // the vector size needs to be an integral multiple of the type size.
2041 if (vectorSize % typeSize) {
2042 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
2043 sizeExpr->getSourceRange());
2044 return QualType();
2045 }
2046 if (vectorSize == 0) {
2047 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2048 sizeExpr->getSourceRange());
2049 return QualType();
2050 }
2051 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
2052 // the number of elements to be a power of two (unlike GCC).
2053 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00002054 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002055}
2056