blob: 5e66684cb42ff936bc5b0be1f896220f4b295b80 [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.
1192///
1193static void CheckProtocolMethodDefs(Sema* objSema, ObjcProtocolDecl *PDecl,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001194 const llvm::DenseMap<void *, char>& InsMap,
1195 const llvm::DenseMap<void *, char>& ClsMap) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001196 // check unimplemented instance methods.
1197 ObjcMethodDecl** methods = PDecl->getInsMethods();
1198 for (int j = 0; j < PDecl->getNumInsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001199 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001200 llvm::SmallString<128> buf;
1201 objSema->Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001202 methods[j]->getSelector().getName(buf));
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001203 }
1204 // check unimplemented class methods
1205 methods = PDecl->getClsMethods();
1206 for (int j = 0; j < PDecl->getNumClsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001207 if (!ClsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001208 llvm::SmallString<128> buf;
1209 objSema->Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001210 methods[j]->getSelector().getName(buf));
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001211 }
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001212
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001213 // Check on this protocols's referenced protocols, recursively
1214 ObjcProtocolDecl** RefPDecl = PDecl->getReferencedProtocols();
1215 for (int i = 0; i < PDecl->getNumReferencedProtocols(); i++)
1216 CheckProtocolMethodDefs(objSema, RefPDecl[i], InsMap, ClsMap);
1217}
1218
1219static void ImplMethodsVsClassMethods(Sema* objSema,
1220 ObjcImplementationDecl* IMPDecl,
1221 ObjcInterfaceDecl* IDecl) {
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001222 llvm::DenseMap<void *, char> InsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001223 // Check and see if instance methods in class interface have been
1224 // implemented in the implementation class.
1225 ObjcMethodDecl **methods = IMPDecl->getInsMethods();
1226 for (int i=0; i < IMPDecl->getNumInsMethods(); i++) {
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001227 InsMap[methods[i]->getSelector().getAsOpaquePtr()] = 'a';
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001228 }
1229
1230 methods = IDecl->getInsMethods();
1231 for (int j = 0; j < IDecl->getNumInsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001232 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001233 llvm::SmallString<128> buf;
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001234 objSema->Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001235 methods[j]->getSelector().getName(buf));
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001236 }
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001237 llvm::DenseMap<void *, char> ClsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001238 // Check and see if class methods in class interface have been
1239 // implemented in the implementation class.
1240 methods = IMPDecl->getClsMethods();
1241 for (int i=0; i < IMPDecl->getNumClsMethods(); i++) {
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001242 ClsMap[methods[i]->getSelector().getAsOpaquePtr()] = 'a';
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001243 }
1244
1245 methods = IDecl->getClsMethods();
1246 for (int j = 0; j < IDecl->getNumClsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001247 if (!ClsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001248 llvm::SmallString<128> buf;
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001249 objSema->Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001250 methods[j]->getSelector().getName(buf));
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001251 }
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001252
1253 // Check the protocol list for unimplemented methods in the @implementation
1254 // class.
1255 ObjcProtocolDecl** protocols = IDecl->getIntfRefProtocols();
1256 for (int i = 0; i < IDecl->getNumIntfRefProtocols(); i++) {
1257 ObjcProtocolDecl* PDecl = protocols[i];
1258 CheckProtocolMethodDefs(objSema, PDecl, InsMap, ClsMap);
1259 }
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001260 return;
1261}
1262
Steve Naroff3536b442007-09-06 21:24:23 +00001263/// ObjcClassDeclaration -
1264/// Scope will always be top level file scope.
1265Action::DeclTy *
1266Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
1267 IdentifierInfo **IdentList, unsigned NumElts) {
1268 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
1269
1270 for (unsigned i = 0; i != NumElts; ++i) {
1271 ObjcInterfaceDecl *IDecl;
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001272 IDecl = getObjCInterfaceDecl(S, IdentList[i], AtClassLoc);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001273 if (!IDecl) {// Already seen?
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001274 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, IdentList[i], true);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001275 // Chain & install the interface decl into the identifier.
1276 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1277 IdentList[i]->setFETokenInfo(IDecl);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001278 }
Steve Naroff3536b442007-09-06 21:24:23 +00001279 // Remember that this needs to be removed when the scope is popped.
1280 S->AddDecl(IdentList[i]);
1281
1282 CDecl->setInterfaceDecl((int)i, IDecl);
1283 }
1284 return CDecl;
1285}
1286
Reid Spencer5f016e22007-07-11 17:01:13 +00001287
Steve Naroff08d92e42007-09-15 18:49:24 +00001288/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001289/// former case, Name will be non-null. In the later case, Name will be null.
1290/// TagType indicates what kind of tag this is. TK indicates whether this is a
1291/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001292Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 SourceLocation KWLoc, IdentifierInfo *Name,
1294 SourceLocation NameLoc, AttributeList *Attr) {
1295 // If this is a use of an existing tag, it must have a name.
1296 assert((Name != 0 || TK == TK_Definition) &&
1297 "Nameless record must be a definition!");
1298
1299 Decl::Kind Kind;
1300 switch (TagType) {
1301 default: assert(0 && "Unknown tag type!");
1302 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1303 case DeclSpec::TST_union: Kind = Decl::Union; break;
1304//case DeclSpec::TST_class: Kind = Decl::Class; break;
1305 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1306 }
1307
1308 // If this is a named struct, check to see if there was a previous forward
1309 // declaration or definition.
1310 if (TagDecl *PrevDecl =
1311 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1312 NameLoc, S))) {
1313
1314 // If this is a use of a previous tag, or if the tag is already declared in
1315 // the same scope (so that the definition/declaration completes or
1316 // rementions the tag), reuse the decl.
1317 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1318 // Make sure that this wasn't declared as an enum and now used as a struct
1319 // or something similar.
1320 if (PrevDecl->getKind() != Kind) {
1321 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1322 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1323 }
1324
1325 // If this is a use or a forward declaration, we're good.
1326 if (TK != TK_Definition)
1327 return PrevDecl;
1328
1329 // Diagnose attempts to redefine a tag.
1330 if (PrevDecl->isDefinition()) {
1331 Diag(NameLoc, diag::err_redefinition, Name->getName());
1332 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1333 // If this is a redefinition, recover by making this struct be
1334 // anonymous, which will make any later references get the previous
1335 // definition.
1336 Name = 0;
1337 } else {
1338 // Okay, this is definition of a previously declared or referenced tag.
1339 // Move the location of the decl to be the definition site.
1340 PrevDecl->setLocation(NameLoc);
1341 return PrevDecl;
1342 }
1343 }
1344 // If we get here, this is a definition of a new struct type in a nested
1345 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1346 // type.
1347 }
1348
1349 // If there is an identifier, use the location of the identifier as the
1350 // location of the decl, otherwise use the location of the struct/union
1351 // keyword.
1352 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1353
1354 // Otherwise, if this is the first time we've seen this tag, create the decl.
1355 TagDecl *New;
1356 switch (Kind) {
1357 default: assert(0 && "Unknown tag kind!");
1358 case Decl::Enum:
1359 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1360 // enum X { A, B, C } D; D should chain to X.
1361 New = new EnumDecl(Loc, Name, 0);
1362 // If this is an undefined enum, warn.
1363 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1364 break;
1365 case Decl::Union:
1366 case Decl::Struct:
1367 case Decl::Class:
1368 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1369 // struct X { int A; } D; D should chain to X.
1370 New = new RecordDecl(Kind, Loc, Name, 0);
1371 break;
1372 }
1373
1374 // If this has an identifier, add it to the scope stack.
1375 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001376 // The scope passed in may not be a decl scope. Zip up the scope tree until
1377 // we find one that is.
1378 while ((S->getFlags() & Scope::DeclScope) == 0)
1379 S = S->getParent();
1380
1381 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001382 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001383 Name->setFETokenInfo(New);
1384 S->AddDecl(New);
1385 }
1386
1387 return New;
1388}
1389
Steve Naroff08d92e42007-09-15 18:49:24 +00001390/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001391/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001392Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 SourceLocation DeclStart,
1394 Declarator &D, ExprTy *BitfieldWidth) {
1395 IdentifierInfo *II = D.getIdentifier();
1396 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001397 SourceLocation Loc = DeclStart;
1398 if (II) Loc = D.getIdentifierLoc();
1399
1400 // FIXME: Unnamed fields can be handled in various different ways, for
1401 // example, unnamed unions inject all members into the struct namespace!
1402
1403
1404 if (BitWidth) {
1405 // TODO: Validate.
1406 //printf("WARNING: BITFIELDS IGNORED!\n");
1407
1408 // 6.7.2.1p3
1409 // 6.7.2.1p4
1410
1411 } else {
1412 // Not a bitfield.
1413
1414 // validate II.
1415
1416 }
1417
1418 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001419 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1420 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001421
Reid Spencer5f016e22007-07-11 17:01:13 +00001422 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1423 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001424 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1425 Diag(Loc, diag::err_typecheck_illegal_vla,
1426 VAT->getSizeExpr()->getSourceRange());
1427 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001430 FieldDecl *NewFD;
1431
1432 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001433 NewFD = new FieldDecl(Loc, II, T);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001434 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl))
1435 || isa<ObjcImplementationDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001436 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001437 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001438 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001439
Steve Naroff5912a352007-08-28 20:14:24 +00001440 if (D.getInvalidType() || InvalidDecl)
1441 NewFD->setInvalidDecl();
1442 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001443}
1444
Steve Narofff13271f2007-09-14 23:09:53 +00001445static void ObjcSetIvarVisibility(ObjcIvarDecl *OIvar,
1446 tok::ObjCKeywordKind ivarVisibility) {
1447 assert(OIvar && "missing instance variable");
1448 switch (ivarVisibility) {
1449 case tok::objc_private:
1450 OIvar->setAccessControl(ObjcIvarDecl::Private);
1451 break;
1452 case tok::objc_public:
1453 OIvar->setAccessControl(ObjcIvarDecl::Public);
1454 break;
1455 case tok::objc_protected:
1456 OIvar->setAccessControl(ObjcIvarDecl::Protected);
1457 break;
1458 case tok::objc_package:
1459 OIvar->setAccessControl(ObjcIvarDecl::Package);
1460 break;
1461 default:
1462 OIvar->setAccessControl(ObjcIvarDecl::None);
1463 break;
1464 }
1465}
1466
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001467void Sema::ActOnFields(Scope* S,
1468 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001469 DeclTy **Fields, unsigned NumFields,
1470 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001471 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1472 assert(EnclosingDecl && "missing record or interface decl");
1473 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1474
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001475 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 // Diagnose code like:
1477 // struct S { struct S {} X; };
1478 // We discover this when we complete the outer S. Reject and ignore the
1479 // outer S.
1480 Diag(Record->getLocation(), diag::err_nested_redefinition,
1481 Record->getKindName());
1482 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001483 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 return;
1485 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 // Verify that all the fields are okay.
1487 unsigned NumNamedMembers = 0;
1488 llvm::SmallVector<FieldDecl*, 32> RecFields;
1489 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001490
Reid Spencer5f016e22007-07-11 17:01:13 +00001491 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001492
Steve Naroff74216642007-09-14 22:20:54 +00001493 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1494 assert(FD && "missing field decl");
1495
1496 // Remember all fields.
1497 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001498
1499 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001500 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001501
Steve Narofff13271f2007-09-14 23:09:53 +00001502 // If we have visibility info, make sure the AST is set accordingly.
1503 if (visibility)
1504 ObjcSetIvarVisibility(dyn_cast<ObjcIvarDecl>(FD), visibility[i]);
1505
Reid Spencer5f016e22007-07-11 17:01:13 +00001506 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001507 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001508 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001510 FD->setInvalidDecl();
1511 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 continue;
1513 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001514 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1515 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001516 if (!Record) { // Incomplete ivar type is always an error.
1517 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001518 FD->setInvalidDecl();
1519 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001520 continue;
1521 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001522 if (i != NumFields-1 || // ... that the last member ...
1523 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001524 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001526 FD->setInvalidDecl();
1527 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 continue;
1529 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001530 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001531 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1532 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001533 FD->setInvalidDecl();
1534 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 continue;
1536 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001538 if (Record)
1539 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1542 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001543 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001544 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1545 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001546 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001547 Record->setHasFlexibleArrayMember(true);
1548 } else {
1549 // If this is a struct/class and this is not the last element, reject
1550 // it. Note that GCC supports variable sized arrays in the middle of
1551 // structures.
1552 if (i != NumFields-1) {
1553 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1554 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001555 FD->setInvalidDecl();
1556 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 continue;
1558 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 // We support flexible arrays at the end of structs in other structs
1560 // as an extension.
1561 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1562 FD->getName());
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001563 if (Record)
1564 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 }
1566 }
1567 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001568 // Keep track of the number of named members.
1569 if (IdentifierInfo *II = FD->getIdentifier()) {
1570 // Detect duplicate member names.
1571 if (!FieldIDs.insert(II)) {
1572 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1573 // Find the previous decl.
1574 SourceLocation PrevLoc;
1575 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1576 assert(i != e && "Didn't find previous def!");
1577 if (RecFields[i]->getIdentifier() == II) {
1578 PrevLoc = RecFields[i]->getLocation();
1579 break;
1580 }
1581 }
1582 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001583 FD->setInvalidDecl();
1584 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 continue;
1586 }
1587 ++NumNamedMembers;
1588 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 }
1590
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 // Okay, we successfully defined 'Record'.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001592 if (Record)
1593 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001594 else {
1595 ObjcIvarDecl **ClsFields =
1596 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001597 if (isa<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1598 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1599 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1600 else if (isa<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1601 ObjcImplementationDecl* IMPDecl =
1602 cast<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl));
1603 assert(IMPDecl && "ActOnFields - missing ObjcImplementationDecl");
1604 IMPDecl->ObjcAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001605 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(S,
1606 IMPDecl->getIdentifier(), RecLoc);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001607 if (IDecl)
1608 ActOnImpleIvarVsClassIvars(static_cast<DeclTy*>(IDecl),
1609 reinterpret_cast<DeclTy**>(&RecFields[0]), RecFields.size());
1610 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001611 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001612}
1613
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001614void Sema::ObjcAddMethodsToClass(Scope* S, DeclTy *ClassDecl,
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001615 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001616 // FIXME: Fix this when we can handle methods declared in protocols.
1617 // See Parser::ParseObjCAtProtocolDeclaration
1618 if (!ClassDecl)
1619 return;
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001620 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1621 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1622
1623 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001624 ObjcMethodDecl *Method =
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001625 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1626 if (!Method) continue; // Already issued a diagnostic.
1627 if (Method->isInstance())
1628 insMethods.push_back(Method);
1629 else
1630 clsMethods.push_back(Method);
1631 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001632 if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(ClassDecl))) {
1633 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1634 static_cast<Decl*>(ClassDecl));
1635 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1636 &clsMethods[0], clsMethods.size());
1637 }
1638 else if (isa<ObjcProtocolDecl>(static_cast<Decl *>(ClassDecl))) {
1639 ObjcProtocolDecl *Protocol = cast<ObjcProtocolDecl>(
1640 static_cast<Decl*>(ClassDecl));
1641 Protocol->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1642 &clsMethods[0], clsMethods.size());
1643 }
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001644 else if (isa<ObjcCategoryDecl>(static_cast<Decl *>(ClassDecl))) {
1645 ObjcCategoryDecl *Category = cast<ObjcCategoryDecl>(
1646 static_cast<Decl*>(ClassDecl));
1647 Category->ObjcAddCatMethods(&insMethods[0], insMethods.size(),
1648 &clsMethods[0], clsMethods.size());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001649 }
1650 else if (isa<ObjcImplementationDecl>(static_cast<Decl *>(ClassDecl))) {
1651 ObjcImplementationDecl* ImplClass = cast<ObjcImplementationDecl>(
1652 static_cast<Decl*>(ClassDecl));
1653 ImplClass->ObjcAddImplMethods(&insMethods[0], insMethods.size(),
1654 &clsMethods[0], clsMethods.size());
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001655 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(S,
1656 ImplClass->getIdentifier(), SourceLocation());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001657 if (IDecl)
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001658 ImplMethodsVsClassMethods(this, ImplClass, IDecl);
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001659 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001660 else
1661 assert(0 && "Sema::ObjcAddMethodsToClass(): Unknown DeclTy");
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001662 return;
1663}
1664
Fariborz Jahanian00933592007-09-18 00:25:23 +00001665Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001666 tok::TokenKind MethodType, TypeTy *ReturnType, Selector Sel,
Steve Naroff68d331a2007-09-27 14:38:14 +00001667 // optional arguments. The number of types/arguments is obtained
1668 // from the Sel.getNumArgs().
1669 TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1670 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001671 llvm::SmallVector<ParmVarDecl*, 16> Params;
1672
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001673 for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001674 // FIXME: arg->AttrList must be stored too!
Steve Naroff68d331a2007-09-27 14:38:14 +00001675 ParmVarDecl* Param = new ParmVarDecl(SourceLocation(/*FIXME*/), ArgNames[i],
1676 QualType::getFromOpaquePtr(ArgTypes[i]),
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001677 VarDecl::None, 0);
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001678 Params.push_back(Param);
1679 }
1680 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Steve Naroff68d331a2007-09-27 14:38:14 +00001681 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc, Sel,
1682 resultDeclType, 0, -1, AttrList,
1683 MethodType == tok::minus);
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001684 ObjcMethod->setMethodParams(&Params[0], Sel.getNumArgs());
Fariborz Jahanian00933592007-09-18 00:25:23 +00001685 if (MethodDeclKind == tok::objc_optional)
Steve Naroff563477d2007-09-18 23:55:05 +00001686 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Optional);
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001687 else
Steve Naroff563477d2007-09-18 23:55:05 +00001688 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Required);
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001689 return ObjcMethod;
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001690}
1691
Steve Naroff08d92e42007-09-15 18:49:24 +00001692Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001693 DeclTy *lastEnumConst,
1694 SourceLocation IdLoc, IdentifierInfo *Id,
1695 SourceLocation EqualLoc, ExprTy *val) {
1696 theEnumDecl = theEnumDecl; // silence unused warning.
1697 EnumConstantDecl *LastEnumConst =
1698 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1699 Expr *Val = static_cast<Expr*>(val);
1700
Chris Lattner31e05722007-08-26 06:24:45 +00001701 // The scope passed in may not be a decl scope. Zip up the scope tree until
1702 // we find one that is.
1703 while ((S->getFlags() & Scope::DeclScope) == 0)
1704 S = S->getParent();
1705
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 // Verify that there isn't already something declared with this name in this
1707 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001708 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1709 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 if (S->isDeclScope(PrevDecl)) {
1711 if (isa<EnumConstantDecl>(PrevDecl))
1712 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1713 else
1714 Diag(IdLoc, diag::err_redefinition, Id->getName());
1715 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1716 // FIXME: Don't leak memory: delete Val;
1717 return 0;
1718 }
1719 }
1720
1721 llvm::APSInt EnumVal(32);
1722 QualType EltTy;
1723 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001724 // Make sure to promote the operand type to int.
1725 UsualUnaryConversions(Val);
1726
Reid Spencer5f016e22007-07-11 17:01:13 +00001727 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1728 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001729 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001730 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1731 Id->getName());
1732 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001733 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001734 } else {
1735 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001736 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001737 }
1738
1739 if (!Val) {
1740 if (LastEnumConst) {
1741 // Assign the last value + 1.
1742 EnumVal = LastEnumConst->getInitVal();
1743 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001744
1745 // Check for overflow on increment.
1746 if (EnumVal < LastEnumConst->getInitVal())
1747 Diag(IdLoc, diag::warn_enum_value_overflow);
1748
Chris Lattnerb7416f92007-08-27 17:37:24 +00001749 EltTy = LastEnumConst->getType();
1750 } else {
1751 // First value, set to zero.
1752 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001753 EnumVal.zextOrTrunc(
1754 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001755 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001756 }
1757
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1759 LastEnumConst);
1760
1761 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001762 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001763 Id->setFETokenInfo(New);
1764 S->AddDecl(New);
1765 return New;
1766}
1767
Steve Naroff08d92e42007-09-15 18:49:24 +00001768void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 DeclTy **Elements, unsigned NumElements) {
1770 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1771 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1772
Chris Lattnere37f0be2007-08-28 05:10:31 +00001773 // TODO: If the result value doesn't fit in an int, it must be a long or long
1774 // long value. ISO C does not support this, but GCC does as an extension,
1775 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001776 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001777
1778
Chris Lattnerac609682007-08-28 06:15:15 +00001779 // Verify that all the values are okay, compute the size of the values, and
1780 // reverse the list.
1781 unsigned NumNegativeBits = 0;
1782 unsigned NumPositiveBits = 0;
1783
1784 // Keep track of whether all elements have type int.
1785 bool AllElementsInt = true;
1786
Reid Spencer5f016e22007-07-11 17:01:13 +00001787 EnumConstantDecl *EltList = 0;
1788 for (unsigned i = 0; i != NumElements; ++i) {
1789 EnumConstantDecl *ECD =
1790 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1791 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001792
1793 // If the enum value doesn't fit in an int, emit an extension warning.
1794 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1795 "Should have promoted value to int");
1796 const llvm::APSInt &InitVal = ECD->getInitVal();
1797 if (InitVal.getBitWidth() > IntWidth) {
1798 llvm::APSInt V(InitVal);
1799 V.trunc(IntWidth);
1800 V.extend(InitVal.getBitWidth());
1801 if (V != InitVal)
1802 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1803 InitVal.toString());
1804 }
Chris Lattnerac609682007-08-28 06:15:15 +00001805
1806 // Keep track of the size of positive and negative values.
1807 if (InitVal.isUnsigned() || !InitVal.isNegative())
1808 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1809 else
1810 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001811
Chris Lattnerac609682007-08-28 06:15:15 +00001812 // Keep track of whether every enum element has type int (very commmon).
1813 if (AllElementsInt)
1814 AllElementsInt = ECD->getType() == Context.IntTy;
1815
Reid Spencer5f016e22007-07-11 17:01:13 +00001816 ECD->setNextDeclarator(EltList);
1817 EltList = ECD;
1818 }
1819
Chris Lattnerac609682007-08-28 06:15:15 +00001820 // Figure out the type that should be used for this enum.
1821 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1822 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001823 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001824
1825 if (NumNegativeBits) {
1826 // If there is a negative value, figure out the smallest integer type (of
1827 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001828 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001829 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001830 BestWidth = IntWidth;
1831 } else {
1832 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1833 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001834 BestType = Context.LongTy;
1835 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001836 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1837 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001838 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1839 BestType = Context.LongLongTy;
1840 }
1841 }
1842 } else {
1843 // If there is no negative value, figure out which of uint, ulong, ulonglong
1844 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001845 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001846 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001847 BestWidth = IntWidth;
1848 } else if (NumPositiveBits <=
1849 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001850 BestType = Context.UnsignedLongTy;
1851 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001852 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1853 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001854 "How could an initializer get larger than ULL?");
1855 BestType = Context.UnsignedLongLongTy;
1856 }
1857 }
1858
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001859 // Loop over all of the enumerator constants, changing their types to match
1860 // the type of the enum if needed.
1861 for (unsigned i = 0; i != NumElements; ++i) {
1862 EnumConstantDecl *ECD =
1863 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1864 if (!ECD) continue; // Already issued a diagnostic.
1865
1866 // Standard C says the enumerators have int type, but we allow, as an
1867 // extension, the enumerators to be larger than int size. If each
1868 // enumerator value fits in an int, type it as an int, otherwise type it the
1869 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1870 // that X has type 'int', not 'unsigned'.
1871 if (ECD->getType() == Context.IntTy)
1872 continue; // Already int type.
1873
1874 // Determine whether the value fits into an int.
1875 llvm::APSInt InitVal = ECD->getInitVal();
1876 bool FitsInInt;
1877 if (InitVal.isUnsigned() || !InitVal.isNegative())
1878 FitsInInt = InitVal.getActiveBits() < IntWidth;
1879 else
1880 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1881
1882 // If it fits into an integer type, force it. Otherwise force it to match
1883 // the enum decl type.
1884 QualType NewTy;
1885 unsigned NewWidth;
1886 bool NewSign;
1887 if (FitsInInt) {
1888 NewTy = Context.IntTy;
1889 NewWidth = IntWidth;
1890 NewSign = true;
1891 } else if (ECD->getType() == BestType) {
1892 // Already the right type!
1893 continue;
1894 } else {
1895 NewTy = BestType;
1896 NewWidth = BestWidth;
1897 NewSign = BestType->isSignedIntegerType();
1898 }
1899
1900 // Adjust the APSInt value.
1901 InitVal.extOrTrunc(NewWidth);
1902 InitVal.setIsSigned(NewSign);
1903 ECD->setInitVal(InitVal);
1904
1905 // Adjust the Expr initializer and type.
1906 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1907 ECD->setType(NewTy);
1908 }
Chris Lattnerac609682007-08-28 06:15:15 +00001909
Chris Lattnere00b18c2007-08-28 18:24:31 +00001910 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001911}
1912
1913void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1914 if (!current) return;
1915
1916 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1917 // remember this in the LastInGroupList list.
1918 if (last)
1919 LastInGroupList.push_back((Decl*)last);
1920}
1921
1922void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1923 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1924 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1925 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1926 if (!newType.isNull()) // install the new vector type into the decl
1927 vDecl->setType(newType);
1928 }
1929 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1930 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1931 rawAttr);
1932 if (!newType.isNull()) // install the new vector type into the decl
1933 tDecl->setUnderlyingType(newType);
1934 }
1935 }
Steve Naroff73322922007-07-18 18:00:27 +00001936 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001937 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1938 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1939 else
Steve Naroff73322922007-07-18 18:00:27 +00001940 Diag(rawAttr->getAttributeLoc(),
1941 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00001942 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001943 // FIXME: add other attributes...
1944}
1945
1946void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1947 AttributeList *declarator_postfix) {
1948 while (declspec_prefix) {
1949 HandleDeclAttribute(New, declspec_prefix);
1950 declspec_prefix = declspec_prefix->getNext();
1951 }
1952 while (declarator_postfix) {
1953 HandleDeclAttribute(New, declarator_postfix);
1954 declarator_postfix = declarator_postfix->getNext();
1955 }
1956}
1957
Steve Naroffbea0b342007-07-29 16:33:31 +00001958void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1959 AttributeList *rawAttr) {
1960 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00001961 // check the attribute arugments.
1962 if (rawAttr->getNumArgs() != 1) {
1963 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1964 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001965 return;
Steve Naroff73322922007-07-18 18:00:27 +00001966 }
1967 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1968 llvm::APSInt vecSize(32);
1969 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1970 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1971 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001972 return;
Steve Naroff73322922007-07-18 18:00:27 +00001973 }
1974 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1975 // in conjunction with complex types (pointers, arrays, functions, etc.).
1976 Type *canonType = curType.getCanonicalType().getTypePtr();
1977 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1978 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1979 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001980 return;
Steve Naroff73322922007-07-18 18:00:27 +00001981 }
1982 // unlike gcc's vector_size attribute, the size is specified as the
1983 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001984 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001985
1986 if (vectorSize == 0) {
1987 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1988 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001989 return;
Steve Naroff73322922007-07-18 18:00:27 +00001990 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001991 // Instantiate/Install the vector type, the number of elements is > 0.
1992 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1993 // Remember this typedef decl, we will need it later for diagnostics.
1994 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001995}
1996
Reid Spencer5f016e22007-07-11 17:01:13 +00001997QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001998 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001999 // check the attribute arugments.
2000 if (rawAttr->getNumArgs() != 1) {
2001 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2002 std::string("1"));
2003 return QualType();
2004 }
2005 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2006 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002007 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2009 sizeExpr->getSourceRange());
2010 return QualType();
2011 }
2012 // navigate to the base type - we need to provide for vector pointers,
2013 // vector arrays, and functions returning vectors.
2014 Type *canonType = curType.getCanonicalType().getTypePtr();
2015
Steve Naroff73322922007-07-18 18:00:27 +00002016 if (canonType->isPointerType() || canonType->isArrayType() ||
2017 canonType->isFunctionType()) {
2018 assert(1 && "HandleVector(): Complex type construction unimplemented");
2019 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2020 do {
2021 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2022 canonType = PT->getPointeeType().getTypePtr();
2023 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2024 canonType = AT->getElementType().getTypePtr();
2025 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2026 canonType = FT->getResultType().getTypePtr();
2027 } while (canonType->isPointerType() || canonType->isArrayType() ||
2028 canonType->isFunctionType());
2029 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002030 }
2031 // the base type must be integer or float.
2032 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2033 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2034 curType.getCanonicalType().getAsString());
2035 return QualType();
2036 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00002037 unsigned typeSize = static_cast<unsigned>(
2038 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002039 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002040 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002041
2042 // the vector size needs to be an integral multiple of the type size.
2043 if (vectorSize % typeSize) {
2044 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
2045 sizeExpr->getSourceRange());
2046 return QualType();
2047 }
2048 if (vectorSize == 0) {
2049 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2050 sizeExpr->getSourceRange());
2051 return QualType();
2052 }
2053 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
2054 // the number of elements to be a power of two (unlike GCC).
2055 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00002056 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002057}
2058