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