blob: 1290975a24b0b315758f155484ad644b8f8c008a [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
Steve Naroff563477d2007-09-18 23:55:05 +000025#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000027#include "llvm/ADT/DenseSet.h"
Steve Naroff8ee529b2007-10-31 18:42:27 +000028#include "clang/Lex/Preprocessor.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
Reid Spencer5f016e22007-07-11 17:01:13 +000031Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000032 Decl *IIDecl = II.getFETokenInfo<Decl>();
33 // Find first occurance of none-tagged declaration
34 while(IIDecl && IIDecl->getIdentifierNamespace() != Decl::IDNS_Ordinary)
35 IIDecl = cast<ScopedDecl>(IIDecl)->getNext();
36 if (!IIDecl)
37 return 0;
38 if (isa<TypedefDecl>(IIDecl) || isa<ObjcInterfaceDecl>(IIDecl))
39 return IIDecl;
40 if (ObjcCompatibleAliasDecl *ADecl =
41 dyn_cast<ObjcCompatibleAliasDecl>(IIDecl))
42 return ADecl->getClassInterface();
Steve Naroff3536b442007-09-06 21:24:23 +000043 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000044}
45
Steve Naroffb216c882007-10-09 22:01:59 +000046void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000047 if (S->decl_empty()) return;
48 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
49
Reid Spencer5f016e22007-07-11 17:01:13 +000050 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
51 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000052 Decl *TmpD = static_cast<Decl*>(*I);
53 assert(TmpD && "This decl didn't get pushed??");
54 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
55 assert(D && "This decl isn't a ScopedDecl?");
56
Reid Spencer5f016e22007-07-11 17:01:13 +000057 IdentifierInfo *II = D->getIdentifier();
58 if (!II) continue;
59
60 // Unlink this decl from the identifier. Because the scope contains decls
61 // in an unordered collection, and because we have multiple identifier
62 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
63 if (II->getFETokenInfo<Decl>() == D) {
64 // Normal case, no multiple decls in different namespaces.
65 II->setFETokenInfo(D->getNext());
66 } else {
67 // Scan ahead. There are only three namespaces in C, so this loop can
68 // never execute more than 3 times.
Steve Naroffc752d042007-09-13 18:10:37 +000069 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +000070 while (SomeDecl->getNext() != D) {
71 SomeDecl = SomeDecl->getNext();
72 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
73 }
74 SomeDecl->setNext(D->getNext());
75 }
76
77 // This will have to be revisited for C++: there we want to nest stuff in
78 // namespace decls etc. Even for C, we might want a top-level translation
79 // unit decl or something.
80 if (!CurFunctionDecl)
81 continue;
82
83 // Chain this decl to the containing function, it now owns the memory for
84 // the decl.
85 D->setNext(CurFunctionDecl->getDeclChain());
86 CurFunctionDecl->setDeclChain(D);
87 }
88}
89
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +000090/// LookupInterfaceDecl - Lookup interface declaration in the scope chain.
91/// Return the first declaration found (which may or may not be a class
Fariborz Jahanian3fe44e42007-10-12 19:53:08 +000092/// declaration. Caller is responsible for handling the none-class case.
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +000093/// Bypassing the alias of a class by returning the aliased class.
94ScopedDecl *Sema::LookupInterfaceDecl(IdentifierInfo *ClassName) {
95 ScopedDecl *IDecl;
96 // Scan up the scope chain looking for a decl that matches this identifier
97 // that is in the appropriate namespace.
98 for (IDecl = ClassName->getFETokenInfo<ScopedDecl>(); IDecl;
99 IDecl = IDecl->getNext())
100 if (IDecl->getIdentifierNamespace() == Decl::IDNS_Ordinary)
101 break;
102
103 if (ObjcCompatibleAliasDecl *ADecl =
104 dyn_cast_or_null<ObjcCompatibleAliasDecl>(IDecl))
105 return ADecl->getClassInterface();
106 return IDecl;
107}
108
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000109/// getObjcInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +0000110/// return 0 if one not found.
Steve Naroff6a8a9a42007-10-02 20:01:56 +0000111ObjcInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000112 ScopedDecl *IdDecl = LookupInterfaceDecl(Id);
113 return cast_or_null<ObjcInterfaceDecl>(IdDecl);
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +0000114}
115
Reid Spencer5f016e22007-07-11 17:01:13 +0000116/// LookupScopedDecl - Look up the inner-most declaration in the specified
117/// namespace.
Steve Naroffc752d042007-09-13 18:10:37 +0000118ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
119 SourceLocation IdLoc, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 if (II == 0) return 0;
121 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
122
123 // Scan up the scope chain looking for a decl that matches this identifier
124 // that is in the appropriate namespace. This search should not take long, as
125 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffc752d042007-09-13 18:10:37 +0000126 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 if (D->getIdentifierNamespace() == NS)
128 return D;
129
130 // If we didn't find a use of this identifier, and if the identifier
131 // corresponds to a compiler builtin, create the decl object for the builtin
132 // now, injecting it into translation unit scope, and return it.
133 if (NS == Decl::IDNS_Ordinary) {
134 // If this is a builtin on some other target, or if this builtin varies
135 // across targets (e.g. in type), emit a diagnostic and mark the translation
136 // unit non-portable for using it.
137 if (II->isNonPortableBuiltin()) {
138 // Only emit this diagnostic once for this builtin.
139 II->setNonPortableBuiltin(false);
140 Context.Target.DiagnoseNonPortability(IdLoc,
141 diag::port_target_builtin_use);
142 }
143 // If this is a builtin on this (or all) targets, create the decl.
144 if (unsigned BuiltinID = II->getBuiltinID())
145 return LazilyCreateBuiltin(II, BuiltinID, S);
146 }
147 return 0;
148}
149
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000150void Sema::InitBuiltinVaListType()
151{
152 if (!Context.getBuiltinVaListType().isNull())
153 return;
154
155 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
156 ScopedDecl *VaDecl = LookupScopedDecl(VaIdent, Decl::IDNS_Ordinary,
157 SourceLocation(), TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000158 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000159 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
160}
161
Reid Spencer5f016e22007-07-11 17:01:13 +0000162/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
163/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000164ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
165 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000166 Builtin::ID BID = (Builtin::ID)bid;
167
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000168 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson793680e2007-10-12 23:56:29 +0000169 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000170 BID == Builtin::BI__builtin_va_end)
171 InitBuiltinVaListType();
172
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000173 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Reid Spencer5f016e22007-07-11 17:01:13 +0000174 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000175 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000176
177 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000178 if (Scope *FnS = S->getFnParent())
179 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000180 while (S->getParent())
181 S = S->getParent();
182 S->AddDecl(New);
183
184 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000185 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 // Scan until we find the last (outermost) decl in the id chain.
187 while (LastDecl->getNext())
188 LastDecl = LastDecl->getNext();
189 // Insert before (outside) it.
190 LastDecl->setNext(New);
191 } else {
192 II->setFETokenInfo(New);
193 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000194 return New;
195}
196
197/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
198/// and scope as a previous declaration 'Old'. Figure out how to resolve this
199/// situation, merging decls or emitting diagnostics as appropriate.
200///
Steve Naroff8e74c932007-09-13 21:41:19 +0000201TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000202 // Verify the old decl was also a typedef.
203 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
204 if (!Old) {
205 Diag(New->getLocation(), diag::err_redefinition_different_kind,
206 New->getName());
207 Diag(OldD->getLocation(), diag::err_previous_definition);
208 return New;
209 }
210
Steve Naroff8ee529b2007-10-31 18:42:27 +0000211 // Allow multiple definitions for ObjC built-in typedefs.
212 // FIXME: Verify the underlying types are equivalent!
213 if (PP.getLangOptions().ObjC1 && isBuiltinObjcType(New))
214 return Old;
215
Reid Spencer5f016e22007-07-11 17:01:13 +0000216 // 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/// MergeFunctionDecl - We just parsed a function '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///
Steve Naroff8e74c932007-09-13 21:41:19 +0000228FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000229 // Verify the old decl was also a function.
230 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
231 if (!Old) {
232 Diag(New->getLocation(), diag::err_redefinition_different_kind,
233 New->getName());
234 Diag(OldD->getLocation(), diag::err_previous_definition);
235 return New;
236 }
237
Chris Lattner55196442007-11-20 19:04:50 +0000238 QualType OldQType = Old->getCanonicalType();
239 QualType NewQType = New->getCanonicalType();
240
241 // This is not right, but it's a start.
242 // If Old is a function prototype with no defined arguments we only compare
243 // the return type; If arguments are defined on the prototype we validate the
244 // entire function type.
245 // FIXME: We should link up decl objects here.
246 if (Old->getBody() == 0) {
247 if (OldQType.getTypePtr()->getTypeClass() == Type::FunctionNoProto &&
248 Old->getResultType() == New->getResultType())
249 return New;
250 if (OldQType == NewQType)
251 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +0000252 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000253
Chris Lattner55196442007-11-20 19:04:50 +0000254 if (New->getBody() == 0 && OldQType == NewQType) {
Chris Lattnere3995fe2007-11-06 06:07:26 +0000255 return 0;
256 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000257
258 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
259 // TODO: This is totally simplistic. It should handle merging functions
260 // together etc, merging extern int X; int X; ...
261 Diag(New->getLocation(), diag::err_redefinition, New->getName());
262 Diag(Old->getLocation(), diag::err_previous_definition);
263 return New;
264}
265
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000266
267/// hasUndefinedLength - Used by equivalentArrayTypes to determine whether the
268/// the outermost VariableArrayType has no size defined.
269static bool hasUndefinedLength(const ArrayType *Array) {
270 const VariableArrayType *VAT = Array->getAsVariableArrayType();
271 return VAT && !VAT->getSizeExpr();
272}
273
274/// equivalentArrayTypes - Used to determine whether two array types are
275/// equivalent.
276/// We need to check this explicitly as an incomplete array definition is
277/// considered a VariableArrayType, so will not match a complete array
278/// definition that would be otherwise equivalent.
279static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
280 const ArrayType *NewAT = NewQType->getAsArrayType();
281 const ArrayType *OldAT = OldQType->getAsArrayType();
282
283 if (!NewAT || !OldAT)
284 return false;
285
286 // If either (or both) array types in incomplete we need to strip off the
287 // outer VariableArrayType. Once the outer VAT is removed the remaining
288 // types must be identical if the array types are to be considered
289 // equivalent.
290 // eg. int[][1] and int[1][1] become
291 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
292 // removing the outermost VAT gives
293 // CAT(1, int) and CAT(1, int)
294 // which are equal, therefore the array types are equivalent.
295 if (hasUndefinedLength(NewAT) || hasUndefinedLength(OldAT)) {
296 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
297 return false;
298 NewQType = NewAT->getElementType();
299 OldQType = OldAT->getElementType();
300 }
301
302 return NewQType == OldQType;
303}
304
Reid Spencer5f016e22007-07-11 17:01:13 +0000305/// MergeVarDecl - We just parsed a variable 'New' which has the same name
306/// and scope as a previous declaration 'Old'. Figure out how to resolve this
307/// situation, merging decls or emitting diagnostics as appropriate.
308///
309/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
310/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
311///
Steve Naroff8e74c932007-09-13 21:41:19 +0000312VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 // Verify the old decl was also a variable.
314 VarDecl *Old = dyn_cast<VarDecl>(OldD);
315 if (!Old) {
316 Diag(New->getLocation(), diag::err_redefinition_different_kind,
317 New->getName());
318 Diag(OldD->getLocation(), diag::err_previous_definition);
319 return New;
320 }
Steve Narofffb22d962007-08-30 01:06:46 +0000321 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
322 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
323 bool OldIsTentative = false;
324
325 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
326 // Handle C "tentative" external object definitions. FIXME: finish!
327 if (!OldFSDecl->getInit() &&
328 (OldFSDecl->getStorageClass() == VarDecl::None ||
329 OldFSDecl->getStorageClass() == VarDecl::Static))
330 OldIsTentative = true;
331 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000332 // Verify the types match.
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000333 if (Old->getCanonicalType() != New->getCanonicalType() &&
334 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 Diag(New->getLocation(), diag::err_redefinition, New->getName());
336 Diag(Old->getLocation(), diag::err_previous_definition);
337 return New;
338 }
339 // We've verified the types match, now check if Old is "extern".
340 if (Old->getStorageClass() != VarDecl::Extern) {
341 Diag(New->getLocation(), diag::err_redefinition, New->getName());
342 Diag(Old->getLocation(), diag::err_previous_definition);
343 }
344 return New;
345}
346
347/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
348/// no declarator (e.g. "struct foo;") is parsed.
349Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
350 // TODO: emit error on 'int;' or 'const enum foo;'.
351 // TODO: emit error on 'typedef int;'
352 // if (!DS.isMissingDeclaratorOk()) Diag(...);
353
Steve Naroff92199282007-11-17 21:37:36 +0000354 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000355}
356
Anders Carlsson1a86b332007-10-17 00:52:43 +0000357bool Sema::CheckSingleInitializer(Expr *&Init, bool isStatic,
358 QualType DeclType) {
Chris Lattnerf471f2e2007-11-27 21:21:35 +0000359 SourceLocation loc = Init->getLocStart();
Anders Carlsson1a86b332007-10-17 00:52:43 +0000360
361 // FIXME: Remove the isReferenceType check and handle assignment
362 // to a reference.
363 if (isStatic && !DeclType->isReferenceType() &&
364 !Init->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
365 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
366 return true;
367 }
368
Steve Narofff0090632007-09-02 02:04:30 +0000369 AssignmentCheckResult result;
Steve Narofff0090632007-09-02 02:04:30 +0000370 // Get the type before calling CheckSingleAssignmentConstraints(), since
371 // it can promote the expression.
372 QualType rhsType = Init->getType();
373
374 result = CheckSingleAssignmentConstraints(DeclType, Init);
375
376 // decode the result (notice that extensions still return a type).
377 switch (result) {
378 case Compatible:
379 break;
380 case Incompatible:
Steve Naroff6f9f3072007-09-02 15:34:30 +0000381 // FIXME: tighten up this check which should allow:
382 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
383 if (rhsType == Context.getPointerType(Context.CharTy))
384 break;
Steve Narofff0090632007-09-02 02:04:30 +0000385 Diag(loc, diag::err_typecheck_assign_incompatible,
386 DeclType.getAsString(), rhsType.getAsString(),
387 Init->getSourceRange());
388 return true;
389 case PointerFromInt:
Steve Naroff529a4ad2007-11-27 17:58:44 +0000390 Diag(loc, diag::ext_typecheck_assign_pointer_int,
391 DeclType.getAsString(), rhsType.getAsString(),
392 Init->getSourceRange());
Steve Narofff0090632007-09-02 02:04:30 +0000393 break;
394 case IntFromPointer:
395 Diag(loc, diag::ext_typecheck_assign_pointer_int,
396 DeclType.getAsString(), rhsType.getAsString(),
397 Init->getSourceRange());
398 break;
399 case IncompatiblePointer:
400 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
401 DeclType.getAsString(), rhsType.getAsString(),
402 Init->getSourceRange());
403 break;
404 case CompatiblePointerDiscardsQualifiers:
405 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
406 DeclType.getAsString(), rhsType.getAsString(),
407 Init->getSourceRange());
408 break;
409 }
410 return false;
411}
412
Steve Naroff9e8925e2007-09-04 14:36:54 +0000413bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
414 bool isStatic, QualType ElementType) {
Steve Naroff371227d2007-09-04 02:20:04 +0000415 SourceLocation loc;
Steve Naroff9e8925e2007-09-04 14:36:54 +0000416 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff371227d2007-09-04 02:20:04 +0000417
418 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
419 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
420 return true;
Anders Carlsson1a86b332007-10-17 00:52:43 +0000421 } else if (CheckSingleInitializer(expr, isStatic, ElementType)) {
Steve Naroff371227d2007-09-04 02:20:04 +0000422 return true; // types weren't compatible.
423 }
Steve Naroff9e8925e2007-09-04 14:36:54 +0000424 if (savExpr != expr) // The type was promoted, update initializer list.
425 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000426 return false;
427}
428
429void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
430 QualType ElementType, bool isStatic,
431 int &nInitializers, bool &hadError) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000432 unsigned numInits = IList->getNumInits();
433
434 if (numInits) {
435 if (CheckForCharArrayInitializer(IList, ElementType, nInitializers,
436 false, hadError))
437 return;
438
439 for (unsigned i = 0; i < numInits; i++) {
440 Expr *expr = IList->getInit(i);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000441
Steve Naroff2fdc3742007-12-10 22:44:33 +0000442 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
443 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
444 int maxElements = CAT->getMaximumElements();
445 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
446 maxElements, hadError);
447 }
448 } else {
449 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
450 }
451 nInitializers++;
452 }
453 } else {
454 Diag(IList->getLocStart(),
455 diag::err_at_least_one_initializer_needed_to_size_array);
456 hadError = true;
457 }
458}
459
460bool Sema::CheckForCharArrayInitializer(InitListExpr *IList,
461 QualType ElementType,
462 int &nInitializers, bool isConstant,
463 bool &hadError)
464{
465 if (ElementType->isPointerType())
466 return false;
467
468 if (StringLiteral *literal = dyn_cast<StringLiteral>(IList->getInit(0))) {
469 // FIXME: Handle wide strings
470 if (ElementType->isCharType()) {
471 if (isConstant) {
472 if (literal->getByteLength() > (unsigned)nInitializers) {
473 Diag(literal->getSourceRange().getBegin(),
474 diag::warn_initializer_string_for_char_array_too_long,
475 literal->getSourceRange());
476 }
477 } else {
478 nInitializers = literal->getByteLength() + 1;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000479 }
Steve Naroff371227d2007-09-04 02:20:04 +0000480 } else {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000481 // FIXME: It might be better if we could point to the declaration
482 // here, instead of the string literal.
483 Diag(literal->getSourceRange().getBegin(),
484 diag::array_of_wrong_type_initialized_from_string,
485 ElementType.getAsString());
486 hadError = true;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000487 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000488
489 // Check for excess initializers
490 for (unsigned i = 1; i < IList->getNumInits(); i++) {
491 Expr *expr = IList->getInit(i);
492 Diag(expr->getLocStart(),
493 diag::err_excess_initializers_in_char_array_initializer,
494 expr->getSourceRange());
495 }
496
497 return true;
Steve Naroff371227d2007-09-04 02:20:04 +0000498 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000499
500 return false;
Steve Naroff371227d2007-09-04 02:20:04 +0000501}
502
503// FIXME: Doesn't deal with arrays of structures yet.
504void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
505 QualType ElementType, bool isStatic,
506 int &totalInits, bool &hadError) {
507 int maxElementsAtThisLevel = 0;
508 int nInitsAtLevel = 0;
509
Steve Naroff32c39042007-12-07 21:12:53 +0000510 if (ElementType->isRecordType()) // FIXME: until we support structures...
511 return;
512
Steve Naroff371227d2007-09-04 02:20:04 +0000513 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
514 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff7cf8c442007-09-04 21:13:33 +0000515 maxElementsAtThisLevel = CAT->getMaximumElements();
516 // Set DeclType, used below to recurse (for multi-dimensional arrays).
517 DeclType = CAT->getElementType();
Steve Naroff371227d2007-09-04 02:20:04 +0000518 } else if (DeclType->isScalarType()) {
Anders Carlssonf0049e62007-12-03 01:01:28 +0000519 if (const VectorType *VT = DeclType->getAsVectorType())
520 maxElementsAtThisLevel = VT->getNumElements();
521 else {
522 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
523 IList->getSourceRange());
524 maxElementsAtThisLevel = 1;
525 }
Steve Naroff371227d2007-09-04 02:20:04 +0000526 }
527 // The empty init list "{ }" is treated specially below.
528 unsigned numInits = IList->getNumInits();
529 if (numInits) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000530 if (CheckForCharArrayInitializer(IList, ElementType,
531 maxElementsAtThisLevel,
532 true, hadError))
533 return;
534
Steve Naroff371227d2007-09-04 02:20:04 +0000535 for (unsigned i = 0; i < numInits; i++) {
536 Expr *expr = IList->getInit(i);
537
538 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
539 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
540 totalInits, hadError);
541 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000542 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff371227d2007-09-04 02:20:04 +0000543 nInitsAtLevel++; // increment the number of initializers at this level.
544 totalInits--; // decrement the total number of initializers.
545
546 // Check if we have space for another initializer.
Anders Carlsson677cda12007-12-05 04:57:06 +0000547 if (((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0)))
Steve Naroff371227d2007-09-04 02:20:04 +0000548 Diag(expr->getLocStart(), diag::warn_excess_initializers,
549 expr->getSourceRange());
550 }
551 }
552 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
553 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
554 } else {
555 // we have an initializer list with no elements.
556 totalInits -= maxElementsAtThisLevel;
557 if (totalInits < 0)
558 Diag(IList->getLocStart(), diag::warn_excess_initializers,
559 IList->getSourceRange());
Steve Naroff6f9f3072007-09-02 15:34:30 +0000560 }
Steve Naroff6f9f3072007-09-02 15:34:30 +0000561}
562
Steve Naroff9e8925e2007-09-04 14:36:54 +0000563bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000564 bool hadError = false;
Anders Carlsson1a86b332007-10-17 00:52:43 +0000565
Steve Naroff2fdc3742007-12-10 22:44:33 +0000566 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
567 if (!InitList) {
568 if (StringLiteral *strLiteral = dyn_cast<StringLiteral>(Init)) {
569 const VariableArrayType *VAT = DeclType->getAsVariableArrayType();
570 // FIXME: Handle wide strings
571 if (VAT && VAT->getElementType()->isCharType()) {
572 // C99 6.7.8p14. We have an array of character type with unknown size
573 // being initialized to a string literal.
574 llvm::APSInt ConstVal(32);
575 ConstVal = strLiteral->getByteLength() + 1;
576 // Return a new array type (C99 6.7.8p22).
577 DeclType = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
578 ArrayType::Normal, 0);
579 return hadError;
580 }
581 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
582 if (CAT && CAT->getElementType()->isCharType()) {
583 // C99 6.7.8p14. We have an array of character type with known size.
584 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements()) {
585 Diag(strLiteral->getSourceRange().getBegin(),
586 diag::warn_initializer_string_for_char_array_too_long,
587 strLiteral->getSourceRange());
588 }
589 return hadError;
590 }
591 }
592 return CheckSingleInitializer(Init, isStatic, DeclType);
593 }
Steve Narofff0090632007-09-02 02:04:30 +0000594 // We have an InitListExpr, make sure we set the type.
595 Init->setType(DeclType);
Steve Naroffd35005e2007-09-03 01:24:23 +0000596
Steve Naroff38374b02007-09-02 20:30:18 +0000597 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
598 // of unknown size ("[]") or an object type that is not a variable array type.
599 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
600 Expr *expr = VAT->getSizeExpr();
Steve Naroffd35005e2007-09-03 01:24:23 +0000601 if (expr)
602 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
603 expr->getSourceRange());
604
Steve Naroff7cf8c442007-09-04 21:13:33 +0000605 // We have a VariableArrayType with unknown size. Note that only the first
606 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff371227d2007-09-04 02:20:04 +0000607 int numInits = 0;
Steve Naroff7cf8c442007-09-04 21:13:33 +0000608 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
609 isStatic, numInits, hadError);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000610 llvm::APSInt ConstVal(32);
611
612 if (!hadError)
Steve Naroff371227d2007-09-04 02:20:04 +0000613 ConstVal = numInits;
Steve Naroff2fdc3742007-12-10 22:44:33 +0000614
615 // Return a new array type from the number of initializers (C99 6.7.8p22).
616
617 // Note that if there was an error, we will still set the decl type,
618 // to an array type with 0 elements.
619 // This is to avoid "incomplete type foo[]" errors when we've already
620 // reported the real cause of the error.
621 DeclType = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
622 ArrayType::Normal, 0);
Steve Naroffd35005e2007-09-03 01:24:23 +0000623 return hadError;
624 }
625 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000626 int maxElements = CAT->getMaximumElements();
627 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
628 isStatic, maxElements, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000629 return hadError;
630 }
Anders Carlssonf0049e62007-12-03 01:01:28 +0000631 if (const VectorType *VT = DeclType->getAsVectorType()) {
632 int maxElements = VT->getNumElements();
633 CheckConstantInitList(DeclType, InitList, VT->getElementType(),
634 isStatic, maxElements, hadError);
635 return hadError;
636 }
Steve Naroff371227d2007-09-04 02:20:04 +0000637 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
638 int maxElements = 1;
639 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
640 hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000641 return hadError;
Steve Naroff38374b02007-09-02 20:30:18 +0000642 }
Steve Naroffe6386392007-12-05 04:00:10 +0000643 // FIXME: Handle struct/union types, including those appearing in a
644 // CompoundLiteralExpr...
Steve Naroffd35005e2007-09-03 01:24:23 +0000645 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +0000646}
647
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000648Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000649Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000650 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000651 IdentifierInfo *II = D.getIdentifier();
652
Chris Lattnere80a59c2007-07-25 00:24:17 +0000653 // All of these full declarators require an identifier. If it doesn't have
654 // one, the ParsedFreeStandingDeclSpec action should be used.
655 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000656 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000657 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000658 D.getDeclSpec().getSourceRange(), D.getSourceRange());
659 return 0;
660 }
661
Chris Lattner31e05722007-08-26 06:24:45 +0000662 // The scope passed in may not be a decl scope. Zip up the scope tree until
663 // we find one that is.
664 while ((S->getFlags() & Scope::DeclScope) == 0)
665 S = S->getParent();
666
Reid Spencer5f016e22007-07-11 17:01:13 +0000667 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000668 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
669 D.getIdentifierLoc(), S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000670 if (PrevDecl && !S->isDeclScope(PrevDecl))
671 PrevDecl = 0; // If in outer scope, it isn't the same thing.
672
Steve Naroffc752d042007-09-13 18:10:37 +0000673 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000674 bool InvalidDecl = false;
675
Chris Lattner41af0932007-11-14 06:34:38 +0000676 QualType R = GetTypeForDeclarator(D, S);
677 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
678
Reid Spencer5f016e22007-07-11 17:01:13 +0000679 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000680 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000681 if (!NewTD) return 0;
682
683 // Handle attributes prior to checking for duplicates in MergeVarDecl
684 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
685 D.getAttributes());
686 // Merge the decl with the existing one if appropriate.
687 if (PrevDecl) {
688 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
689 if (NewTD == 0) return 0;
690 }
691 New = NewTD;
692 if (S->getParent() == 0) {
693 // C99 6.7.7p2: If a typedef name specifies a variably modified type
694 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000695 if (const VariableArrayType *VAT =
696 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
697 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
698 VAT->getSizeExpr()->getSourceRange());
699 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 }
701 }
Chris Lattner41af0932007-11-14 06:34:38 +0000702 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000703 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000704 switch (D.getDeclSpec().getStorageClassSpec()) {
705 default: assert(0 && "Unknown storage class!");
706 case DeclSpec::SCS_auto:
707 case DeclSpec::SCS_register:
708 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
709 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000710 InvalidDecl = true;
711 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000712 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
713 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
714 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
715 }
716
717 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000718 D.getDeclSpec().isInlineSpecified(),
Nate Begeman1b4e2512007-11-13 22:14:47 +0000719 LastDeclarator,
720 D.getDeclSpec().getAttributes());
721
722 // Transfer ownership of DeclSpec attributes to FunctionDecl
723 D.getDeclSpec().clearAttributes();
Reid Spencer5f016e22007-07-11 17:01:13 +0000724
725 // Merge the decl with the existing one if appropriate.
726 if (PrevDecl) {
727 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
728 if (NewFD == 0) return 0;
729 }
730 New = NewFD;
731 } else {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000732 if (R.getTypePtr()->isObjcInterfaceType()) {
733 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
734 D.getIdentifier()->getName());
735 InvalidDecl = true;
736 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000737
738 VarDecl *NewVD;
739 VarDecl::StorageClass SC;
740 switch (D.getDeclSpec().getStorageClassSpec()) {
741 default: assert(0 && "Unknown storage class!");
742 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
743 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
744 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
745 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
746 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
747 }
748 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000749 // C99 6.9p2: The storage-class specifiers auto and register shall not
750 // appear in the declaration specifiers in an external declaration.
751 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
752 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
753 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000754 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000755 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000757 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000758 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000759 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000760 // Handle attributes prior to checking for duplicates in MergeVarDecl
761 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
762 D.getAttributes());
763
764 // Merge the decl with the existing one if appropriate.
765 if (PrevDecl) {
766 NewVD = MergeVarDecl(NewVD, PrevDecl);
767 if (NewVD == 0) return 0;
768 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000769 New = NewVD;
770 }
771
772 // If this has an identifier, add it to the scope stack.
773 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000774 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000775 II->setFETokenInfo(New);
776 S->AddDecl(New);
777 }
Steve Naroff5912a352007-08-28 20:14:24 +0000778 // If any semantic error occurred, mark the decl as invalid.
779 if (D.getInvalidType() || InvalidDecl)
780 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000781
782 return New;
783}
784
Steve Naroffbb204692007-09-12 14:07:44 +0000785void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000786 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000787 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000788 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000789
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000790 // If there is no declaration, there was an error parsing it. Just ignore
791 // the initializer.
792 if (RealDecl == 0) {
793 delete Init;
794 return;
795 }
Steve Naroffbb204692007-09-12 14:07:44 +0000796
Steve Naroff410e3e22007-09-12 20:13:48 +0000797 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
798 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000799 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
800 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000801 RealDecl->setInvalidDecl();
802 return;
803 }
Steve Naroffbb204692007-09-12 14:07:44 +0000804 // Get the decls type and save a reference for later, since
805 // CheckInitializer may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000806 QualType DclT = VDecl->getType(), SavT = DclT;
807 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000808 VarDecl::StorageClass SC = BVD->getStorageClass();
809 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000810 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000811 BVD->setInvalidDecl();
812 } else if (!BVD->isInvalidDecl()) {
813 CheckInitializer(Init, DclT, SC == VarDecl::Static);
814 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000815 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000816 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000817 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000818 if (!FVD->isInvalidDecl())
819 CheckInitializer(Init, DclT, true);
820 }
821 // If the type changed, it means we had an incomplete type that was
822 // completed by the initializer. For example:
823 // int ary[] = { 1, 3, 5 };
824 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +0000825 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000826 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +0000827 Init->setType(DclT);
828 }
Steve Naroffbb204692007-09-12 14:07:44 +0000829
830 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000831 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000832 return;
833}
834
Reid Spencer5f016e22007-07-11 17:01:13 +0000835/// The declarators are chained together backwards, reverse the list.
836Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
837 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000838 Decl *GroupDecl = static_cast<Decl*>(group);
839 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000840 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000841
842 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
843 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000844 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000845 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000846 else { // reverse the list.
847 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000848 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000849 Group->setNextDeclarator(NewGroup);
850 NewGroup = Group;
851 Group = Next;
852 }
853 }
854 // Perform semantic analysis that depends on having fully processed both
855 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000856 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000857 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
858 if (!IDecl)
859 continue;
860 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
861 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
862 QualType T = IDecl->getType();
863
864 // C99 6.7.5.2p2: If an identifier is declared to be an object with
865 // static storage duration, it shall not have a variable length array.
866 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
867 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
868 if (VLA->getSizeExpr()) {
869 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
870 IDecl->setInvalidDecl();
871 }
872 }
873 }
874 // Block scope. C99 6.7p7: If an identifier for an object is declared with
875 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
876 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
877 if (T->isIncompleteType()) {
Chris Lattner8b1be772007-12-02 07:50:03 +0000878 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
879 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000880 IDecl->setInvalidDecl();
881 }
882 }
883 // File scope. C99 6.9.2p2: A declaration of an identifier for and
884 // object that has file scope without an initializer, and without a
885 // storage-class specifier or with the storage-class specifier "static",
886 // constitutes a tentative definition. Note: A tentative definition with
887 // external linkage is valid (C99 6.2.2p5).
888 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
889 // C99 6.9.2p3: If the declaration of an identifier for an object is
890 // a tentative definition and has internal linkage (C99 6.2.2p3), the
891 // declared type shall not be an incomplete type.
892 if (T->isIncompleteType()) {
Chris Lattner8b1be772007-12-02 07:50:03 +0000893 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
894 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000895 IDecl->setInvalidDecl();
896 }
897 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000898 }
899 return NewGroup;
900}
Steve Naroffe1223f72007-08-28 03:03:08 +0000901
902// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000903ParmVarDecl *
Nate Begemanbff5f5c2007-11-13 21:49:48 +0000904Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI, Scope *FnScope)
Steve Naroff66499922007-11-12 03:44:46 +0000905{
Reid Spencer5f016e22007-07-11 17:01:13 +0000906 IdentifierInfo *II = PI.Ident;
907 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
908 // Can this happen for params? We already checked that they don't conflict
909 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000910 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000911 PI.IdentLoc, FnScope)) {
912
913 }
914
915 // FIXME: Handle storage class (auto, register). No declarator?
916 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000917
918 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
919 // Doing the promotion here has a win and a loss. The win is the type for
920 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
921 // code generator). The loss is the orginal type isn't preserved. For example:
922 //
923 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
924 // int blockvardecl[5];
925 // sizeof(parmvardecl); // size == 4
926 // sizeof(blockvardecl); // size == 20
927 // }
928 //
929 // For expressions, all implicit conversions are captured using the
930 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
931 //
932 // FIXME: If a source translation tool needs to see the original type, then
933 // we need to consider storing both types (in ParmVarDecl)...
934 //
935 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
936 if (const ArrayType *AT = parmDeclType->getAsArrayType())
937 parmDeclType = Context.getPointerType(AT->getElementType());
938 else if (parmDeclType->isFunctionType())
939 parmDeclType = Context.getPointerType(parmDeclType);
940
941 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Nate Begeman1b4e2512007-11-13 22:14:47 +0000942 VarDecl::None, 0, PI.AttrList);
Steve Naroff53a32342007-08-28 18:45:29 +0000943 if (PI.InvalidType)
944 New->setInvalidDecl();
945
Reid Spencer5f016e22007-07-11 17:01:13 +0000946 // If this has an identifier, add it to the scope stack.
947 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000948 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000949 II->setFETokenInfo(New);
950 FnScope->AddDecl(New);
951 }
952
953 return New;
954}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000955
Chris Lattnerb652cea2007-10-09 17:14:05 +0000956Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000957 assert(CurFunctionDecl == 0 && "Function parsing confused");
958 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
959 "Not a function declarator!");
960 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
961
962 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
963 // for a K&R function.
964 if (!FTI.hasPrototype) {
965 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
966 if (FTI.ArgInfo[i].TypeInfo == 0) {
967 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
968 FTI.ArgInfo[i].Ident->getName());
969 // Implicitly declare the argument as type 'int' for lack of a better
970 // type.
971 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
972 }
973 }
974
975 // Since this is a function definition, act as though we have information
976 // about the arguments.
977 FTI.hasPrototype = true;
978 } else {
979 // FIXME: Diagnose arguments without names in C.
980
981 }
982
983 Scope *GlobalScope = FnBodyScope->getParent();
984
985 FunctionDecl *FD =
Steve Naroff08d92e42007-09-15 18:49:24 +0000986 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000987 CurFunctionDecl = FD;
988
989 // Create Decl objects for each parameter, adding them to the FunctionDecl.
990 llvm::SmallVector<ParmVarDecl*, 16> Params;
991
992 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
993 // no arguments, not a function that takes a single void argument.
994 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb751c282007-11-28 18:51:29 +0000995 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getQualifiers() &&
996 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 // empty arg list, don't push any params.
998 } else {
Steve Naroff66499922007-11-12 03:44:46 +0000999 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begemanbff5f5c2007-11-13 21:49:48 +00001000 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroff66499922007-11-12 03:44:46 +00001001 FnBodyScope));
1002 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001003 }
1004
1005 FD->setParams(&Params[0], Params.size());
1006
1007 return FD;
1008}
1009
Steve Naroffd6d054d2007-11-11 23:20:51 +00001010Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1011 Decl *dcl = static_cast<Decl *>(D);
1012 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1013 FD->setBody((Stmt*)Body);
1014 assert(FD == CurFunctionDecl && "Function parsing confused");
1015 } else if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(dcl)) {
1016 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001017 CurMethodDecl = 0;
Steve Naroffd6d054d2007-11-11 23:20:51 +00001018 }
Steve Naroff03300712007-11-12 13:56:41 +00001019 // This is unconditional, since methods have a corresponding function decl.
Reid Spencer5f016e22007-07-11 17:01:13 +00001020 CurFunctionDecl = 0;
1021
1022 // Verify and clean out per-function state.
1023
1024 // Check goto/label use.
1025 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1026 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1027 // Verify that we have no forward references left. If so, there was a goto
1028 // or address of a label taken, but no definition of it. Label fwd
1029 // definitions are indicated with a null substmt.
1030 if (I->second->getSubStmt() == 0) {
1031 LabelStmt *L = I->second;
1032 // Emit error.
1033 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1034
1035 // At this point, we have gotos that use the bogus label. Stitch it into
1036 // the function body so that they aren't leaked and that the AST is well
1037 // formed.
1038 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1039 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1040 }
1041 }
1042 LabelMap.clear();
1043
Steve Naroffd6d054d2007-11-11 23:20:51 +00001044 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001045}
1046
Fariborz Jahanian360300c2007-11-09 22:27:59 +00001047/// ObjcActOnStartOfMethodDef - This routine sets up parameters; invisible
1048/// and user declared, in the method definition's AST.
Fariborz Jahanian439d28c2007-11-10 17:40:57 +00001049void Sema::ObjcActOnStartOfMethodDef(Scope *FnBodyScope, DeclTy *D) {
Steve Naroff03300712007-11-12 13:56:41 +00001050 assert(CurFunctionDecl == 0 && "Method parsing confused");
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001051 ObjcMethodDecl *MDecl = dyn_cast<ObjcMethodDecl>(static_cast<Decl *>(D));
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001052 assert(MDecl != 0 && "Not a method declarator!");
1053
Steve Naroff03300712007-11-12 13:56:41 +00001054 // Allow all of Sema to see that we are entering a method definition.
1055 CurMethodDecl = MDecl;
Steve Naroff0755aba2007-11-12 04:59:00 +00001056
Fariborz Jahanianb107ce82007-12-04 19:20:11 +00001057 // Create Decl objects for each parameter, entrring them in the scope for
1058 // binding to their use.
Steve Naroff66499922007-11-12 03:44:46 +00001059 struct DeclaratorChunk::ParamInfo PI;
1060
Steve Naroff03300712007-11-12 13:56:41 +00001061 // Insert the invisible arguments, self and _cmd!
Steve Naroff66499922007-11-12 03:44:46 +00001062 PI.Ident = &Context.Idents.get("self");
Steve Naroff03300712007-11-12 13:56:41 +00001063 PI.IdentLoc = SourceLocation(); // synthesized vars have a null location.
Steve Naroffbd278bc2007-11-12 19:48:27 +00001064 PI.InvalidType = false;
Fariborz Jahanian1f7b6f82007-11-09 19:52:12 +00001065 if (MDecl->isInstance()) {
1066 QualType selfTy = Context.getObjcInterfaceType(MDecl->getClassInterface());
1067 selfTy = Context.getPointerType(selfTy);
Steve Naroff66499922007-11-12 03:44:46 +00001068 PI.TypeInfo = selfTy.getAsOpaquePtr();
1069 } else
1070 PI.TypeInfo = Context.getObjcIdType().getAsOpaquePtr();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001071 CurMethodDecl->setSelfDecl(ActOnParamDeclarator(PI, FnBodyScope));
Steve Naroff66499922007-11-12 03:44:46 +00001072
1073 PI.Ident = &Context.Idents.get("_cmd");
Steve Naroff66499922007-11-12 03:44:46 +00001074 PI.TypeInfo = Context.getObjcSelType().getAsOpaquePtr();
Fariborz Jahanianb107ce82007-12-04 19:20:11 +00001075 ActOnParamDeclarator(PI, FnBodyScope);
Steve Naroff66499922007-11-12 03:44:46 +00001076
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001077 for (int i = 0; i < MDecl->getNumParams(); i++) {
Steve Naroff66499922007-11-12 03:44:46 +00001078 ParmVarDecl *PDecl = MDecl->getParamDecl(i);
1079 PI.Ident = PDecl->getIdentifier();
Steve Naroff03300712007-11-12 13:56:41 +00001080 PI.IdentLoc = PDecl->getLocation(); // user vars have a real location.
Steve Naroff66499922007-11-12 03:44:46 +00001081 PI.TypeInfo = PDecl->getType().getAsOpaquePtr();
Fariborz Jahanianb107ce82007-12-04 19:20:11 +00001082 ActOnParamDeclarator(PI, FnBodyScope);
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001083 }
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001084}
Reid Spencer5f016e22007-07-11 17:01:13 +00001085
1086/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1087/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001088ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1089 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001090 if (getLangOptions().C99) // Extension in C99.
1091 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1092 else // Legal in C90, but warn about it.
1093 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1094
1095 // FIXME: handle stuff like:
1096 // void foo() { extern float X(); }
1097 // void bar() { X(); } <-- implicit decl for X in another scope.
1098
1099 // Set a Declarator for the implicit definition: int foo();
1100 const char *Dummy;
1101 DeclSpec DS;
1102 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1103 Error = Error; // Silence warning.
1104 assert(!Error && "Error setting up implicit decl!");
1105 Declarator D(DS, Declarator::BlockContext);
1106 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1107 D.SetIdentifier(&II, Loc);
1108
1109 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +00001110 if (Scope *FnS = S->getFnParent())
1111 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +00001112 while (S->getParent())
1113 S = S->getParent();
1114
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001115 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +00001116}
1117
1118
Chris Lattner41af0932007-11-14 06:34:38 +00001119TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001120 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001121 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001122 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001123
1124 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +00001125 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
1126 T, LastDeclarator);
1127 if (D.getInvalidType())
1128 NewTD->setInvalidDecl();
1129 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001130}
1131
Steve Naroffe440eb82007-10-10 17:32:04 +00001132Sema::DeclTy *Sema::ActOnStartClassInterface(
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001133 SourceLocation AtInterfaceLoc,
Steve Naroff3536b442007-09-06 21:24:23 +00001134 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1135 IdentifierInfo *SuperName, SourceLocation SuperLoc,
1136 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
Steve Narofff908a872007-10-30 02:23:23 +00001137 SourceLocation EndProtoLoc, AttributeList *AttrList) {
Steve Naroff3536b442007-09-06 21:24:23 +00001138 assert(ClassName && "Missing class identifier");
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001139
1140 // Check for another declaration kind with the same name.
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +00001141 ScopedDecl *PrevDecl = LookupInterfaceDecl(ClassName);
Fariborz Jahanian05672a02007-10-09 18:03:53 +00001142 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001143 Diag(ClassLoc, diag::err_redefinition_different_kind,
1144 ClassName->getName());
1145 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1146 }
1147
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +00001148 ObjcInterfaceDecl* IDecl = dyn_cast_or_null<ObjcInterfaceDecl>(PrevDecl);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001149 if (IDecl) {
1150 // Class already seen. Is it a forward declaration?
Steve Naroff768f26e2007-10-02 20:26:23 +00001151 if (!IDecl->isForwardDecl())
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +00001152 Diag(AtInterfaceLoc, diag::err_duplicate_class_def, IDecl->getName());
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001153 else {
Steve Narofff908a872007-10-30 02:23:23 +00001154 IDecl->setLocation(AtInterfaceLoc);
Steve Naroff768f26e2007-10-02 20:26:23 +00001155 IDecl->setForwardDecl(false);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001156 IDecl->AllocIntfRefProtocols(NumProtocols);
1157 }
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001158 }
1159 else {
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001160 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, NumProtocols, ClassName);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +00001161
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001162 // Chain & install the interface decl into the identifier.
1163 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
1164 ClassName->setFETokenInfo(IDecl);
Fariborz Jahanianbe127ba2007-10-15 19:16:57 +00001165
1166 // Remember that this needs to be removed when the scope is popped.
1167 TUScope->AddDecl(IDecl);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001168 }
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +00001169
1170 if (SuperName) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001171 ObjcInterfaceDecl* SuperClassEntry = 0;
1172 // Check if a different kind of symbol declared in this scope.
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +00001173 PrevDecl = LookupInterfaceDecl(SuperName);
Fariborz Jahanian05672a02007-10-09 18:03:53 +00001174 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001175 Diag(SuperLoc, diag::err_redefinition_different_kind,
1176 SuperName->getName());
1177 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +00001178 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001179 else {
1180 // Check that super class is previously defined
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +00001181 SuperClassEntry = dyn_cast_or_null<ObjcInterfaceDecl>(PrevDecl);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001182
Steve Naroff768f26e2007-10-02 20:26:23 +00001183 if (!SuperClassEntry || SuperClassEntry->isForwardDecl()) {
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +00001184 Diag(AtInterfaceLoc, diag::err_undef_superclass,
1185 SuperClassEntry ? SuperClassEntry->getName()
1186 : SuperName->getName(),
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001187 ClassName->getName());
1188 }
1189 }
1190 IDecl->setSuperClass(SuperClassEntry);
Steve Narofff908a872007-10-30 02:23:23 +00001191 IDecl->setLocEnd(SuperLoc);
1192 } else { // we have a root class.
1193 IDecl->setLocEnd(ClassLoc);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +00001194 }
1195
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001196 /// Check then save referenced protocols
Steve Narofff908a872007-10-30 02:23:23 +00001197 if (NumProtocols) {
1198 for (unsigned int i = 0; i != NumProtocols; i++) {
1199 ObjcProtocolDecl* RefPDecl = ObjcProtocols[ProtocolNames[i]];
1200 if (!RefPDecl || RefPDecl->isForwardDecl())
1201 Diag(ClassLoc, diag::err_undef_protocolref,
1202 ProtocolNames[i]->getName(),
1203 ClassName->getName());
1204 IDecl->setIntfRefProtocols((int)i, RefPDecl);
1205 }
1206 IDecl->setLocEnd(EndProtoLoc);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001207 }
Steve Naroff3536b442007-09-06 21:24:23 +00001208 return IDecl;
1209}
1210
Fariborz Jahanian243b64b2007-10-11 23:42:27 +00001211/// ActOnCompatiblityAlias - this action is called after complete parsing of
1212/// @compaatibility_alias declaration. It sets up the alias relationships.
1213Sema::DeclTy *Sema::ActOnCompatiblityAlias(
1214 SourceLocation AtCompatibilityAliasLoc,
1215 IdentifierInfo *AliasName, SourceLocation AliasLocation,
1216 IdentifierInfo *ClassName, SourceLocation ClassLocation) {
1217 // Look for previous declaration of alias name
1218 ScopedDecl *ADecl = LookupScopedDecl(AliasName, Decl::IDNS_Ordinary,
1219 AliasLocation, TUScope);
1220 if (ADecl) {
1221 if (isa<ObjcCompatibleAliasDecl>(ADecl)) {
1222 Diag(AliasLocation, diag::warn_previous_alias_decl);
1223 Diag(ADecl->getLocation(), diag::warn_previous_declaration);
1224 }
1225 else {
1226 Diag(AliasLocation, diag::err_conflicting_aliasing_type,
1227 AliasName->getName());
1228 Diag(ADecl->getLocation(), diag::err_previous_declaration);
1229 }
1230 return 0;
1231 }
1232 // Check for class declaration
1233 ScopedDecl *CDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
1234 ClassLocation, TUScope);
1235 if (!CDecl || !isa<ObjcInterfaceDecl>(CDecl)) {
1236 Diag(ClassLocation, diag::warn_undef_interface,
1237 ClassName->getName());
1238 if (CDecl)
1239 Diag(CDecl->getLocation(), diag::warn_previous_declaration);
1240 return 0;
1241 }
1242 // Everything checked out, instantiate a new alias declaration ast
1243 ObjcCompatibleAliasDecl *AliasDecl =
1244 new ObjcCompatibleAliasDecl(AtCompatibilityAliasLoc,
1245 AliasName,
1246 dyn_cast<ObjcInterfaceDecl>(CDecl));
1247
1248 // Chain & install the interface decl into the identifier.
1249 AliasDecl->setNext(AliasName->getFETokenInfo<ScopedDecl>());
1250 AliasName->setFETokenInfo(AliasDecl);
1251 return AliasDecl;
1252}
1253
Steve Naroffe440eb82007-10-10 17:32:04 +00001254Sema::DeclTy *Sema::ActOnStartProtocolInterface(
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001255 SourceLocation AtProtoInterfaceLoc,
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001256 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
Steve Narofff908a872007-10-30 02:23:23 +00001257 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs,
1258 SourceLocation EndProtoLoc) {
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001259 assert(ProtocolName && "Missing protocol identifier");
Fariborz Jahanian05672a02007-10-09 18:03:53 +00001260 ObjcProtocolDecl *PDecl = ObjcProtocols[ProtocolName];
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001261 if (PDecl) {
1262 // Protocol already seen. Better be a forward protocol declaration
Steve Naroff768f26e2007-10-02 20:26:23 +00001263 if (!PDecl->isForwardDecl())
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001264 Diag(ProtocolLoc, diag::err_duplicate_protocol_def,
1265 ProtocolName->getName());
1266 else {
Steve Naroff768f26e2007-10-02 20:26:23 +00001267 PDecl->setForwardDecl(false);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001268 PDecl->AllocReferencedProtocols(NumProtoRefs);
1269 }
1270 }
1271 else {
1272 PDecl = new ObjcProtocolDecl(AtProtoInterfaceLoc, NumProtoRefs,
1273 ProtocolName);
Fariborz Jahanian05672a02007-10-09 18:03:53 +00001274 ObjcProtocols[ProtocolName] = PDecl;
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001275 }
1276
Steve Naroff423cb562007-10-30 13:30:57 +00001277 if (NumProtoRefs) {
1278 /// Check then save referenced protocols
1279 for (unsigned int i = 0; i != NumProtoRefs; i++) {
1280 ObjcProtocolDecl* RefPDecl = ObjcProtocols[ProtoRefNames[i]];
1281 if (!RefPDecl || RefPDecl->isForwardDecl())
1282 Diag(ProtocolLoc, diag::err_undef_protocolref,
1283 ProtoRefNames[i]->getName(),
1284 ProtocolName->getName());
1285 PDecl->setReferencedProtocols((int)i, RefPDecl);
1286 }
1287 PDecl->setLocEnd(EndProtoLoc);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001288 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001289 return PDecl;
1290}
1291
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001292/// FindProtocolDeclaration - This routine looks up protocols and
1293/// issuer error if they are not declared. It returns list of protocol
1294/// declarations in its 'Protocols' argument.
1295void
1296Sema::FindProtocolDeclaration(SourceLocation TypeLoc,
1297 IdentifierInfo **ProtocolId,
1298 unsigned NumProtocols,
1299 llvm::SmallVector<DeclTy *,8> &Protocols) {
Fariborz Jahanian245f92a2007-10-05 21:01:53 +00001300 for (unsigned i = 0; i != NumProtocols; ++i) {
Fariborz Jahanian05672a02007-10-09 18:03:53 +00001301 ObjcProtocolDecl *PDecl = ObjcProtocols[ProtocolId[i]];
Fariborz Jahanian245f92a2007-10-05 21:01:53 +00001302 if (!PDecl)
1303 Diag(TypeLoc, diag::err_undeclared_protocol,
1304 ProtocolId[i]->getName());
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001305 else
1306 Protocols.push_back(PDecl);
Fariborz Jahanian245f92a2007-10-05 21:01:53 +00001307 }
Fariborz Jahanian245f92a2007-10-05 21:01:53 +00001308}
1309
Steve Naroff37e58d12007-10-02 22:39:18 +00001310/// ActOnForwardProtocolDeclaration -
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001311Action::DeclTy *
Steve Naroffe440eb82007-10-10 17:32:04 +00001312Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001313 IdentifierInfo **IdentList, unsigned NumElts) {
Chris Lattnerb97de3e2007-10-06 20:05:59 +00001314 llvm::SmallVector<ObjcProtocolDecl*, 32> Protocols;
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001315
1316 for (unsigned i = 0; i != NumElts; ++i) {
Chris Lattner60c52182007-10-07 07:05:08 +00001317 IdentifierInfo *P = IdentList[i];
Fariborz Jahanian05672a02007-10-09 18:03:53 +00001318 ObjcProtocolDecl *PDecl = ObjcProtocols[P];
Chris Lattner60c52182007-10-07 07:05:08 +00001319 if (!PDecl) { // Not already seen?
1320 // FIXME: Pass in the location of the identifier!
1321 PDecl = new ObjcProtocolDecl(AtProtocolLoc, 0, P, true);
Fariborz Jahanian05672a02007-10-09 18:03:53 +00001322 ObjcProtocols[P] = PDecl;
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001323 }
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001324
Chris Lattnerb97de3e2007-10-06 20:05:59 +00001325 Protocols.push_back(PDecl);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001326 }
Chris Lattnerb97de3e2007-10-06 20:05:59 +00001327 return new ObjcForwardProtocolDecl(AtProtocolLoc,
1328 &Protocols[0], Protocols.size());
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001329}
1330
Steve Naroffe440eb82007-10-10 17:32:04 +00001331Sema::DeclTy *Sema::ActOnStartCategoryInterface(
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001332 SourceLocation AtInterfaceLoc,
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001333 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1334 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
Steve Naroff423cb562007-10-30 13:30:57 +00001335 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs,
1336 SourceLocation EndProtoLoc) {
Chris Lattnerfd5de472007-10-06 22:53:46 +00001337 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanian22d71d62007-10-09 17:05:22 +00001338
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001339 /// Check that class of this category is already completely declared.
Fariborz Jahanian0332b6c2007-10-08 16:07:03 +00001340 if (!IDecl || IDecl->isForwardDecl()) {
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001341 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
Fariborz Jahanian22d71d62007-10-09 17:05:22 +00001342 return 0;
Fariborz Jahanian0332b6c2007-10-08 16:07:03 +00001343 }
Fariborz Jahanian8fe5c2a2007-10-09 18:22:59 +00001344 ObjcCategoryDecl *CDecl = new ObjcCategoryDecl(AtInterfaceLoc, NumProtoRefs,
1345 CategoryName);
1346 CDecl->setClassInterface(IDecl);
1347 /// Check for duplicate interface declaration for this category
1348 ObjcCategoryDecl *CDeclChain;
Steve Naroff3d581382007-10-14 18:27:41 +00001349 for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
Fariborz Jahanian8fe5c2a2007-10-09 18:22:59 +00001350 CDeclChain = CDeclChain->getNextClassCategory()) {
1351 if (CDeclChain->getIdentifier() == CategoryName) {
1352 Diag(CategoryLoc, diag::err_dup_category_def, ClassName->getName(),
1353 CategoryName->getName());
1354 break;
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001355 }
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001356 }
Fariborz Jahanian8fe5c2a2007-10-09 18:22:59 +00001357 if (!CDeclChain)
1358 CDecl->insertNextClassCategory();
1359
Steve Naroff423cb562007-10-30 13:30:57 +00001360 if (NumProtoRefs) {
1361 /// Check then save referenced protocols
1362 for (unsigned int i = 0; i != NumProtoRefs; i++) {
1363 ObjcProtocolDecl* RefPDecl = ObjcProtocols[ProtoRefNames[i]];
1364 if (!RefPDecl || RefPDecl->isForwardDecl()) {
1365 Diag(CategoryLoc, diag::err_undef_protocolref,
1366 ProtoRefNames[i]->getName(),
1367 CategoryName->getName());
1368 }
1369 CDecl->setCatReferencedProtocols((int)i, RefPDecl);
Fariborz Jahanian0332b6c2007-10-08 16:07:03 +00001370 }
Steve Naroff423cb562007-10-30 13:30:57 +00001371 CDecl->setLocEnd(EndProtoLoc);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001372 }
Fariborz Jahanian22d71d62007-10-09 17:05:22 +00001373 return CDecl;
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001374}
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001375
Steve Naroff3a165b02007-10-03 21:00:46 +00001376/// ActOnStartCategoryImplementation - Perform semantic checks on the
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001377/// category implementation declaration and build an ObjcCategoryImplDecl
1378/// object.
Steve Naroffe440eb82007-10-10 17:32:04 +00001379Sema::DeclTy *Sema::ActOnStartCategoryImplementation(
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001380 SourceLocation AtCatImplLoc,
1381 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1382 IdentifierInfo *CatName, SourceLocation CatLoc) {
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001383 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001384 ObjcCategoryImplDecl *CDecl = new ObjcCategoryImplDecl(AtCatImplLoc,
Chris Lattner6a0e89e2007-10-06 23:12:31 +00001385 CatName, IDecl);
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001386 /// Check that class of this category is already completely declared.
Steve Naroff768f26e2007-10-02 20:26:23 +00001387 if (!IDecl || IDecl->isForwardDecl())
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001388 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
Steve Naroff8ee529b2007-10-31 18:42:27 +00001389
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001390 /// TODO: Check that CatName, category name, is not used in another
1391 // implementation.
1392 return CDecl;
1393}
1394
Steve Naroffe440eb82007-10-10 17:32:04 +00001395Sema::DeclTy *Sema::ActOnStartClassImplementation(
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001396 SourceLocation AtClassImplLoc,
1397 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1398 IdentifierInfo *SuperClassname,
1399 SourceLocation SuperClassLoc) {
1400 ObjcInterfaceDecl* IDecl = 0;
1401 // Check for another declaration kind with the same name.
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +00001402 ScopedDecl *PrevDecl = LookupInterfaceDecl(ClassName);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001403 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
1404 Diag(ClassLoc, diag::err_redefinition_different_kind,
1405 ClassName->getName());
1406 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1407 }
1408 else {
1409 // Is there an interface declaration of this class; if not, warn!
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +00001410 IDecl = dyn_cast_or_null<ObjcInterfaceDecl>(PrevDecl);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001411 if (!IDecl)
1412 Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
1413 }
1414
1415 // Check that super class name is valid class name
1416 ObjcInterfaceDecl* SDecl = 0;
1417 if (SuperClassname) {
1418 // Check if a different kind of symbol declared in this scope.
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +00001419 PrevDecl = LookupInterfaceDecl(SuperClassname);
Fariborz Jahanian05672a02007-10-09 18:03:53 +00001420 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001421 Diag(SuperClassLoc, diag::err_redefinition_different_kind,
1422 SuperClassname->getName());
1423 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1424 }
1425 else {
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +00001426 SDecl = dyn_cast_or_null<ObjcInterfaceDecl>(PrevDecl);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001427 if (!SDecl)
1428 Diag(SuperClassLoc, diag::err_undef_superclass,
1429 SuperClassname->getName(), ClassName->getName());
1430 else if (IDecl && IDecl->getSuperClass() != SDecl) {
1431 // This implementation and its interface do not have the same
1432 // super class.
1433 Diag(SuperClassLoc, diag::err_conflicting_super_class,
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +00001434 SDecl->getName());
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001435 Diag(SDecl->getLocation(), diag::err_previous_definition);
1436 }
1437 }
1438 }
1439
Fariborz Jahanian0da1c102007-09-25 21:00:20 +00001440 if (!IDecl) {
1441 // Legacy case of @implementation with no corresponding @interface.
1442 // Build, chain & install the interface decl into the identifier.
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001443 IDecl = new ObjcInterfaceDecl(AtClassImplLoc, 0, ClassName,
1444 false, true);
Fariborz Jahanian0da1c102007-09-25 21:00:20 +00001445 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
1446 ClassName->setFETokenInfo(IDecl);
Fariborz Jahanian7780d2d2007-10-26 20:50:24 +00001447 IDecl->setSuperClass(SDecl);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001448 IDecl->setLocEnd(ClassLoc);
Fariborz Jahanian0da1c102007-09-25 21:00:20 +00001449
Fariborz Jahanianbe127ba2007-10-15 19:16:57 +00001450 // Remember that this needs to be removed when the scope is popped.
1451 TUScope->AddDecl(IDecl);
Fariborz Jahanian0da1c102007-09-25 21:00:20 +00001452 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001453
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001454 ObjcImplementationDecl* IMPDecl =
1455 new ObjcImplementationDecl(AtClassImplLoc, ClassName, IDecl, SDecl);
1456
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001457 // Check that there is no duplicate implementation of this class.
Steve Naroffc43d8682007-11-11 00:10:47 +00001458 if (ObjcImplementations[ClassName])
Chris Lattnerf3876682007-10-07 01:13:46 +00001459 Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
Steve Naroffc43d8682007-11-11 00:10:47 +00001460 else // add it to the list.
1461 ObjcImplementations[ClassName] = IMPDecl;
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001462 return IMPDecl;
1463}
1464
Steve Naroffa5997c42007-10-02 21:43:37 +00001465void Sema::CheckImplementationIvars(ObjcImplementationDecl *ImpDecl,
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001466 ObjcIvarDecl **ivars, unsigned numIvars,
1467 SourceLocation RBrace) {
Steve Naroffa5997c42007-10-02 21:43:37 +00001468 assert(ImpDecl && "missing implementation decl");
1469 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ImpDecl->getIdentifier());
Fariborz Jahanian7780d2d2007-10-26 20:50:24 +00001470 if (!IDecl)
Steve Naroffa5997c42007-10-02 21:43:37 +00001471 return;
Fariborz Jahanian7780d2d2007-10-26 20:50:24 +00001472 /// Check case of non-existing @interface decl.
1473 /// (legacy objective-c @implementation decl without an @interface decl).
1474 /// Add implementations's ivar to the synthesize class's ivar list.
1475 if (IDecl->ImplicitInterfaceDecl()) {
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001476 IDecl->addInstanceVariablesToClass(ivars, numIvars, RBrace);
Fariborz Jahanian7780d2d2007-10-26 20:50:24 +00001477 return;
1478 }
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +00001479 // If implementation has empty ivar list, just return.
1480 if (numIvars == 0)
1481 return;
Fariborz Jahanian7780d2d2007-10-26 20:50:24 +00001482
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001483 assert(ivars && "missing @implementation ivars");
1484
Steve Naroffa5997c42007-10-02 21:43:37 +00001485 // Check interface's Ivar list against those in the implementation.
1486 // names and types must match.
1487 //
Steve Naroff03300712007-11-12 13:56:41 +00001488 ObjcIvarDecl** IntfIvars = IDecl->getInstanceVariables();
1489 int IntfNumIvars = IDecl->getNumInstanceVariables();
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001490 unsigned j = 0;
1491 bool err = false;
1492 while (numIvars > 0 && IntfNumIvars > 0) {
1493 ObjcIvarDecl* ImplIvar = ivars[j];
1494 ObjcIvarDecl* ClsIvar = IntfIvars[j++];
1495 assert (ImplIvar && "missing implementation ivar");
1496 assert (ClsIvar && "missing class ivar");
1497 if (ImplIvar->getCanonicalType() != ClsIvar->getCanonicalType()) {
1498 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
1499 ImplIvar->getIdentifier()->getName());
1500 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1501 ClsIvar->getIdentifier()->getName());
1502 }
1503 // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
1504 // as error.
1505 else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1506 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
1507 ImplIvar->getIdentifier()->getName());
1508 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1509 ClsIvar->getIdentifier()->getName());
1510 err = true;
1511 break;
1512 }
1513 --numIvars;
1514 --IntfNumIvars;
1515 }
1516 if (!err && (numIvars > 0 || IntfNumIvars > 0))
1517 Diag(numIvars > 0 ? ivars[j]->getLocation() : IntfIvars[j]->getLocation(),
1518 diag::err_inconsistant_ivar);
1519
1520}
1521
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001522/// CheckProtocolMethodDefs - This routine checks unimpletented methods
1523/// Declared in protocol, and those referenced by it.
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001524void Sema::CheckProtocolMethodDefs(ObjcProtocolDecl *PDecl,
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001525 bool& IncompleteImpl,
Steve Naroffeefc4182007-10-08 21:05:34 +00001526 const llvm::DenseSet<Selector> &InsMap,
Chris Lattner85994262007-10-05 20:15:24 +00001527 const llvm::DenseSet<Selector> &ClsMap) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001528 // check unimplemented instance methods.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001529 ObjcMethodDecl** methods = PDecl->getInstanceMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001530 for (int j = 0; j < PDecl->getNumInstanceMethods(); j++) {
Steve Naroffeefc4182007-10-08 21:05:34 +00001531 if (!InsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001532 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001533 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001534 IncompleteImpl = true;
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001535 }
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001536 }
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001537 // check unimplemented class methods
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001538 methods = PDecl->getClassMethods();
1539 for (int j = 0; j < PDecl->getNumClassMethods(); j++)
Chris Lattner85994262007-10-05 20:15:24 +00001540 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001541 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001542 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001543 IncompleteImpl = true;
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001544 }
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001545
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001546 // Check on this protocols's referenced protocols, recursively
1547 ObjcProtocolDecl** RefPDecl = PDecl->getReferencedProtocols();
1548 for (int i = 0; i < PDecl->getNumReferencedProtocols(); i++)
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001549 CheckProtocolMethodDefs(RefPDecl[i], IncompleteImpl, InsMap, ClsMap);
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001550}
1551
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001552void Sema::ImplMethodsVsClassMethods(ObjcImplementationDecl* IMPDecl,
1553 ObjcInterfaceDecl* IDecl) {
Steve Naroffeefc4182007-10-08 21:05:34 +00001554 llvm::DenseSet<Selector> InsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001555 // Check and see if instance methods in class interface have been
1556 // implemented in the implementation class.
Steve Naroff0416fb92007-11-11 17:19:15 +00001557 ObjcMethodDecl *const*methods = IMPDecl->getInstanceMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001558 for (int i=0; i < IMPDecl->getNumInstanceMethods(); i++)
Steve Naroffeefc4182007-10-08 21:05:34 +00001559 InsMap.insert(methods[i]->getSelector());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001560
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001561 bool IncompleteImpl = false;
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001562 methods = IDecl->getInstanceMethods();
1563 for (int j = 0; j < IDecl->getNumInstanceMethods(); j++)
Steve Naroffeefc4182007-10-08 21:05:34 +00001564 if (!InsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001565 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001566 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001567 IncompleteImpl = true;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001568 }
Chris Lattner85994262007-10-05 20:15:24 +00001569 llvm::DenseSet<Selector> ClsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001570 // Check and see if class methods in class interface have been
1571 // implemented in the implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001572 methods = IMPDecl->getClassMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001573 for (int i=0; i < IMPDecl->getNumClassMethods(); i++)
Chris Lattner85994262007-10-05 20:15:24 +00001574 ClsMap.insert(methods[i]->getSelector());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001575
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001576 methods = IDecl->getClassMethods();
1577 for (int j = 0; j < IDecl->getNumClassMethods(); j++)
Chris Lattner85994262007-10-05 20:15:24 +00001578 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001579 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001580 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001581 IncompleteImpl = true;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001582 }
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001583
1584 // Check the protocol list for unimplemented methods in the @implementation
1585 // class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001586 ObjcProtocolDecl** protocols = IDecl->getReferencedProtocols();
Chris Lattner85994262007-10-05 20:15:24 +00001587 for (int i = 0; i < IDecl->getNumIntfRefProtocols(); i++)
1588 CheckProtocolMethodDefs(protocols[i], IncompleteImpl, InsMap, ClsMap);
1589
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001590 if (IncompleteImpl)
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001591 Diag(IMPDecl->getLocation(), diag::warn_incomplete_impl_class,
1592 IMPDecl->getName());
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001593}
1594
1595/// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
1596/// category interface is implemented in the category @implementation.
1597void Sema::ImplCategoryMethodsVsIntfMethods(ObjcCategoryImplDecl *CatImplDecl,
1598 ObjcCategoryDecl *CatClassDecl) {
Steve Naroffeefc4182007-10-08 21:05:34 +00001599 llvm::DenseSet<Selector> InsMap;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001600 // Check and see if instance methods in category interface have been
1601 // implemented in its implementation class.
Steve Naroffe1e6c0d2007-11-12 22:05:31 +00001602 ObjcMethodDecl *const*methods = CatImplDecl->getInstanceMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001603 for (int i=0; i < CatImplDecl->getNumInstanceMethods(); i++)
Steve Naroffeefc4182007-10-08 21:05:34 +00001604 InsMap.insert(methods[i]->getSelector());
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001605
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001606 bool IncompleteImpl = false;
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001607 methods = CatClassDecl->getInstanceMethods();
1608 for (int j = 0; j < CatClassDecl->getNumInstanceMethods(); j++)
Steve Naroffeefc4182007-10-08 21:05:34 +00001609 if (!InsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001610 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001611 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001612 IncompleteImpl = true;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001613 }
Chris Lattner85994262007-10-05 20:15:24 +00001614 llvm::DenseSet<Selector> ClsMap;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001615 // Check and see if class methods in category interface have been
1616 // implemented in its implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001617 methods = CatImplDecl->getClassMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001618 for (int i=0; i < CatImplDecl->getNumClassMethods(); i++)
Chris Lattner85994262007-10-05 20:15:24 +00001619 ClsMap.insert(methods[i]->getSelector());
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001620
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001621 methods = CatClassDecl->getClassMethods();
1622 for (int j = 0; j < CatClassDecl->getNumClassMethods(); j++)
Chris Lattner85994262007-10-05 20:15:24 +00001623 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001624 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001625 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001626 IncompleteImpl = true;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001627 }
1628
1629 // Check the protocol list for unimplemented methods in the @implementation
1630 // class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001631 ObjcProtocolDecl** protocols = CatClassDecl->getReferencedProtocols();
1632 for (int i = 0; i < CatClassDecl->getNumReferencedProtocols(); i++) {
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001633 ObjcProtocolDecl* PDecl = protocols[i];
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001634 CheckProtocolMethodDefs(PDecl, IncompleteImpl, InsMap, ClsMap);
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001635 }
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001636 if (IncompleteImpl)
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001637 Diag(CatImplDecl->getLocation(), diag::warn_incomplete_impl_category,
Chris Lattnerfd5de472007-10-06 22:53:46 +00001638 CatClassDecl->getName());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001639}
1640
Steve Naroff37e58d12007-10-02 22:39:18 +00001641/// ActOnForwardClassDeclaration -
Steve Naroff3536b442007-09-06 21:24:23 +00001642Action::DeclTy *
Steve Naroffe440eb82007-10-10 17:32:04 +00001643Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
Steve Naroff37e58d12007-10-02 22:39:18 +00001644 IdentifierInfo **IdentList, unsigned NumElts)
1645{
Chris Lattner7e620722007-10-06 20:08:36 +00001646 llvm::SmallVector<ObjcInterfaceDecl*, 32> Interfaces;
1647
Steve Naroff3536b442007-09-06 21:24:23 +00001648 for (unsigned i = 0; i != NumElts; ++i) {
Fariborz Jahanianbe127ba2007-10-15 19:16:57 +00001649 // Check for another declaration kind with the same name.
1650 ScopedDecl *PrevDecl = LookupInterfaceDecl(IdentList[i]);
1651 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
1652 Diag(AtClassLoc, diag::err_redefinition_different_kind,
1653 IdentList[i]->getName());
1654 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1655 }
1656 ObjcInterfaceDecl *IDecl = dyn_cast_or_null<ObjcInterfaceDecl>(PrevDecl);
Chris Lattner7e620722007-10-06 20:08:36 +00001657 if (!IDecl) { // Not already seen? Make a forward decl.
Fariborz Jahanianbe127ba2007-10-15 19:16:57 +00001658 IDecl = new ObjcInterfaceDecl(AtClassLoc, 0, IdentList[i], true);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001659 // Chain & install the interface decl into the identifier.
1660 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1661 IdentList[i]->setFETokenInfo(IDecl);
Chris Lattner60c52182007-10-07 07:05:08 +00001662
1663 // Remember that this needs to be removed when the scope is popped.
Steve Naroffe440eb82007-10-10 17:32:04 +00001664 TUScope->AddDecl(IDecl);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001665 }
Chris Lattner7e620722007-10-06 20:08:36 +00001666
1667 Interfaces.push_back(IDecl);
Steve Naroff3536b442007-09-06 21:24:23 +00001668 }
Chris Lattner7e620722007-10-06 20:08:36 +00001669
1670 return new ObjcClassDecl(AtClassLoc, &Interfaces[0], Interfaces.size());
Steve Naroff3536b442007-09-06 21:24:23 +00001671}
1672
Reid Spencer5f016e22007-07-11 17:01:13 +00001673
Steve Naroff08d92e42007-09-15 18:49:24 +00001674/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001675/// former case, Name will be non-null. In the later case, Name will be null.
1676/// TagType indicates what kind of tag this is. TK indicates whether this is a
1677/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001678Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001679 SourceLocation KWLoc, IdentifierInfo *Name,
1680 SourceLocation NameLoc, AttributeList *Attr) {
1681 // If this is a use of an existing tag, it must have a name.
1682 assert((Name != 0 || TK == TK_Definition) &&
1683 "Nameless record must be a definition!");
1684
1685 Decl::Kind Kind;
1686 switch (TagType) {
1687 default: assert(0 && "Unknown tag type!");
1688 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1689 case DeclSpec::TST_union: Kind = Decl::Union; break;
1690//case DeclSpec::TST_class: Kind = Decl::Class; break;
1691 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1692 }
1693
1694 // If this is a named struct, check to see if there was a previous forward
1695 // declaration or definition.
1696 if (TagDecl *PrevDecl =
1697 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1698 NameLoc, S))) {
1699
1700 // If this is a use of a previous tag, or if the tag is already declared in
1701 // the same scope (so that the definition/declaration completes or
1702 // rementions the tag), reuse the decl.
1703 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1704 // Make sure that this wasn't declared as an enum and now used as a struct
1705 // or something similar.
1706 if (PrevDecl->getKind() != Kind) {
1707 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1708 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1709 }
1710
1711 // If this is a use or a forward declaration, we're good.
1712 if (TK != TK_Definition)
1713 return PrevDecl;
1714
1715 // Diagnose attempts to redefine a tag.
1716 if (PrevDecl->isDefinition()) {
1717 Diag(NameLoc, diag::err_redefinition, Name->getName());
1718 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1719 // If this is a redefinition, recover by making this struct be
1720 // anonymous, which will make any later references get the previous
1721 // definition.
1722 Name = 0;
1723 } else {
1724 // Okay, this is definition of a previously declared or referenced tag.
1725 // Move the location of the decl to be the definition site.
1726 PrevDecl->setLocation(NameLoc);
1727 return PrevDecl;
1728 }
1729 }
1730 // If we get here, this is a definition of a new struct type in a nested
1731 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1732 // type.
1733 }
1734
1735 // If there is an identifier, use the location of the identifier as the
1736 // location of the decl, otherwise use the location of the struct/union
1737 // keyword.
1738 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1739
1740 // Otherwise, if this is the first time we've seen this tag, create the decl.
1741 TagDecl *New;
1742 switch (Kind) {
1743 default: assert(0 && "Unknown tag kind!");
1744 case Decl::Enum:
1745 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1746 // enum X { A, B, C } D; D should chain to X.
1747 New = new EnumDecl(Loc, Name, 0);
1748 // If this is an undefined enum, warn.
1749 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1750 break;
1751 case Decl::Union:
1752 case Decl::Struct:
1753 case Decl::Class:
1754 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1755 // struct X { int A; } D; D should chain to X.
1756 New = new RecordDecl(Kind, Loc, Name, 0);
1757 break;
1758 }
1759
1760 // If this has an identifier, add it to the scope stack.
1761 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001762 // The scope passed in may not be a decl scope. Zip up the scope tree until
1763 // we find one that is.
1764 while ((S->getFlags() & Scope::DeclScope) == 0)
1765 S = S->getParent();
1766
1767 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001768 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 Name->setFETokenInfo(New);
1770 S->AddDecl(New);
1771 }
Steve Naroff1f644322007-11-28 22:54:11 +00001772
Reid Spencer5f016e22007-07-11 17:01:13 +00001773 return New;
1774}
1775
Steve Naroff08d92e42007-09-15 18:49:24 +00001776/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001777/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001778Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 SourceLocation DeclStart,
1780 Declarator &D, ExprTy *BitfieldWidth) {
1781 IdentifierInfo *II = D.getIdentifier();
1782 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001783 SourceLocation Loc = DeclStart;
1784 if (II) Loc = D.getIdentifierLoc();
1785
1786 // FIXME: Unnamed fields can be handled in various different ways, for
1787 // example, unnamed unions inject all members into the struct namespace!
1788
1789
1790 if (BitWidth) {
1791 // TODO: Validate.
1792 //printf("WARNING: BITFIELDS IGNORED!\n");
1793
1794 // 6.7.2.1p3
1795 // 6.7.2.1p4
1796
1797 } else {
1798 // Not a bitfield.
1799
1800 // validate II.
1801
1802 }
1803
1804 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001805 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1806 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001807
Reid Spencer5f016e22007-07-11 17:01:13 +00001808 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1809 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001810 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1811 Diag(Loc, diag::err_typecheck_illegal_vla,
1812 VAT->getSizeExpr()->getSourceRange());
1813 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001814 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001815 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001816 FieldDecl *NewFD;
1817
1818 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patel54e62352007-11-01 16:29:56 +00001819 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Steve Naroffeaf5f412007-11-12 04:22:52 +00001820 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1821 isa<ObjcImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroffddd600f2007-11-14 14:15:31 +00001822 isa<ObjcCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
1823 // FIXME: ivars are currently used to model properties, and
1824 // properties can appear within a protocol.
1825 // See corresponding FIXME in DeclObjC.h:ObjcPropertyDecl.
1826 isa<ObjcProtocolDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001827 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001828 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001829 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001830
Steve Naroff5912a352007-08-28 20:14:24 +00001831 if (D.getInvalidType() || InvalidDecl)
1832 NewFD->setInvalidDecl();
1833 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001834}
1835
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001836/// TranslateIvarVisibility - Translate visibility from a token ID to an
1837/// AST enum value.
1838static ObjcIvarDecl::AccessControl
1839TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001840 switch (ivarVisibility) {
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001841 case tok::objc_private: return ObjcIvarDecl::Private;
1842 case tok::objc_public: return ObjcIvarDecl::Public;
1843 case tok::objc_protected: return ObjcIvarDecl::Protected;
1844 case tok::objc_package: return ObjcIvarDecl::Package;
1845 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001846 }
1847}
1848
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001849void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001850 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001851 DeclTy **Fields, unsigned NumFields,
Steve Naroff60fccee2007-10-29 21:38:07 +00001852 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff08d92e42007-09-15 18:49:24 +00001853 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001854 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1855 assert(EnclosingDecl && "missing record or interface decl");
1856 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1857
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001858 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001859 // Diagnose code like:
1860 // struct S { struct S {} X; };
1861 // We discover this when we complete the outer S. Reject and ignore the
1862 // outer S.
1863 Diag(Record->getLocation(), diag::err_nested_redefinition,
1864 Record->getKindName());
1865 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001866 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001867 return;
1868 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001869 // Verify that all the fields are okay.
1870 unsigned NumNamedMembers = 0;
1871 llvm::SmallVector<FieldDecl*, 32> RecFields;
1872 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001873
Reid Spencer5f016e22007-07-11 17:01:13 +00001874 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001875
Steve Naroff74216642007-09-14 22:20:54 +00001876 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1877 assert(FD && "missing field decl");
1878
1879 // Remember all fields.
1880 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001881
1882 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001883 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001884
Steve Narofff13271f2007-09-14 23:09:53 +00001885 // If we have visibility info, make sure the AST is set accordingly.
1886 if (visibility)
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001887 cast<ObjcIvarDecl>(FD)->setAccessControl(
1888 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001889
Reid Spencer5f016e22007-07-11 17:01:13 +00001890 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001891 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001892 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001893 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001894 FD->setInvalidDecl();
1895 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001896 continue;
1897 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001898 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1899 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001900 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001901 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001902 FD->setInvalidDecl();
1903 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001904 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001905 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001906 if (i != NumFields-1 || // ... that the last member ...
1907 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001908 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001909 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001910 FD->setInvalidDecl();
1911 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001912 continue;
1913 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001914 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001915 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1916 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001917 FD->setInvalidDecl();
1918 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001919 continue;
1920 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001921 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001922 if (Record)
1923 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001924 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001925 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1926 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001927 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001928 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1929 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001930 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001931 Record->setHasFlexibleArrayMember(true);
1932 } else {
1933 // If this is a struct/class and this is not the last element, reject
1934 // it. Note that GCC supports variable sized arrays in the middle of
1935 // structures.
1936 if (i != NumFields-1) {
1937 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1938 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001939 FD->setInvalidDecl();
1940 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 continue;
1942 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001943 // We support flexible arrays at the end of structs in other structs
1944 // as an extension.
1945 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1946 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001947 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001948 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001949 }
1950 }
1951 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001952 /// A field cannot be an Objective-c object
1953 if (FDTy->isObjcInterfaceType()) {
1954 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1955 FD->getName());
1956 FD->setInvalidDecl();
1957 EnclosingDecl->setInvalidDecl();
1958 continue;
1959 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001960 // Keep track of the number of named members.
1961 if (IdentifierInfo *II = FD->getIdentifier()) {
1962 // Detect duplicate member names.
1963 if (!FieldIDs.insert(II)) {
1964 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1965 // Find the previous decl.
1966 SourceLocation PrevLoc;
1967 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1968 assert(i != e && "Didn't find previous def!");
1969 if (RecFields[i]->getIdentifier() == II) {
1970 PrevLoc = RecFields[i]->getLocation();
1971 break;
1972 }
1973 }
1974 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001975 FD->setInvalidDecl();
1976 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001977 continue;
1978 }
1979 ++NumNamedMembers;
1980 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001981 }
1982
Reid Spencer5f016e22007-07-11 17:01:13 +00001983 // Okay, we successfully defined 'Record'.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001984 if (Record)
1985 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001986 else {
1987 ObjcIvarDecl **ClsFields =
1988 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001989 if (isa<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1990 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
Steve Naroff60fccee2007-10-29 21:38:07 +00001991 addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001992 else if (isa<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1993 ObjcImplementationDecl* IMPDecl =
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001994 cast<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl));
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001995 assert(IMPDecl && "ActOnFields - missing ObjcImplementationDecl");
1996 IMPDecl->ObjcAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001997 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001998 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001999 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002000}
2001
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00002002/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
2003/// returns true, or false, accordingly.
2004/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
2005bool Sema:: MatchTwoMethodDeclarations(const ObjcMethodDecl *Method,
2006 const ObjcMethodDecl *PrevMethod) {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002007 if (Method->getResultType().getCanonicalType() !=
2008 PrevMethod->getResultType().getCanonicalType())
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00002009 return false;
2010 for (int i = 0; i < Method->getNumParams(); i++) {
2011 ParmVarDecl *ParamDecl = Method->getParamDecl(i);
2012 ParmVarDecl *PrevParamDecl = PrevMethod->getParamDecl(i);
2013 if (ParamDecl->getCanonicalType() != PrevParamDecl->getCanonicalType())
2014 return false;
2015 }
2016 return true;
2017}
2018
Steve Naroff58ff9e82007-10-14 00:58:41 +00002019void Sema::AddInstanceMethodToGlobalPool(ObjcMethodDecl *Method) {
2020 ObjcMethodList &FirstMethod = InstanceMethodPool[Method->getSelector()];
2021 if (!FirstMethod.Method) {
2022 // Haven't seen a method with this selector name yet - add it.
2023 FirstMethod.Method = Method;
2024 FirstMethod.Next = 0;
2025 } else {
2026 // We've seen a method with this name, now check the type signature(s).
2027 bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
2028
2029 for (ObjcMethodList *Next = FirstMethod.Next; !match && Next;
2030 Next = Next->Next)
2031 match = MatchTwoMethodDeclarations(Method, Next->Method);
2032
2033 if (!match) {
2034 // We have a new signature for an existing method - add it.
2035 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
2036 struct ObjcMethodList *OMI = new ObjcMethodList(Method, FirstMethod.Next);
2037 FirstMethod.Next = OMI;
2038 }
2039 }
2040}
2041
2042void Sema::AddFactoryMethodToGlobalPool(ObjcMethodDecl *Method) {
2043 ObjcMethodList &FirstMethod = FactoryMethodPool[Method->getSelector()];
2044 if (!FirstMethod.Method) {
2045 // Haven't seen a method with this selector name yet - add it.
2046 FirstMethod.Method = Method;
2047 FirstMethod.Next = 0;
2048 } else {
2049 // We've seen a method with this name, now check the type signature(s).
2050 bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
2051
2052 for (ObjcMethodList *Next = FirstMethod.Next; !match && Next;
2053 Next = Next->Next)
2054 match = MatchTwoMethodDeclarations(Method, Next->Method);
2055
2056 if (!match) {
2057 // We have a new signature for an existing method - add it.
2058 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
2059 struct ObjcMethodList *OMI = new ObjcMethodList(Method, FirstMethod.Next);
2060 FirstMethod.Next = OMI;
2061 }
2062 }
2063}
2064
Steve Naroff0416fb92007-11-11 17:19:15 +00002065void Sema::ActOnAtEnd(SourceLocation AtEndLoc, DeclTy *classDecl,
2066 DeclTy **allMethods, unsigned allNum,
2067 DeclTy **allProperties, unsigned pNum) {
Chris Lattnerfd5de472007-10-06 22:53:46 +00002068 Decl *ClassDecl = static_cast<Decl *>(classDecl);
Steve Naroff8f744762007-10-12 18:49:25 +00002069
2070 // FIXME: If we don't have a ClassDecl, we have an error. I (snaroff) would
2071 // prefer we always pass in a decl. If the decl has an error, isInvalidDecl()
2072 // should be true.
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00002073 if (!ClassDecl)
2074 return;
Steve Naroff2feac5e2007-10-30 03:43:13 +00002075
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00002076 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
2077 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00002078
Steve Naroffeefc4182007-10-08 21:05:34 +00002079 llvm::DenseMap<Selector, const ObjcMethodDecl*> InsMap;
2080 llvm::DenseMap<Selector, const ObjcMethodDecl*> ClsMap;
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00002081
Fariborz Jahanian82a5fe32007-11-06 22:01:00 +00002082 bool isInterfaceDeclKind =
Fariborz Jahanian1109b422007-10-12 23:43:31 +00002083 (isa<ObjcInterfaceDecl>(ClassDecl) || isa<ObjcCategoryDecl>(ClassDecl)
2084 || isa<ObjcProtocolDecl>(ClassDecl));
Fariborz Jahanian3e7fd152007-10-16 21:52:23 +00002085 bool checkIdenticalMethods = isa<ObjcImplementationDecl>(ClassDecl);
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00002086
Fariborz Jahanian82a5fe32007-11-06 22:01:00 +00002087 // TODO: property declaration in category and protocols.
2088 if (pNum != 0 && isa<ObjcInterfaceDecl>(ClassDecl)) {
2089 ObjcPropertyDecl **properties = new ObjcPropertyDecl*[pNum];
2090 memcpy(properties, allProperties, pNum*sizeof(ObjcPropertyDecl*));
2091 dyn_cast<ObjcInterfaceDecl>(ClassDecl)->setPropertyDecls(properties);
2092 dyn_cast<ObjcInterfaceDecl>(ClassDecl)->setNumPropertyDecl(pNum);
2093 }
2094
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00002095 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00002096 ObjcMethodDecl *Method =
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00002097 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
Steve Naroff58ff9e82007-10-14 00:58:41 +00002098
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00002099 if (!Method) continue; // Already issued a diagnostic.
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00002100 if (Method->isInstance()) {
Fariborz Jahanian3e7fd152007-10-16 21:52:23 +00002101 /// Check for instance method of the same name with incompatible types
2102 const ObjcMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
2103 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2104 : false;
Fariborz Jahanian82a5fe32007-11-06 22:01:00 +00002105 if (isInterfaceDeclKind && PrevMethod && !match
Fariborz Jahanian3e7fd152007-10-16 21:52:23 +00002106 || checkIdenticalMethods && match) {
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00002107 Diag(Method->getLocation(), diag::error_duplicate_method_decl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00002108 Method->getSelector().getName());
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00002109 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
Fariborz Jahanian3e7fd152007-10-16 21:52:23 +00002110 } else {
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00002111 insMethods.push_back(Method);
Fariborz Jahanian3e7fd152007-10-16 21:52:23 +00002112 InsMap[Method->getSelector()] = Method;
2113 /// The following allows us to typecheck messages to "id".
2114 AddInstanceMethodToGlobalPool(Method);
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00002115 }
Fariborz Jahanian3e7fd152007-10-16 21:52:23 +00002116 }
2117 else {
2118 /// Check for class method of the same name with incompatible types
2119 const ObjcMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
2120 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2121 : false;
Fariborz Jahanian82a5fe32007-11-06 22:01:00 +00002122 if (isInterfaceDeclKind && PrevMethod && !match
Fariborz Jahanian3e7fd152007-10-16 21:52:23 +00002123 || checkIdenticalMethods && match) {
2124 Diag(Method->getLocation(), diag::error_duplicate_method_decl,
2125 Method->getSelector().getName());
2126 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
2127 } else {
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00002128 clsMethods.push_back(Method);
Fariborz Jahanian3e7fd152007-10-16 21:52:23 +00002129 ClsMap[Method->getSelector()] = Method;
2130 /// The following allows us to typecheck messages to "id".
2131 AddInstanceMethodToGlobalPool(Method);
2132 }
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00002133 }
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00002134 }
Chris Lattnerfd5de472007-10-06 22:53:46 +00002135
2136 if (ObjcInterfaceDecl *I = dyn_cast<ObjcInterfaceDecl>(ClassDecl)) {
Steve Naroff60fccee2007-10-29 21:38:07 +00002137 I->addMethods(&insMethods[0], insMethods.size(),
2138 &clsMethods[0], clsMethods.size(), AtEndLoc);
Chris Lattnerfd5de472007-10-06 22:53:46 +00002139 } else if (ObjcProtocolDecl *P = dyn_cast<ObjcProtocolDecl>(ClassDecl)) {
Steve Naroff60fccee2007-10-29 21:38:07 +00002140 P->addMethods(&insMethods[0], insMethods.size(),
2141 &clsMethods[0], clsMethods.size(), AtEndLoc);
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00002142 }
Chris Lattnerfd5de472007-10-06 22:53:46 +00002143 else if (ObjcCategoryDecl *C = dyn_cast<ObjcCategoryDecl>(ClassDecl)) {
Steve Naroff60fccee2007-10-29 21:38:07 +00002144 C->addMethods(&insMethods[0], insMethods.size(),
2145 &clsMethods[0], clsMethods.size(), AtEndLoc);
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00002146 }
Chris Lattnerfd5de472007-10-06 22:53:46 +00002147 else if (ObjcImplementationDecl *IC =
2148 dyn_cast<ObjcImplementationDecl>(ClassDecl)) {
Steve Naroff0416fb92007-11-11 17:19:15 +00002149 IC->setLocEnd(AtEndLoc);
Chris Lattnerfd5de472007-10-06 22:53:46 +00002150 if (ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(IC->getIdentifier()))
2151 ImplMethodsVsClassMethods(IC, IDecl);
2152 } else {
2153 ObjcCategoryImplDecl* CatImplClass = cast<ObjcCategoryImplDecl>(ClassDecl);
Steve Naroffe1e6c0d2007-11-12 22:05:31 +00002154 CatImplClass->setLocEnd(AtEndLoc);
Chris Lattnerfd5de472007-10-06 22:53:46 +00002155 ObjcInterfaceDecl* IDecl = CatImplClass->getClassInterface();
2156 // Find category interface decl and then check that all methods declared
2157 // in this interface is implemented in the category @implementation.
2158 if (IDecl) {
Steve Naroff3d581382007-10-14 18:27:41 +00002159 for (ObjcCategoryDecl *Categories = IDecl->getCategoryList();
Chris Lattnerfd5de472007-10-06 22:53:46 +00002160 Categories; Categories = Categories->getNextClassCategory()) {
Chris Lattner6a0e89e2007-10-06 23:12:31 +00002161 if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
Chris Lattnerfd5de472007-10-06 22:53:46 +00002162 ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
2163 break;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00002164 }
2165 }
2166 }
2167 }
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00002168}
2169
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002170/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
2171/// objective-c's type qualifier from the parser version of the same info.
2172static Decl::ObjcDeclQualifier
2173CvtQTToAstBitMask(ObjcDeclSpec::ObjcDeclQualifier PQTVal) {
2174 Decl::ObjcDeclQualifier ret = Decl::OBJC_TQ_None;
2175 if (PQTVal & ObjcDeclSpec::DQ_In)
2176 ret = (Decl::ObjcDeclQualifier)(ret | Decl::OBJC_TQ_In);
2177 if (PQTVal & ObjcDeclSpec::DQ_Inout)
2178 ret = (Decl::ObjcDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
2179 if (PQTVal & ObjcDeclSpec::DQ_Out)
2180 ret = (Decl::ObjcDeclQualifier)(ret | Decl::OBJC_TQ_Out);
2181 if (PQTVal & ObjcDeclSpec::DQ_Bycopy)
2182 ret = (Decl::ObjcDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
2183 if (PQTVal & ObjcDeclSpec::DQ_Byref)
2184 ret = (Decl::ObjcDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
2185 if (PQTVal & ObjcDeclSpec::DQ_Oneway)
2186 ret = (Decl::ObjcDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
2187
2188 return ret;
2189}
2190
Steve Naroffbef11852007-10-26 20:53:56 +00002191Sema::DeclTy *Sema::ActOnMethodDeclaration(
2192 SourceLocation MethodLoc, SourceLocation EndLoc,
Fariborz Jahanian1f7b6f82007-11-09 19:52:12 +00002193 tok::TokenKind MethodType, DeclTy *ClassDecl,
2194 ObjcDeclSpec &ReturnQT, TypeTy *ReturnType,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +00002195 Selector Sel,
Steve Naroff68d331a2007-09-27 14:38:14 +00002196 // optional arguments. The number of types/arguments is obtained
2197 // from the Sel.getNumArgs().
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +00002198 ObjcDeclSpec *ArgQT, TypeTy **ArgTypes, IdentifierInfo **ArgNames,
Steve Naroff335eafa2007-11-15 12:35:21 +00002199 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
2200 bool isVariadic) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00002201 llvm::SmallVector<ParmVarDecl*, 16> Params;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002202
Steve Naroffbcfb06a2007-09-28 22:22:11 +00002203 for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00002204 // FIXME: arg->AttrList must be stored too!
Steve Naroff3b950172007-10-10 21:53:07 +00002205 QualType argType;
2206
2207 if (ArgTypes[i])
2208 argType = QualType::getFromOpaquePtr(ArgTypes[i]);
2209 else
Steve Naroff8ee529b2007-10-31 18:42:27 +00002210 argType = Context.getObjcIdType();
Steve Naroff68d331a2007-09-27 14:38:14 +00002211 ParmVarDecl* Param = new ParmVarDecl(SourceLocation(/*FIXME*/), ArgNames[i],
Steve Naroff3b950172007-10-10 21:53:07 +00002212 argType, VarDecl::None, 0);
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002213 Param->setObjcDeclQualifier(
2214 CvtQTToAstBitMask(ArgQT[i].getObjcDeclQualifier()));
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00002215 Params.push_back(Param);
2216 }
Steve Naroffb216c882007-10-09 22:01:59 +00002217 QualType resultDeclType;
2218
2219 if (ReturnType)
2220 resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Steve Naroff3b950172007-10-10 21:53:07 +00002221 else // get the type for "id".
Steve Naroff8ee529b2007-10-31 18:42:27 +00002222 resultDeclType = Context.getObjcIdType();
Fariborz Jahanian1f7b6f82007-11-09 19:52:12 +00002223
2224 Decl *CDecl = static_cast<Decl*>(ClassDecl);
Steve Naroffbef11852007-10-26 20:53:56 +00002225 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc, EndLoc, Sel,
Fariborz Jahanian1f7b6f82007-11-09 19:52:12 +00002226 resultDeclType,
Fariborz Jahanianb245a332007-11-13 01:10:08 +00002227 CDecl,
Fariborz Jahanian1f7b6f82007-11-09 19:52:12 +00002228 0, -1, AttrList,
Steve Naroff335eafa2007-11-15 12:35:21 +00002229 MethodType == tok::minus, isVariadic,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002230 MethodDeclKind == tok::objc_optional ?
2231 ObjcMethodDecl::Optional :
2232 ObjcMethodDecl::Required);
Steve Naroffbcfb06a2007-09-28 22:22:11 +00002233 ObjcMethod->setMethodParams(&Params[0], Sel.getNumArgs());
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002234 ObjcMethod->setObjcDeclQualifier(
2235 CvtQTToAstBitMask(ReturnQT.getObjcDeclQualifier()));
Steve Naroffe1e6c0d2007-11-12 22:05:31 +00002236 const ObjcMethodDecl *PrevMethod = 0;
Fariborz Jahanianb245a332007-11-13 01:10:08 +00002237
Steve Naroffe1e6c0d2007-11-12 22:05:31 +00002238 // For implementations (which can be very "coarse grain"), we add the
2239 // method now. This allows the AST to implement lookup methods that work
2240 // incrementally (without waiting until we parse the @end). It also allows
2241 // us to flag multiple declaration errors as they occur.
Fariborz Jahanianb245a332007-11-13 01:10:08 +00002242 if (ObjcImplementationDecl *ImpDecl =
2243 dyn_cast<ObjcImplementationDecl>(CDecl)) {
Steve Naroff0416fb92007-11-11 17:19:15 +00002244 if (MethodType == tok::minus) {
2245 PrevMethod = ImpDecl->lookupInstanceMethod(Sel);
2246 ImpDecl->addInstanceMethod(ObjcMethod);
2247 } else {
2248 PrevMethod = ImpDecl->lookupClassMethod(Sel);
2249 ImpDecl->addClassMethod(ObjcMethod);
2250 }
Fariborz Jahanianb245a332007-11-13 01:10:08 +00002251 }
2252 else if (ObjcCategoryImplDecl *CatImpDecl =
2253 dyn_cast<ObjcCategoryImplDecl>(CDecl)) {
Steve Naroffe1e6c0d2007-11-12 22:05:31 +00002254 if (MethodType == tok::minus) {
2255 PrevMethod = CatImpDecl->lookupInstanceMethod(Sel);
2256 CatImpDecl->addInstanceMethod(ObjcMethod);
2257 } else {
2258 PrevMethod = CatImpDecl->lookupClassMethod(Sel);
2259 CatImpDecl->addClassMethod(ObjcMethod);
2260 }
Steve Naroff0416fb92007-11-11 17:19:15 +00002261 }
Steve Naroffe1e6c0d2007-11-12 22:05:31 +00002262 if (PrevMethod) {
2263 // You can never have two method definitions with the same name.
2264 Diag(ObjcMethod->getLocation(), diag::error_duplicate_method_decl,
2265 ObjcMethod->getSelector().getName());
2266 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
2267 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00002268 return ObjcMethod;
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00002269}
2270
Fariborz Jahanian82a5fe32007-11-06 22:01:00 +00002271Sema::DeclTy *Sema::ActOnAddObjcProperties(SourceLocation AtLoc,
2272 DeclTy **allProperties, unsigned NumProperties, ObjcDeclSpec &DS) {
2273 ObjcPropertyDecl *PDecl = new ObjcPropertyDecl(AtLoc);
2274
2275 if(DS.getPropertyAttributes() & ObjcDeclSpec::DQ_PR_readonly)
2276 PDecl->setPropertyAttributes(ObjcPropertyDecl::OBJC_PR_readonly);
2277
2278 if(DS.getPropertyAttributes() & ObjcDeclSpec::DQ_PR_getter) {
2279 PDecl->setPropertyAttributes(ObjcPropertyDecl::OBJC_PR_getter);
2280 PDecl->setGetterName(DS.getGetterName());
2281 }
2282
2283 if(DS.getPropertyAttributes() & ObjcDeclSpec::DQ_PR_setter) {
2284 PDecl->setPropertyAttributes(ObjcPropertyDecl::OBJC_PR_setter);
2285 PDecl->setSetterName(DS.getSetterName());
2286 }
2287
2288 if(DS.getPropertyAttributes() & ObjcDeclSpec::DQ_PR_assign)
2289 PDecl->setPropertyAttributes(ObjcPropertyDecl::OBJC_PR_assign);
2290
2291 if(DS.getPropertyAttributes() & ObjcDeclSpec::DQ_PR_readwrite)
2292 PDecl->setPropertyAttributes(ObjcPropertyDecl::OBJC_PR_readwrite);
2293
2294 if(DS.getPropertyAttributes() & ObjcDeclSpec::DQ_PR_retain)
2295 PDecl->setPropertyAttributes(ObjcPropertyDecl::OBJC_PR_retain);
2296
2297 if(DS.getPropertyAttributes() & ObjcDeclSpec::DQ_PR_copy)
2298 PDecl->setPropertyAttributes(ObjcPropertyDecl::OBJC_PR_copy);
2299
2300 if(DS.getPropertyAttributes() & ObjcDeclSpec::DQ_PR_nonatomic)
2301 PDecl->setPropertyAttributes(ObjcPropertyDecl::OBJC_PR_nonatomic);
2302
2303 PDecl->setNumPropertyDecls(NumProperties);
2304 if (NumProperties != 0) {
2305 ObjcIvarDecl **properties = new ObjcIvarDecl*[NumProperties];
2306 memcpy(properties, allProperties, NumProperties*sizeof(ObjcIvarDecl*));
2307 PDecl->setPropertyDecls(properties);
2308 }
2309 return PDecl;
2310}
2311
Steve Naroff08d92e42007-09-15 18:49:24 +00002312Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002313 DeclTy *lastEnumConst,
2314 SourceLocation IdLoc, IdentifierInfo *Id,
2315 SourceLocation EqualLoc, ExprTy *val) {
2316 theEnumDecl = theEnumDecl; // silence unused warning.
2317 EnumConstantDecl *LastEnumConst =
2318 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2319 Expr *Val = static_cast<Expr*>(val);
2320
Chris Lattner31e05722007-08-26 06:24:45 +00002321 // The scope passed in may not be a decl scope. Zip up the scope tree until
2322 // we find one that is.
2323 while ((S->getFlags() & Scope::DeclScope) == 0)
2324 S = S->getParent();
2325
Reid Spencer5f016e22007-07-11 17:01:13 +00002326 // Verify that there isn't already something declared with this name in this
2327 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00002328 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
2329 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002330 if (S->isDeclScope(PrevDecl)) {
2331 if (isa<EnumConstantDecl>(PrevDecl))
2332 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2333 else
2334 Diag(IdLoc, diag::err_redefinition, Id->getName());
2335 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2336 // FIXME: Don't leak memory: delete Val;
2337 return 0;
2338 }
2339 }
2340
2341 llvm::APSInt EnumVal(32);
2342 QualType EltTy;
2343 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002344 // Make sure to promote the operand type to int.
2345 UsualUnaryConversions(Val);
2346
Reid Spencer5f016e22007-07-11 17:01:13 +00002347 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2348 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002349 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002350 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2351 Id->getName());
2352 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002353 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002354 } else {
2355 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002356 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002357 }
2358
2359 if (!Val) {
2360 if (LastEnumConst) {
2361 // Assign the last value + 1.
2362 EnumVal = LastEnumConst->getInitVal();
2363 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002364
2365 // Check for overflow on increment.
2366 if (EnumVal < LastEnumConst->getInitVal())
2367 Diag(IdLoc, diag::warn_enum_value_overflow);
2368
Chris Lattnerb7416f92007-08-27 17:37:24 +00002369 EltTy = LastEnumConst->getType();
2370 } else {
2371 // First value, set to zero.
2372 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00002373 EnumVal.zextOrTrunc(
2374 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002375 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002376 }
2377
Reid Spencer5f016e22007-07-11 17:01:13 +00002378 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
2379 LastEnumConst);
2380
2381 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00002382 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00002383 Id->setFETokenInfo(New);
2384 S->AddDecl(New);
2385 return New;
2386}
2387
Steve Naroff08d92e42007-09-15 18:49:24 +00002388void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002389 DeclTy **Elements, unsigned NumElements) {
2390 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
2391 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
2392
Chris Lattnere37f0be2007-08-28 05:10:31 +00002393 // TODO: If the result value doesn't fit in an int, it must be a long or long
2394 // long value. ISO C does not support this, but GCC does as an extension,
2395 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00002396 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00002397
2398
Chris Lattnerac609682007-08-28 06:15:15 +00002399 // Verify that all the values are okay, compute the size of the values, and
2400 // reverse the list.
2401 unsigned NumNegativeBits = 0;
2402 unsigned NumPositiveBits = 0;
2403
2404 // Keep track of whether all elements have type int.
2405 bool AllElementsInt = true;
2406
Reid Spencer5f016e22007-07-11 17:01:13 +00002407 EnumConstantDecl *EltList = 0;
2408 for (unsigned i = 0; i != NumElements; ++i) {
2409 EnumConstantDecl *ECD =
2410 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2411 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002412
2413 // If the enum value doesn't fit in an int, emit an extension warning.
2414 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
2415 "Should have promoted value to int");
2416 const llvm::APSInt &InitVal = ECD->getInitVal();
2417 if (InitVal.getBitWidth() > IntWidth) {
2418 llvm::APSInt V(InitVal);
2419 V.trunc(IntWidth);
2420 V.extend(InitVal.getBitWidth());
2421 if (V != InitVal)
2422 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
2423 InitVal.toString());
2424 }
Chris Lattnerac609682007-08-28 06:15:15 +00002425
2426 // Keep track of the size of positive and negative values.
2427 if (InitVal.isUnsigned() || !InitVal.isNegative())
2428 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
2429 else
2430 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002431
Chris Lattnerac609682007-08-28 06:15:15 +00002432 // Keep track of whether every enum element has type int (very commmon).
2433 if (AllElementsInt)
2434 AllElementsInt = ECD->getType() == Context.IntTy;
2435
Reid Spencer5f016e22007-07-11 17:01:13 +00002436 ECD->setNextDeclarator(EltList);
2437 EltList = ECD;
2438 }
2439
Chris Lattnerac609682007-08-28 06:15:15 +00002440 // Figure out the type that should be used for this enum.
2441 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2442 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002443 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002444
2445 if (NumNegativeBits) {
2446 // If there is a negative value, figure out the smallest integer type (of
2447 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002448 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002449 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002450 BestWidth = IntWidth;
2451 } else {
2452 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
2453 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002454 BestType = Context.LongTy;
2455 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002456 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
2457 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002458 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2459 BestType = Context.LongLongTy;
2460 }
2461 }
2462 } else {
2463 // If there is no negative value, figure out which of uint, ulong, ulonglong
2464 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002465 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002466 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002467 BestWidth = IntWidth;
2468 } else if (NumPositiveBits <=
2469 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00002470 BestType = Context.UnsignedLongTy;
2471 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002472 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
2473 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002474 "How could an initializer get larger than ULL?");
2475 BestType = Context.UnsignedLongLongTy;
2476 }
2477 }
2478
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002479 // Loop over all of the enumerator constants, changing their types to match
2480 // the type of the enum if needed.
2481 for (unsigned i = 0; i != NumElements; ++i) {
2482 EnumConstantDecl *ECD =
2483 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2484 if (!ECD) continue; // Already issued a diagnostic.
2485
2486 // Standard C says the enumerators have int type, but we allow, as an
2487 // extension, the enumerators to be larger than int size. If each
2488 // enumerator value fits in an int, type it as an int, otherwise type it the
2489 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2490 // that X has type 'int', not 'unsigned'.
2491 if (ECD->getType() == Context.IntTy)
2492 continue; // Already int type.
2493
2494 // Determine whether the value fits into an int.
2495 llvm::APSInt InitVal = ECD->getInitVal();
2496 bool FitsInInt;
2497 if (InitVal.isUnsigned() || !InitVal.isNegative())
2498 FitsInInt = InitVal.getActiveBits() < IntWidth;
2499 else
2500 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2501
2502 // If it fits into an integer type, force it. Otherwise force it to match
2503 // the enum decl type.
2504 QualType NewTy;
2505 unsigned NewWidth;
2506 bool NewSign;
2507 if (FitsInInt) {
2508 NewTy = Context.IntTy;
2509 NewWidth = IntWidth;
2510 NewSign = true;
2511 } else if (ECD->getType() == BestType) {
2512 // Already the right type!
2513 continue;
2514 } else {
2515 NewTy = BestType;
2516 NewWidth = BestWidth;
2517 NewSign = BestType->isSignedIntegerType();
2518 }
2519
2520 // Adjust the APSInt value.
2521 InitVal.extOrTrunc(NewWidth);
2522 InitVal.setIsSigned(NewSign);
2523 ECD->setInitVal(InitVal);
2524
2525 // Adjust the Expr initializer and type.
2526 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2527 ECD->setType(NewTy);
2528 }
Chris Lattnerac609682007-08-28 06:15:15 +00002529
Chris Lattnere00b18c2007-08-28 18:24:31 +00002530 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00002531}
2532
Reid Spencer5f016e22007-07-11 17:01:13 +00002533void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
Chris Lattner7ee261c2007-11-27 07:28:18 +00002534 if (!strcmp(rawAttr->getAttributeName()->getName(), "vector_size") ||
2535 !strcmp(rawAttr->getAttributeName()->getName(), "__vector_size__")) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002536 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2537 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
2538 if (!newType.isNull()) // install the new vector type into the decl
2539 vDecl->setType(newType);
2540 }
2541 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2542 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
2543 rawAttr);
2544 if (!newType.isNull()) // install the new vector type into the decl
2545 tDecl->setUnderlyingType(newType);
2546 }
2547 }
Chris Lattner7ee261c2007-11-27 07:28:18 +00002548 if (!strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") ||
2549 !strcmp(rawAttr->getAttributeName()->getName(), "__ocu_vector_type__")) {
Steve Naroffbea0b342007-07-29 16:33:31 +00002550 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
2551 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
2552 else
Steve Naroff73322922007-07-18 18:00:27 +00002553 Diag(rawAttr->getAttributeLoc(),
2554 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00002555 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002556 // FIXME: add other attributes...
2557}
2558
2559void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2560 AttributeList *declarator_postfix) {
2561 while (declspec_prefix) {
2562 HandleDeclAttribute(New, declspec_prefix);
2563 declspec_prefix = declspec_prefix->getNext();
2564 }
2565 while (declarator_postfix) {
2566 HandleDeclAttribute(New, declarator_postfix);
2567 declarator_postfix = declarator_postfix->getNext();
2568 }
2569}
2570
Steve Naroffbea0b342007-07-29 16:33:31 +00002571void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2572 AttributeList *rawAttr) {
2573 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00002574 // check the attribute arugments.
2575 if (rawAttr->getNumArgs() != 1) {
2576 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2577 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002578 return;
Steve Naroff73322922007-07-18 18:00:27 +00002579 }
2580 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2581 llvm::APSInt vecSize(32);
2582 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
2583 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2584 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002585 return;
Steve Naroff73322922007-07-18 18:00:27 +00002586 }
2587 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2588 // in conjunction with complex types (pointers, arrays, functions, etc.).
2589 Type *canonType = curType.getCanonicalType().getTypePtr();
2590 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2591 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2592 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002593 return;
Steve Naroff73322922007-07-18 18:00:27 +00002594 }
2595 // unlike gcc's vector_size attribute, the size is specified as the
2596 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002597 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002598
2599 if (vectorSize == 0) {
2600 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2601 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002602 return;
Steve Naroff73322922007-07-18 18:00:27 +00002603 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002604 // Instantiate/Install the vector type, the number of elements is > 0.
2605 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2606 // Remember this typedef decl, we will need it later for diagnostics.
2607 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002608}
2609
Reid Spencer5f016e22007-07-11 17:01:13 +00002610QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002611 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002612 // check the attribute arugments.
2613 if (rawAttr->getNumArgs() != 1) {
2614 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2615 std::string("1"));
2616 return QualType();
2617 }
2618 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2619 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002620 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002621 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2622 sizeExpr->getSourceRange());
2623 return QualType();
2624 }
2625 // navigate to the base type - we need to provide for vector pointers,
2626 // vector arrays, and functions returning vectors.
2627 Type *canonType = curType.getCanonicalType().getTypePtr();
2628
Steve Naroff73322922007-07-18 18:00:27 +00002629 if (canonType->isPointerType() || canonType->isArrayType() ||
2630 canonType->isFunctionType()) {
2631 assert(1 && "HandleVector(): Complex type construction unimplemented");
2632 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2633 do {
2634 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2635 canonType = PT->getPointeeType().getTypePtr();
2636 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2637 canonType = AT->getElementType().getTypePtr();
2638 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2639 canonType = FT->getResultType().getTypePtr();
2640 } while (canonType->isPointerType() || canonType->isArrayType() ||
2641 canonType->isFunctionType());
2642 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002643 }
2644 // the base type must be integer or float.
2645 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2646 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2647 curType.getCanonicalType().getAsString());
2648 return QualType();
2649 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00002650 unsigned typeSize = static_cast<unsigned>(
2651 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002652 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002653 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002654
2655 // the vector size needs to be an integral multiple of the type size.
2656 if (vectorSize % typeSize) {
2657 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
2658 sizeExpr->getSourceRange());
2659 return QualType();
2660 }
2661 if (vectorSize == 0) {
2662 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2663 sizeExpr->getSourceRange());
2664 return QualType();
2665 }
2666 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
2667 // the number of elements to be a power of two (unlike GCC).
2668 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00002669 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002670}
2671