blob: 3eb50ff08f3e3aa12219f1e77f075e84eab977eb [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000028using namespace clang;
29
Reid Spencer5f016e22007-07-11 17:01:13 +000030Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Chris Lattner5c0fa302007-09-30 08:31:00 +000031 if (Decl *IIDecl = II.getFETokenInfo<Decl>())
32 if (isa<TypedefDecl>(IIDecl) || isa<ObjcInterfaceDecl>(IIDecl))
33 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000034 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000035}
36
37void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000038 if (S->decl_empty()) return;
39 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
40
Reid Spencer5f016e22007-07-11 17:01:13 +000041 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
42 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000043 Decl *TmpD = static_cast<Decl*>(*I);
44 assert(TmpD && "This decl didn't get pushed??");
45 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
46 assert(D && "This decl isn't a ScopedDecl?");
47
Reid Spencer5f016e22007-07-11 17:01:13 +000048 IdentifierInfo *II = D->getIdentifier();
49 if (!II) continue;
50
51 // Unlink this decl from the identifier. Because the scope contains decls
52 // in an unordered collection, and because we have multiple identifier
53 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
54 if (II->getFETokenInfo<Decl>() == D) {
55 // Normal case, no multiple decls in different namespaces.
56 II->setFETokenInfo(D->getNext());
57 } else {
58 // Scan ahead. There are only three namespaces in C, so this loop can
59 // never execute more than 3 times.
Steve Naroffc752d042007-09-13 18:10:37 +000060 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +000061 while (SomeDecl->getNext() != D) {
62 SomeDecl = SomeDecl->getNext();
63 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
64 }
65 SomeDecl->setNext(D->getNext());
66 }
67
68 // This will have to be revisited for C++: there we want to nest stuff in
69 // namespace decls etc. Even for C, we might want a top-level translation
70 // unit decl or something.
71 if (!CurFunctionDecl)
72 continue;
73
74 // Chain this decl to the containing function, it now owns the memory for
75 // the decl.
76 D->setNext(CurFunctionDecl->getDeclChain());
77 CurFunctionDecl->setDeclChain(D);
78 }
79}
80
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +000081/// getObjcInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +000082/// return 0 if one not found.
Steve Naroff6a8a9a42007-10-02 20:01:56 +000083ObjcInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
84
85 // Scan up the scope chain looking for a decl that matches this identifier
86 // that is in the appropriate namespace. This search should not take long, as
87 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
88 ScopedDecl *IdDecl = NULL;
89 for (ScopedDecl *D = Id->getFETokenInfo<ScopedDecl>(); D; D = D->getNext()) {
90 if (D->getIdentifierNamespace() == Decl::IDNS_Ordinary) {
91 IdDecl = D;
92 break;
93 }
94 }
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +000095 if (IdDecl && !isa<ObjcInterfaceDecl>(IdDecl))
96 IdDecl = 0;
97 return cast_or_null<ObjcInterfaceDecl>(static_cast<Decl*>(IdDecl));
98}
99
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000100/// getObjcProtocolDecl - Look up a for a protocol declaration in the scope.
101/// return 0 if one not found.
102ObjcProtocolDecl *Sema::getObjCProtocolDecl(Scope *S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +0000103 IdentifierInfo *Id,
104 SourceLocation IdLoc) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000105 // Note that Protocols have their own namespace.
Fariborz Jahanian245f92a2007-10-05 21:01:53 +0000106 ScopedDecl *PrDecl = NULL;
107 for (ScopedDecl *D = Id->getFETokenInfo<ScopedDecl>(); D; D = D->getNext()) {
108 if (D->getIdentifierNamespace() == Decl::IDNS_Protocol) {
109 PrDecl = D;
110 break;
111 }
112 }
113
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000114 if (PrDecl && !isa<ObjcProtocolDecl>(PrDecl))
115 PrDecl = 0;
116 return cast_or_null<ObjcProtocolDecl>(static_cast<Decl*>(PrDecl));
117}
118
Reid Spencer5f016e22007-07-11 17:01:13 +0000119/// LookupScopedDecl - Look up the inner-most declaration in the specified
120/// namespace.
Steve Naroffc752d042007-09-13 18:10:37 +0000121ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
122 SourceLocation IdLoc, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 if (II == 0) return 0;
124 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
125
126 // Scan up the scope chain looking for a decl that matches this identifier
127 // that is in the appropriate namespace. This search should not take long, as
128 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffc752d042007-09-13 18:10:37 +0000129 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +0000130 if (D->getIdentifierNamespace() == NS)
131 return D;
132
133 // If we didn't find a use of this identifier, and if the identifier
134 // corresponds to a compiler builtin, create the decl object for the builtin
135 // now, injecting it into translation unit scope, and return it.
136 if (NS == Decl::IDNS_Ordinary) {
137 // If this is a builtin on some other target, or if this builtin varies
138 // across targets (e.g. in type), emit a diagnostic and mark the translation
139 // unit non-portable for using it.
140 if (II->isNonPortableBuiltin()) {
141 // Only emit this diagnostic once for this builtin.
142 II->setNonPortableBuiltin(false);
143 Context.Target.DiagnoseNonPortability(IdLoc,
144 diag::port_target_builtin_use);
145 }
146 // If this is a builtin on this (or all) targets, create the decl.
147 if (unsigned BuiltinID = II->getBuiltinID())
148 return LazilyCreateBuiltin(II, BuiltinID, S);
149 }
150 return 0;
151}
152
153/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
154/// lazily create a decl for it.
Steve Naroffc752d042007-09-13 18:10:37 +0000155ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000156 Builtin::ID BID = (Builtin::ID)bid;
157
158 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
159 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000160 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000161
162 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000163 if (Scope *FnS = S->getFnParent())
164 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000165 while (S->getParent())
166 S = S->getParent();
167 S->AddDecl(New);
168
169 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000170 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000171 // Scan until we find the last (outermost) decl in the id chain.
172 while (LastDecl->getNext())
173 LastDecl = LastDecl->getNext();
174 // Insert before (outside) it.
175 LastDecl->setNext(New);
176 } else {
177 II->setFETokenInfo(New);
178 }
179 // Make sure clients iterating over decls see this.
180 LastInGroupList.push_back(New);
181
182 return New;
183}
184
185/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
186/// and scope as a previous declaration 'Old'. Figure out how to resolve this
187/// situation, merging decls or emitting diagnostics as appropriate.
188///
Steve Naroff8e74c932007-09-13 21:41:19 +0000189TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 // Verify the old decl was also a typedef.
191 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
192 if (!Old) {
193 Diag(New->getLocation(), diag::err_redefinition_different_kind,
194 New->getName());
195 Diag(OldD->getLocation(), diag::err_previous_definition);
196 return New;
197 }
198
199 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
200 // TODO: This is totally simplistic. It should handle merging functions
201 // together etc, merging extern int X; int X; ...
202 Diag(New->getLocation(), diag::err_redefinition, New->getName());
203 Diag(Old->getLocation(), diag::err_previous_definition);
204 return New;
205}
206
207/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
208/// and scope as a previous declaration 'Old'. Figure out how to resolve this
209/// situation, merging decls or emitting diagnostics as appropriate.
210///
Steve Naroff8e74c932007-09-13 21:41:19 +0000211FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000212 // Verify the old decl was also a function.
213 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
214 if (!Old) {
215 Diag(New->getLocation(), diag::err_redefinition_different_kind,
216 New->getName());
217 Diag(OldD->getLocation(), diag::err_previous_definition);
218 return New;
219 }
220
221 // This is not right, but it's a start. If 'Old' is a function prototype with
222 // the same type as 'New', silently allow this. FIXME: We should link up decl
223 // objects here.
224 if (Old->getBody() == 0 &&
225 Old->getCanonicalType() == New->getCanonicalType()) {
226 return New;
227 }
228
229 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
230 // TODO: This is totally simplistic. It should handle merging functions
231 // together etc, merging extern int X; int X; ...
232 Diag(New->getLocation(), diag::err_redefinition, New->getName());
233 Diag(Old->getLocation(), diag::err_previous_definition);
234 return New;
235}
236
237/// MergeVarDecl - We just parsed a variable 'New' which has the same name
238/// and scope as a previous declaration 'Old'. Figure out how to resolve this
239/// situation, merging decls or emitting diagnostics as appropriate.
240///
241/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
242/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
243///
Steve Naroff8e74c932007-09-13 21:41:19 +0000244VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000245 // Verify the old decl was also a variable.
246 VarDecl *Old = dyn_cast<VarDecl>(OldD);
247 if (!Old) {
248 Diag(New->getLocation(), diag::err_redefinition_different_kind,
249 New->getName());
250 Diag(OldD->getLocation(), diag::err_previous_definition);
251 return New;
252 }
Steve Narofffb22d962007-08-30 01:06:46 +0000253 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
254 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
255 bool OldIsTentative = false;
256
257 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
258 // Handle C "tentative" external object definitions. FIXME: finish!
259 if (!OldFSDecl->getInit() &&
260 (OldFSDecl->getStorageClass() == VarDecl::None ||
261 OldFSDecl->getStorageClass() == VarDecl::Static))
262 OldIsTentative = true;
263 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000264 // Verify the types match.
265 if (Old->getCanonicalType() != New->getCanonicalType()) {
266 Diag(New->getLocation(), diag::err_redefinition, New->getName());
267 Diag(Old->getLocation(), diag::err_previous_definition);
268 return New;
269 }
270 // We've verified the types match, now check if Old is "extern".
271 if (Old->getStorageClass() != VarDecl::Extern) {
272 Diag(New->getLocation(), diag::err_redefinition, New->getName());
273 Diag(Old->getLocation(), diag::err_previous_definition);
274 }
275 return New;
276}
277
278/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
279/// no declarator (e.g. "struct foo;") is parsed.
280Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
281 // TODO: emit error on 'int;' or 'const enum foo;'.
282 // TODO: emit error on 'typedef int;'
283 // if (!DS.isMissingDeclaratorOk()) Diag(...);
284
285 return 0;
286}
287
Steve Naroff9e8925e2007-09-04 14:36:54 +0000288bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000289 AssignmentCheckResult result;
290 SourceLocation loc = Init->getLocStart();
291 // Get the type before calling CheckSingleAssignmentConstraints(), since
292 // it can promote the expression.
293 QualType rhsType = Init->getType();
294
295 result = CheckSingleAssignmentConstraints(DeclType, Init);
296
297 // decode the result (notice that extensions still return a type).
298 switch (result) {
299 case Compatible:
300 break;
301 case Incompatible:
Steve Naroff6f9f3072007-09-02 15:34:30 +0000302 // FIXME: tighten up this check which should allow:
303 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
304 if (rhsType == Context.getPointerType(Context.CharTy))
305 break;
Steve Narofff0090632007-09-02 02:04:30 +0000306 Diag(loc, diag::err_typecheck_assign_incompatible,
307 DeclType.getAsString(), rhsType.getAsString(),
308 Init->getSourceRange());
309 return true;
310 case PointerFromInt:
311 // check for null pointer constant (C99 6.3.2.3p3)
312 if (!Init->isNullPointerConstant(Context)) {
313 Diag(loc, diag::ext_typecheck_assign_pointer_int,
314 DeclType.getAsString(), rhsType.getAsString(),
315 Init->getSourceRange());
316 return true;
317 }
318 break;
319 case IntFromPointer:
320 Diag(loc, diag::ext_typecheck_assign_pointer_int,
321 DeclType.getAsString(), rhsType.getAsString(),
322 Init->getSourceRange());
323 break;
324 case IncompatiblePointer:
325 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
326 DeclType.getAsString(), rhsType.getAsString(),
327 Init->getSourceRange());
328 break;
329 case CompatiblePointerDiscardsQualifiers:
330 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
331 DeclType.getAsString(), rhsType.getAsString(),
332 Init->getSourceRange());
333 break;
334 }
335 return false;
336}
337
Steve Naroff9e8925e2007-09-04 14:36:54 +0000338bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
339 bool isStatic, QualType ElementType) {
Steve Naroff371227d2007-09-04 02:20:04 +0000340 SourceLocation loc;
Steve Naroff9e8925e2007-09-04 14:36:54 +0000341 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff371227d2007-09-04 02:20:04 +0000342
343 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
344 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
345 return true;
346 } else if (CheckSingleInitializer(expr, ElementType)) {
347 return true; // types weren't compatible.
348 }
Steve Naroff9e8925e2007-09-04 14:36:54 +0000349 if (savExpr != expr) // The type was promoted, update initializer list.
350 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000351 return false;
352}
353
354void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
355 QualType ElementType, bool isStatic,
356 int &nInitializers, bool &hadError) {
Steve Naroff6f9f3072007-09-02 15:34:30 +0000357 for (unsigned i = 0; i < IList->getNumInits(); i++) {
358 Expr *expr = IList->getInit(i);
359
Steve Naroff371227d2007-09-04 02:20:04 +0000360 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
361 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000362 int maxElements = CAT->getMaximumElements();
Steve Naroff371227d2007-09-04 02:20:04 +0000363 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
364 maxElements, hadError);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000365 }
Steve Naroff371227d2007-09-04 02:20:04 +0000366 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000367 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000368 }
Steve Naroff371227d2007-09-04 02:20:04 +0000369 nInitializers++;
370 }
371 return;
372}
373
374// FIXME: Doesn't deal with arrays of structures yet.
375void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
376 QualType ElementType, bool isStatic,
377 int &totalInits, bool &hadError) {
378 int maxElementsAtThisLevel = 0;
379 int nInitsAtLevel = 0;
380
381 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
382 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff7cf8c442007-09-04 21:13:33 +0000383 maxElementsAtThisLevel = CAT->getMaximumElements();
384 // Set DeclType, used below to recurse (for multi-dimensional arrays).
385 DeclType = CAT->getElementType();
Steve Naroff371227d2007-09-04 02:20:04 +0000386 } else if (DeclType->isScalarType()) {
387 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
388 IList->getSourceRange());
389 maxElementsAtThisLevel = 1;
390 }
391 // The empty init list "{ }" is treated specially below.
392 unsigned numInits = IList->getNumInits();
393 if (numInits) {
394 for (unsigned i = 0; i < numInits; i++) {
395 Expr *expr = IList->getInit(i);
396
397 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
398 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
399 totalInits, hadError);
400 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000401 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff371227d2007-09-04 02:20:04 +0000402 nInitsAtLevel++; // increment the number of initializers at this level.
403 totalInits--; // decrement the total number of initializers.
404
405 // Check if we have space for another initializer.
406 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
407 Diag(expr->getLocStart(), diag::warn_excess_initializers,
408 expr->getSourceRange());
409 }
410 }
411 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
412 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
413 } else {
414 // we have an initializer list with no elements.
415 totalInits -= maxElementsAtThisLevel;
416 if (totalInits < 0)
417 Diag(IList->getLocStart(), diag::warn_excess_initializers,
418 IList->getSourceRange());
Steve Naroff6f9f3072007-09-02 15:34:30 +0000419 }
Steve Naroffd35005e2007-09-03 01:24:23 +0000420 return;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000421}
422
Steve Naroff9e8925e2007-09-04 14:36:54 +0000423bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Narofff0090632007-09-02 02:04:30 +0000424 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroffd35005e2007-09-03 01:24:23 +0000425 if (!InitList)
426 return CheckSingleInitializer(Init, DeclType);
427
Steve Narofff0090632007-09-02 02:04:30 +0000428 // We have an InitListExpr, make sure we set the type.
429 Init->setType(DeclType);
Steve Naroffd35005e2007-09-03 01:24:23 +0000430
431 bool hadError = false;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000432
Steve Naroff38374b02007-09-02 20:30:18 +0000433 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
434 // of unknown size ("[]") or an object type that is not a variable array type.
435 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
436 Expr *expr = VAT->getSizeExpr();
Steve Naroffd35005e2007-09-03 01:24:23 +0000437 if (expr)
438 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
439 expr->getSourceRange());
440
Steve Naroff7cf8c442007-09-04 21:13:33 +0000441 // We have a VariableArrayType with unknown size. Note that only the first
442 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff371227d2007-09-04 02:20:04 +0000443 int numInits = 0;
Steve Naroff7cf8c442007-09-04 21:13:33 +0000444 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
445 isStatic, numInits, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000446 if (!hadError) {
447 // Return a new array type from the number of initializers (C99 6.7.8p22).
448 llvm::APSInt ConstVal(32);
Steve Naroff371227d2007-09-04 02:20:04 +0000449 ConstVal = numInits;
450 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroffd35005e2007-09-03 01:24:23 +0000451 ArrayType::Normal, 0);
452 }
453 return hadError;
454 }
455 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000456 int maxElements = CAT->getMaximumElements();
457 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
458 isStatic, maxElements, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000459 return hadError;
460 }
Steve Naroff371227d2007-09-04 02:20:04 +0000461 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
462 int maxElements = 1;
463 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
464 hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000465 return hadError;
Steve Naroff38374b02007-09-02 20:30:18 +0000466 }
467 // FIXME: Handle struct/union types.
Steve Naroffd35005e2007-09-03 01:24:23 +0000468 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +0000469}
470
Reid Spencer5f016e22007-07-11 17:01:13 +0000471Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000472Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000473 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 IdentifierInfo *II = D.getIdentifier();
475
Chris Lattnere80a59c2007-07-25 00:24:17 +0000476 // All of these full declarators require an identifier. If it doesn't have
477 // one, the ParsedFreeStandingDeclSpec action should be used.
478 if (II == 0) {
Chris Lattner98e08632007-08-28 06:17:15 +0000479 Diag(D.getDeclSpec().getSourceRange().Begin(),
480 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000481 D.getDeclSpec().getSourceRange(), D.getSourceRange());
482 return 0;
483 }
484
Chris Lattner31e05722007-08-26 06:24:45 +0000485 // The scope passed in may not be a decl scope. Zip up the scope tree until
486 // we find one that is.
487 while ((S->getFlags() & Scope::DeclScope) == 0)
488 S = S->getParent();
489
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000491 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
492 D.getIdentifierLoc(), S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000493 if (PrevDecl && !S->isDeclScope(PrevDecl))
494 PrevDecl = 0; // If in outer scope, it isn't the same thing.
495
Steve Naroffc752d042007-09-13 18:10:37 +0000496 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000497 bool InvalidDecl = false;
498
Reid Spencer5f016e22007-07-11 17:01:13 +0000499 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
500 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
501 if (!NewTD) return 0;
502
503 // Handle attributes prior to checking for duplicates in MergeVarDecl
504 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
505 D.getAttributes());
506 // Merge the decl with the existing one if appropriate.
507 if (PrevDecl) {
508 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
509 if (NewTD == 0) return 0;
510 }
511 New = NewTD;
512 if (S->getParent() == 0) {
513 // C99 6.7.7p2: If a typedef name specifies a variably modified type
514 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000515 if (const VariableArrayType *VAT =
516 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
517 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
518 VAT->getSizeExpr()->getSourceRange());
519 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 }
521 }
522 } else if (D.isFunctionDeclarator()) {
523 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000524 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000525
Chris Lattner271f1a62007-09-27 15:15:46 +0000526 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000527 switch (D.getDeclSpec().getStorageClassSpec()) {
528 default: assert(0 && "Unknown storage class!");
529 case DeclSpec::SCS_auto:
530 case DeclSpec::SCS_register:
531 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
532 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000533 InvalidDecl = true;
534 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000535 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
536 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
537 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
538 }
539
540 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000541 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000542 LastDeclarator);
543
544 // Merge the decl with the existing one if appropriate.
545 if (PrevDecl) {
546 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
547 if (NewFD == 0) return 0;
548 }
549 New = NewFD;
550 } else {
551 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff53a32342007-08-28 18:45:29 +0000552 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000553
554 VarDecl *NewVD;
555 VarDecl::StorageClass SC;
556 switch (D.getDeclSpec().getStorageClassSpec()) {
557 default: assert(0 && "Unknown storage class!");
558 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
559 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
560 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
561 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
562 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
563 }
564 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000565 // C99 6.9p2: The storage-class specifiers auto and register shall not
566 // appear in the declaration specifiers in an external declaration.
567 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
568 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
569 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000570 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000571 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000573 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000574 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000575 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000576 // Handle attributes prior to checking for duplicates in MergeVarDecl
577 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
578 D.getAttributes());
579
580 // Merge the decl with the existing one if appropriate.
581 if (PrevDecl) {
582 NewVD = MergeVarDecl(NewVD, PrevDecl);
583 if (NewVD == 0) return 0;
584 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000585 New = NewVD;
586 }
587
588 // If this has an identifier, add it to the scope stack.
589 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000590 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 II->setFETokenInfo(New);
592 S->AddDecl(New);
593 }
594
595 if (S->getParent() == 0)
596 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +0000597
598 // If any semantic error occurred, mark the decl as invalid.
599 if (D.getInvalidType() || InvalidDecl)
600 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000601
602 return New;
603}
604
Steve Naroffbb204692007-09-12 14:07:44 +0000605void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000606 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000607 Expr *Init = static_cast<Expr *>(init);
608
Steve Naroff410e3e22007-09-12 20:13:48 +0000609 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000610
Steve Naroff410e3e22007-09-12 20:13:48 +0000611 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
612 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000613 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
614 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000615 RealDecl->setInvalidDecl();
616 return;
617 }
Steve Naroffbb204692007-09-12 14:07:44 +0000618 // Get the decls type and save a reference for later, since
619 // CheckInitializer may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000620 QualType DclT = VDecl->getType(), SavT = DclT;
621 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000622 VarDecl::StorageClass SC = BVD->getStorageClass();
623 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000624 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000625 BVD->setInvalidDecl();
626 } else if (!BVD->isInvalidDecl()) {
627 CheckInitializer(Init, DclT, SC == VarDecl::Static);
628 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000629 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000630 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000631 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000632 if (!FVD->isInvalidDecl())
633 CheckInitializer(Init, DclT, true);
634 }
635 // If the type changed, it means we had an incomplete type that was
636 // completed by the initializer. For example:
637 // int ary[] = { 1, 3, 5 };
638 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff410e3e22007-09-12 20:13:48 +0000639 if (!VDecl->isInvalidDecl() && (DclT != SavT))
640 VDecl->setType(DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000641
642 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000643 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000644 return;
645}
646
Reid Spencer5f016e22007-07-11 17:01:13 +0000647/// The declarators are chained together backwards, reverse the list.
648Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
649 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000650 Decl *GroupDecl = static_cast<Decl*>(group);
651 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000652 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000653
654 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
655 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000656 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000657 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000658 else { // reverse the list.
659 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000660 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000661 Group->setNextDeclarator(NewGroup);
662 NewGroup = Group;
663 Group = Next;
664 }
665 }
666 // Perform semantic analysis that depends on having fully processed both
667 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000668 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000669 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
670 if (!IDecl)
671 continue;
672 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
673 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
674 QualType T = IDecl->getType();
675
676 // C99 6.7.5.2p2: If an identifier is declared to be an object with
677 // static storage duration, it shall not have a variable length array.
678 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
679 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
680 if (VLA->getSizeExpr()) {
681 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
682 IDecl->setInvalidDecl();
683 }
684 }
685 }
686 // Block scope. C99 6.7p7: If an identifier for an object is declared with
687 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
688 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
689 if (T->isIncompleteType()) {
690 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
691 T.getAsString());
692 IDecl->setInvalidDecl();
693 }
694 }
695 // File scope. C99 6.9.2p2: A declaration of an identifier for and
696 // object that has file scope without an initializer, and without a
697 // storage-class specifier or with the storage-class specifier "static",
698 // constitutes a tentative definition. Note: A tentative definition with
699 // external linkage is valid (C99 6.2.2p5).
700 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
701 // C99 6.9.2p3: If the declaration of an identifier for an object is
702 // a tentative definition and has internal linkage (C99 6.2.2p3), the
703 // declared type shall not be an incomplete type.
704 if (T->isIncompleteType()) {
705 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
706 T.getAsString());
707 IDecl->setInvalidDecl();
708 }
709 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000710 }
711 return NewGroup;
712}
Steve Naroffe1223f72007-08-28 03:03:08 +0000713
714// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000715ParmVarDecl *
716Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
717 Scope *FnScope) {
718 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
719
720 IdentifierInfo *II = PI.Ident;
721 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
722 // Can this happen for params? We already checked that they don't conflict
723 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000724 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 PI.IdentLoc, FnScope)) {
726
727 }
728
729 // FIXME: Handle storage class (auto, register). No declarator?
730 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000731
732 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
733 // Doing the promotion here has a win and a loss. The win is the type for
734 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
735 // code generator). The loss is the orginal type isn't preserved. For example:
736 //
737 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
738 // int blockvardecl[5];
739 // sizeof(parmvardecl); // size == 4
740 // sizeof(blockvardecl); // size == 20
741 // }
742 //
743 // For expressions, all implicit conversions are captured using the
744 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
745 //
746 // FIXME: If a source translation tool needs to see the original type, then
747 // we need to consider storing both types (in ParmVarDecl)...
748 //
749 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
750 if (const ArrayType *AT = parmDeclType->getAsArrayType())
751 parmDeclType = Context.getPointerType(AT->getElementType());
752 else if (parmDeclType->isFunctionType())
753 parmDeclType = Context.getPointerType(parmDeclType);
754
755 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff53a32342007-08-28 18:45:29 +0000756 VarDecl::None, 0);
757 if (PI.InvalidType)
758 New->setInvalidDecl();
759
Reid Spencer5f016e22007-07-11 17:01:13 +0000760 // If this has an identifier, add it to the scope stack.
761 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000762 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 II->setFETokenInfo(New);
764 FnScope->AddDecl(New);
765 }
766
767 return New;
768}
769
770
771Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
772 assert(CurFunctionDecl == 0 && "Function parsing confused");
773 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
774 "Not a function declarator!");
775 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
776
777 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
778 // for a K&R function.
779 if (!FTI.hasPrototype) {
780 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
781 if (FTI.ArgInfo[i].TypeInfo == 0) {
782 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
783 FTI.ArgInfo[i].Ident->getName());
784 // Implicitly declare the argument as type 'int' for lack of a better
785 // type.
786 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
787 }
788 }
789
790 // Since this is a function definition, act as though we have information
791 // about the arguments.
792 FTI.hasPrototype = true;
793 } else {
794 // FIXME: Diagnose arguments without names in C.
795
796 }
797
798 Scope *GlobalScope = FnBodyScope->getParent();
799
800 FunctionDecl *FD =
Steve Naroff08d92e42007-09-15 18:49:24 +0000801 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000802 CurFunctionDecl = FD;
803
804 // Create Decl objects for each parameter, adding them to the FunctionDecl.
805 llvm::SmallVector<ParmVarDecl*, 16> Params;
806
807 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
808 // no arguments, not a function that takes a single void argument.
809 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
810 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
811 // empty arg list, don't push any params.
812 } else {
813 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
814 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
815 }
816
817 FD->setParams(&Params[0], Params.size());
818
819 return FD;
820}
821
822Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
823 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
824 FD->setBody((Stmt*)Body);
825
826 assert(FD == CurFunctionDecl && "Function parsing confused");
827 CurFunctionDecl = 0;
828
829 // Verify and clean out per-function state.
830
831 // Check goto/label use.
832 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
833 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
834 // Verify that we have no forward references left. If so, there was a goto
835 // or address of a label taken, but no definition of it. Label fwd
836 // definitions are indicated with a null substmt.
837 if (I->second->getSubStmt() == 0) {
838 LabelStmt *L = I->second;
839 // Emit error.
840 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
841
842 // At this point, we have gotos that use the bogus label. Stitch it into
843 // the function body so that they aren't leaked and that the AST is well
844 // formed.
845 L->setSubStmt(new NullStmt(L->getIdentLoc()));
846 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
847 }
848 }
849 LabelMap.clear();
850
851 return FD;
852}
853
854
855/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
856/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000857ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
858 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000859 if (getLangOptions().C99) // Extension in C99.
860 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
861 else // Legal in C90, but warn about it.
862 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
863
864 // FIXME: handle stuff like:
865 // void foo() { extern float X(); }
866 // void bar() { X(); } <-- implicit decl for X in another scope.
867
868 // Set a Declarator for the implicit definition: int foo();
869 const char *Dummy;
870 DeclSpec DS;
871 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
872 Error = Error; // Silence warning.
873 assert(!Error && "Error setting up implicit decl!");
874 Declarator D(DS, Declarator::BlockContext);
875 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
876 D.SetIdentifier(&II, Loc);
877
878 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000879 if (Scope *FnS = S->getFnParent())
880 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000881 while (S->getParent())
882 S = S->getParent();
883
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000884 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +0000885}
886
887
888TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
Steve Naroff94745042007-09-13 23:52:58 +0000889 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000890 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
891
892 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000893 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000894
895 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +0000896 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
897 T, LastDeclarator);
898 if (D.getInvalidType())
899 NewTD->setInvalidDecl();
900 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000901}
902
Steve Naroff3a165b02007-10-03 21:00:46 +0000903Sema::DeclTy *Sema::ActOnStartClassInterface(Scope* S,
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000904 SourceLocation AtInterfaceLoc,
Steve Naroff3536b442007-09-06 21:24:23 +0000905 IdentifierInfo *ClassName, SourceLocation ClassLoc,
906 IdentifierInfo *SuperName, SourceLocation SuperLoc,
907 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
908 AttributeList *AttrList) {
909 assert(ClassName && "Missing class identifier");
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000910
911 // Check for another declaration kind with the same name.
912 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
913 ClassLoc, S);
914 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
915 && !isa<ObjcProtocolDecl>(PrevDecl)) {
916 Diag(ClassLoc, diag::err_redefinition_different_kind,
917 ClassName->getName());
918 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
919 }
920
Steve Naroff6a8a9a42007-10-02 20:01:56 +0000921 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000922 if (IDecl) {
923 // Class already seen. Is it a forward declaration?
Steve Naroff768f26e2007-10-02 20:26:23 +0000924 if (!IDecl->isForwardDecl())
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000925 Diag(AtInterfaceLoc, diag::err_duplicate_class_def, ClassName->getName());
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000926 else {
Steve Naroff768f26e2007-10-02 20:26:23 +0000927 IDecl->setForwardDecl(false);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000928 IDecl->AllocIntfRefProtocols(NumProtocols);
929 }
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000930 }
931 else {
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000932 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, NumProtocols, ClassName);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000933
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000934 // Chain & install the interface decl into the identifier.
935 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
936 ClassName->setFETokenInfo(IDecl);
937 }
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000938
939 if (SuperName) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000940 ObjcInterfaceDecl* SuperClassEntry = 0;
941 // Check if a different kind of symbol declared in this scope.
942 PrevDecl = LookupScopedDecl(SuperName, Decl::IDNS_Ordinary,
943 SuperLoc, S);
944 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
945 && !isa<ObjcProtocolDecl>(PrevDecl)) {
946 Diag(SuperLoc, diag::err_redefinition_different_kind,
947 SuperName->getName());
948 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000949 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000950 else {
951 // Check that super class is previously defined
Steve Naroff6a8a9a42007-10-02 20:01:56 +0000952 SuperClassEntry = getObjCInterfaceDecl(SuperName);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000953
Steve Naroff768f26e2007-10-02 20:26:23 +0000954 if (!SuperClassEntry || SuperClassEntry->isForwardDecl()) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000955 Diag(AtInterfaceLoc, diag::err_undef_superclass, SuperName->getName(),
956 ClassName->getName());
957 }
958 }
959 IDecl->setSuperClass(SuperClassEntry);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000960 }
961
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000962 /// Check then save referenced protocols
963 for (unsigned int i = 0; i != NumProtocols; i++) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000964 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtocolNames[i],
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +0000965 ClassLoc);
Steve Naroff768f26e2007-10-02 20:26:23 +0000966 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000967 Diag(ClassLoc, diag::err_undef_protocolref,
968 ProtocolNames[i]->getName(),
969 ClassName->getName());
970 IDecl->setIntfRefProtocols((int)i, RefPDecl);
971 }
972
Steve Naroff3536b442007-09-06 21:24:23 +0000973 return IDecl;
974}
975
Steve Naroff3a165b02007-10-03 21:00:46 +0000976Sema::DeclTy *Sema::ActOnStartProtocolInterface(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +0000977 SourceLocation AtProtoInterfaceLoc,
Fariborz Jahanian25e077d2007-09-17 21:07:36 +0000978 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
979 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
980 assert(ProtocolName && "Missing protocol identifier");
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000981 ObjcProtocolDecl *PDecl = getObjCProtocolDecl(S, ProtocolName, ProtocolLoc);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000982 if (PDecl) {
983 // Protocol already seen. Better be a forward protocol declaration
Steve Naroff768f26e2007-10-02 20:26:23 +0000984 if (!PDecl->isForwardDecl())
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000985 Diag(ProtocolLoc, diag::err_duplicate_protocol_def,
986 ProtocolName->getName());
987 else {
Steve Naroff768f26e2007-10-02 20:26:23 +0000988 PDecl->setForwardDecl(false);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000989 PDecl->AllocReferencedProtocols(NumProtoRefs);
990 }
991 }
992 else {
993 PDecl = new ObjcProtocolDecl(AtProtoInterfaceLoc, NumProtoRefs,
994 ProtocolName);
Steve Naroff768f26e2007-10-02 20:26:23 +0000995 PDecl->setForwardDecl(false);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000996 // Chain & install the protocol decl into the identifier.
997 PDecl->setNext(ProtocolName->getFETokenInfo<ScopedDecl>());
998 ProtocolName->setFETokenInfo(PDecl);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000999 }
1000
1001 /// Check then save referenced protocols
1002 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +00001003 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtoRefNames[i],
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001004 ProtocolLoc);
Steve Naroff768f26e2007-10-02 20:26:23 +00001005 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001006 Diag(ProtocolLoc, diag::err_undef_protocolref,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001007 ProtoRefNames[i]->getName(),
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001008 ProtocolName->getName());
1009 PDecl->setReferencedProtocols((int)i, RefPDecl);
1010 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001011
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001012 return PDecl;
1013}
1014
Fariborz Jahanian245f92a2007-10-05 21:01:53 +00001015/// ActOnFindProtocolDeclaration - This routine looks for a previously
1016/// declared protocol and returns it. If not found, issues diagnostic.
1017/// Will build a list of previously protocol declarations found in the list.
1018Action::DeclTy **
1019Sema::ActOnFindProtocolDeclaration(Scope *S,
1020 SourceLocation TypeLoc,
1021 IdentifierInfo **ProtocolId,
1022 unsigned NumProtocols) {
1023 for (unsigned i = 0; i != NumProtocols; ++i) {
1024 ObjcProtocolDecl *PDecl = getObjCProtocolDecl(S, ProtocolId[i],
1025 TypeLoc);
1026 if (!PDecl)
1027 Diag(TypeLoc, diag::err_undeclared_protocol,
1028 ProtocolId[i]->getName());
1029 }
1030 return 0;
1031}
1032
Steve Naroff37e58d12007-10-02 22:39:18 +00001033/// ActOnForwardProtocolDeclaration -
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001034/// Scope will always be top level file scope.
1035Action::DeclTy *
Steve Naroff37e58d12007-10-02 22:39:18 +00001036Sema::ActOnForwardProtocolDeclaration(Scope *S, SourceLocation AtProtocolLoc,
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001037 IdentifierInfo **IdentList, unsigned NumElts) {
Chris Lattnerb97de3e2007-10-06 20:05:59 +00001038 llvm::SmallVector<ObjcProtocolDecl*, 32> Protocols;
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001039
1040 for (unsigned i = 0; i != NumElts; ++i) {
Chris Lattner60c52182007-10-07 07:05:08 +00001041 IdentifierInfo *P = IdentList[i];
1042 ObjcProtocolDecl *PDecl = getObjCProtocolDecl(S, P, AtProtocolLoc);
1043 if (!PDecl) { // Not already seen?
1044 // FIXME: Pass in the location of the identifier!
1045 PDecl = new ObjcProtocolDecl(AtProtocolLoc, 0, P, true);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001046 // Chain & install the protocol decl into the identifier.
1047 PDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1048 IdentList[i]->setFETokenInfo(PDecl);
Chris Lattner60c52182007-10-07 07:05:08 +00001049
1050 // Remember that this needs to be removed when the scope is popped.
1051 S->AddDecl(PDecl);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001052 }
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001053
Chris Lattnerb97de3e2007-10-06 20:05:59 +00001054 Protocols.push_back(PDecl);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001055 }
Chris Lattnerb97de3e2007-10-06 20:05:59 +00001056 return new ObjcForwardProtocolDecl(AtProtocolLoc,
1057 &Protocols[0], Protocols.size());
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001058}
1059
Steve Naroff3a165b02007-10-03 21:00:46 +00001060Sema::DeclTy *Sema::ActOnStartCategoryInterface(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001061 SourceLocation AtInterfaceLoc,
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001062 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1063 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1064 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
Chris Lattnerfd5de472007-10-06 22:53:46 +00001065 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
1066 ObjcCategoryDecl *CDecl = new ObjcCategoryDecl(AtInterfaceLoc, NumProtoRefs,
1067 CategoryName);
Fariborz Jahanian0332b6c2007-10-08 16:07:03 +00001068 bool err = false;
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001069 CDecl->setClassInterface(IDecl);
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +00001070
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001071 /// Check that class of this category is already completely declared.
Fariborz Jahanian0332b6c2007-10-08 16:07:03 +00001072 if (!IDecl || IDecl->isForwardDecl()) {
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001073 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
Fariborz Jahanian0332b6c2007-10-08 16:07:03 +00001074 err = true;
1075 }
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001076 else {
1077 /// Check for duplicate interface declaration for this category
1078 ObjcCategoryDecl *CDeclChain;
1079 for (CDeclChain = IDecl->getListCategories(); CDeclChain;
1080 CDeclChain = CDeclChain->getNextClassCategory()) {
Chris Lattnerfd5de472007-10-06 22:53:46 +00001081 if (CDeclChain->getIdentifier() == CategoryName) {
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001082 Diag(CategoryLoc, diag::err_dup_category_def, ClassName->getName(),
1083 CategoryName->getName());
Fariborz Jahanian0332b6c2007-10-08 16:07:03 +00001084 err = true;
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001085 break;
1086 }
1087 }
Chris Lattnerfd5de472007-10-06 22:53:46 +00001088 if (!CDeclChain)
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001089 CDecl->insertNextClassCategory();
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001090 }
1091
1092 /// Check then save referenced protocols
1093 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +00001094 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtoRefNames[i],
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001095 CategoryLoc);
Fariborz Jahanian0332b6c2007-10-08 16:07:03 +00001096 if (!RefPDecl || RefPDecl->isForwardDecl()) {
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001097 Diag(CategoryLoc, diag::err_undef_protocolref,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001098 ProtoRefNames[i]->getName(),
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001099 CategoryName->getName());
Fariborz Jahanian0332b6c2007-10-08 16:07:03 +00001100 err = true;
1101 }
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001102 CDecl->setCatReferencedProtocols((int)i, RefPDecl);
1103 }
1104
Fariborz Jahanian0332b6c2007-10-08 16:07:03 +00001105 return err ? 0 : CDecl;
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001106}
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001107
Steve Naroff3a165b02007-10-03 21:00:46 +00001108/// ActOnStartCategoryImplementation - Perform semantic checks on the
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001109/// category implementation declaration and build an ObjcCategoryImplDecl
1110/// object.
Steve Naroff3a165b02007-10-03 21:00:46 +00001111Sema::DeclTy *Sema::ActOnStartCategoryImplementation(Scope* S,
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001112 SourceLocation AtCatImplLoc,
1113 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1114 IdentifierInfo *CatName, SourceLocation CatLoc) {
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001115 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001116 ObjcCategoryImplDecl *CDecl = new ObjcCategoryImplDecl(AtCatImplLoc,
Chris Lattner6a0e89e2007-10-06 23:12:31 +00001117 CatName, IDecl);
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001118 /// Check that class of this category is already completely declared.
Steve Naroff768f26e2007-10-02 20:26:23 +00001119 if (!IDecl || IDecl->isForwardDecl())
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001120 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
1121 /// TODO: Check that CatName, category name, is not used in another
1122 // implementation.
1123 return CDecl;
1124}
1125
Steve Naroff3a165b02007-10-03 21:00:46 +00001126Sema::DeclTy *Sema::ActOnStartClassImplementation(Scope *S,
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001127 SourceLocation AtClassImplLoc,
1128 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1129 IdentifierInfo *SuperClassname,
1130 SourceLocation SuperClassLoc) {
1131 ObjcInterfaceDecl* IDecl = 0;
1132 // Check for another declaration kind with the same name.
1133 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
1134 ClassLoc, S);
1135 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
1136 Diag(ClassLoc, diag::err_redefinition_different_kind,
1137 ClassName->getName());
1138 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1139 }
1140 else {
1141 // Is there an interface declaration of this class; if not, warn!
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001142 IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001143 if (!IDecl)
1144 Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
1145 }
1146
1147 // Check that super class name is valid class name
1148 ObjcInterfaceDecl* SDecl = 0;
1149 if (SuperClassname) {
1150 // Check if a different kind of symbol declared in this scope.
1151 PrevDecl = LookupScopedDecl(SuperClassname, Decl::IDNS_Ordinary,
1152 SuperClassLoc, S);
1153 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
1154 && !isa<ObjcProtocolDecl>(PrevDecl)) {
1155 Diag(SuperClassLoc, diag::err_redefinition_different_kind,
1156 SuperClassname->getName());
1157 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1158 }
1159 else {
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001160 SDecl = getObjCInterfaceDecl(SuperClassname);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001161 if (!SDecl)
1162 Diag(SuperClassLoc, diag::err_undef_superclass,
1163 SuperClassname->getName(), ClassName->getName());
1164 else if (IDecl && IDecl->getSuperClass() != SDecl) {
1165 // This implementation and its interface do not have the same
1166 // super class.
1167 Diag(SuperClassLoc, diag::err_conflicting_super_class,
1168 SuperClassname->getName());
1169 Diag(SDecl->getLocation(), diag::err_previous_definition);
1170 }
1171 }
1172 }
1173
1174 ObjcImplementationDecl* IMPDecl =
1175 new ObjcImplementationDecl(AtClassImplLoc, ClassName, SDecl);
Fariborz Jahanian0da1c102007-09-25 21:00:20 +00001176 if (!IDecl) {
1177 // Legacy case of @implementation with no corresponding @interface.
1178 // Build, chain & install the interface decl into the identifier.
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001179 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, ClassName);
Fariborz Jahanian0da1c102007-09-25 21:00:20 +00001180 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
1181 ClassName->setFETokenInfo(IDecl);
1182
1183 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001184
1185 // Check that there is no duplicate implementation of this class.
Chris Lattnerf3876682007-10-07 01:13:46 +00001186 if (!ObjcImplementations.insert(ClassName))
1187 Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001188
1189 return IMPDecl;
1190}
1191
Steve Naroffa5997c42007-10-02 21:43:37 +00001192void Sema::CheckImplementationIvars(ObjcImplementationDecl *ImpDecl,
1193 ObjcIvarDecl **ivars, unsigned numIvars) {
1194 assert(ImpDecl && "missing implementation decl");
1195 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ImpDecl->getIdentifier());
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001196 /// 2nd check is added to accomodate case of non-existing @interface decl.
1197 /// (legacy objective-c @implementation decl without an @interface decl).
1198 if (!IDecl || IDecl->ImplicitInterfaceDecl())
Steve Naroffa5997c42007-10-02 21:43:37 +00001199 return;
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001200 assert(ivars && "missing @implementation ivars");
1201
Steve Naroffa5997c42007-10-02 21:43:37 +00001202 // Check interface's Ivar list against those in the implementation.
1203 // names and types must match.
1204 //
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001205 ObjcIvarDecl** IntfIvars = IDecl->getIntfDeclIvars();
1206 int IntfNumIvars = IDecl->getIntfDeclNumIvars();
1207 unsigned j = 0;
1208 bool err = false;
1209 while (numIvars > 0 && IntfNumIvars > 0) {
1210 ObjcIvarDecl* ImplIvar = ivars[j];
1211 ObjcIvarDecl* ClsIvar = IntfIvars[j++];
1212 assert (ImplIvar && "missing implementation ivar");
1213 assert (ClsIvar && "missing class ivar");
1214 if (ImplIvar->getCanonicalType() != ClsIvar->getCanonicalType()) {
1215 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
1216 ImplIvar->getIdentifier()->getName());
1217 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1218 ClsIvar->getIdentifier()->getName());
1219 }
1220 // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
1221 // as error.
1222 else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1223 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
1224 ImplIvar->getIdentifier()->getName());
1225 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1226 ClsIvar->getIdentifier()->getName());
1227 err = true;
1228 break;
1229 }
1230 --numIvars;
1231 --IntfNumIvars;
1232 }
1233 if (!err && (numIvars > 0 || IntfNumIvars > 0))
1234 Diag(numIvars > 0 ? ivars[j]->getLocation() : IntfIvars[j]->getLocation(),
1235 diag::err_inconsistant_ivar);
1236
1237}
1238
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001239/// CheckProtocolMethodDefs - This routine checks unimpletented methods
1240/// Declared in protocol, and those referenced by it.
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001241void Sema::CheckProtocolMethodDefs(ObjcProtocolDecl *PDecl,
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001242 bool& IncompleteImpl,
Steve Naroffeefc4182007-10-08 21:05:34 +00001243 const llvm::DenseSet<Selector> &InsMap,
Chris Lattner85994262007-10-05 20:15:24 +00001244 const llvm::DenseSet<Selector> &ClsMap) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001245 // check unimplemented instance methods.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001246 ObjcMethodDecl** methods = PDecl->getInstanceMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001247 for (int j = 0; j < PDecl->getNumInstanceMethods(); j++) {
Steve Naroffeefc4182007-10-08 21:05:34 +00001248 if (!InsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001249 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001250 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001251 IncompleteImpl = true;
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001252 }
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001253 }
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001254 // check unimplemented class methods
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001255 methods = PDecl->getClassMethods();
1256 for (int j = 0; j < PDecl->getNumClassMethods(); j++)
Chris Lattner85994262007-10-05 20:15:24 +00001257 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001258 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001259 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001260 IncompleteImpl = true;
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001261 }
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001262
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001263 // Check on this protocols's referenced protocols, recursively
1264 ObjcProtocolDecl** RefPDecl = PDecl->getReferencedProtocols();
1265 for (int i = 0; i < PDecl->getNumReferencedProtocols(); i++)
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001266 CheckProtocolMethodDefs(RefPDecl[i], IncompleteImpl, InsMap, ClsMap);
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001267}
1268
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001269void Sema::ImplMethodsVsClassMethods(ObjcImplementationDecl* IMPDecl,
1270 ObjcInterfaceDecl* IDecl) {
Steve Naroffeefc4182007-10-08 21:05:34 +00001271 llvm::DenseSet<Selector> InsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001272 // Check and see if instance methods in class interface have been
1273 // implemented in the implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001274 ObjcMethodDecl **methods = IMPDecl->getInstanceMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001275 for (int i=0; i < IMPDecl->getNumInstanceMethods(); i++)
Steve Naroffeefc4182007-10-08 21:05:34 +00001276 InsMap.insert(methods[i]->getSelector());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001277
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001278 bool IncompleteImpl = false;
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001279 methods = IDecl->getInstanceMethods();
1280 for (int j = 0; j < IDecl->getNumInstanceMethods(); j++)
Steve Naroffeefc4182007-10-08 21:05:34 +00001281 if (!InsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001282 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001283 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001284 IncompleteImpl = true;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001285 }
Chris Lattner85994262007-10-05 20:15:24 +00001286 llvm::DenseSet<Selector> ClsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001287 // Check and see if class methods in class interface have been
1288 // implemented in the implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001289 methods = IMPDecl->getClassMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001290 for (int i=0; i < IMPDecl->getNumClassMethods(); i++)
Chris Lattner85994262007-10-05 20:15:24 +00001291 ClsMap.insert(methods[i]->getSelector());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001292
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001293 methods = IDecl->getClassMethods();
1294 for (int j = 0; j < IDecl->getNumClassMethods(); j++)
Chris Lattner85994262007-10-05 20:15:24 +00001295 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001296 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001297 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001298 IncompleteImpl = true;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001299 }
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001300
1301 // Check the protocol list for unimplemented methods in the @implementation
1302 // class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001303 ObjcProtocolDecl** protocols = IDecl->getReferencedProtocols();
Chris Lattner85994262007-10-05 20:15:24 +00001304 for (int i = 0; i < IDecl->getNumIntfRefProtocols(); i++)
1305 CheckProtocolMethodDefs(protocols[i], IncompleteImpl, InsMap, ClsMap);
1306
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001307 if (IncompleteImpl)
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001308 Diag(IMPDecl->getLocation(), diag::warn_incomplete_impl_class,
1309 IMPDecl->getName());
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001310}
1311
1312/// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
1313/// category interface is implemented in the category @implementation.
1314void Sema::ImplCategoryMethodsVsIntfMethods(ObjcCategoryImplDecl *CatImplDecl,
1315 ObjcCategoryDecl *CatClassDecl) {
Steve Naroffeefc4182007-10-08 21:05:34 +00001316 llvm::DenseSet<Selector> InsMap;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001317 // Check and see if instance methods in category interface have been
1318 // implemented in its implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001319 ObjcMethodDecl **methods = CatImplDecl->getInstanceMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001320 for (int i=0; i < CatImplDecl->getNumInstanceMethods(); i++)
Steve Naroffeefc4182007-10-08 21:05:34 +00001321 InsMap.insert(methods[i]->getSelector());
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001322
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001323 bool IncompleteImpl = false;
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001324 methods = CatClassDecl->getInstanceMethods();
1325 for (int j = 0; j < CatClassDecl->getNumInstanceMethods(); j++)
Steve Naroffeefc4182007-10-08 21:05:34 +00001326 if (!InsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001327 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001328 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001329 IncompleteImpl = true;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001330 }
Chris Lattner85994262007-10-05 20:15:24 +00001331 llvm::DenseSet<Selector> ClsMap;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001332 // Check and see if class methods in category interface have been
1333 // implemented in its implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001334 methods = CatImplDecl->getClassMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001335 for (int i=0; i < CatImplDecl->getNumClassMethods(); i++)
Chris Lattner85994262007-10-05 20:15:24 +00001336 ClsMap.insert(methods[i]->getSelector());
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001337
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001338 methods = CatClassDecl->getClassMethods();
1339 for (int j = 0; j < CatClassDecl->getNumClassMethods(); j++)
Chris Lattner85994262007-10-05 20:15:24 +00001340 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001341 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001342 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001343 IncompleteImpl = true;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001344 }
1345
1346 // Check the protocol list for unimplemented methods in the @implementation
1347 // class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001348 ObjcProtocolDecl** protocols = CatClassDecl->getReferencedProtocols();
1349 for (int i = 0; i < CatClassDecl->getNumReferencedProtocols(); i++) {
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001350 ObjcProtocolDecl* PDecl = protocols[i];
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001351 CheckProtocolMethodDefs(PDecl, IncompleteImpl, InsMap, ClsMap);
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001352 }
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001353 if (IncompleteImpl)
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001354 Diag(CatImplDecl->getLocation(), diag::warn_incomplete_impl_category,
Chris Lattnerfd5de472007-10-06 22:53:46 +00001355 CatClassDecl->getName());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001356}
1357
Steve Naroff37e58d12007-10-02 22:39:18 +00001358/// ActOnForwardClassDeclaration -
Steve Naroff3536b442007-09-06 21:24:23 +00001359/// Scope will always be top level file scope.
1360Action::DeclTy *
Steve Naroff37e58d12007-10-02 22:39:18 +00001361Sema::ActOnForwardClassDeclaration(Scope *S, SourceLocation AtClassLoc,
1362 IdentifierInfo **IdentList, unsigned NumElts)
1363{
Chris Lattner7e620722007-10-06 20:08:36 +00001364 llvm::SmallVector<ObjcInterfaceDecl*, 32> Interfaces;
1365
Steve Naroff3536b442007-09-06 21:24:23 +00001366 for (unsigned i = 0; i != NumElts; ++i) {
Chris Lattner7e620722007-10-06 20:08:36 +00001367 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(IdentList[i]);
1368 if (!IDecl) { // Not already seen? Make a forward decl.
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001369 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, IdentList[i], true);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001370 // Chain & install the interface decl into the identifier.
1371 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1372 IdentList[i]->setFETokenInfo(IDecl);
Chris Lattner60c52182007-10-07 07:05:08 +00001373
1374 // Remember that this needs to be removed when the scope is popped.
1375 S->AddDecl(IDecl);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001376 }
Chris Lattner7e620722007-10-06 20:08:36 +00001377
1378 Interfaces.push_back(IDecl);
Steve Naroff3536b442007-09-06 21:24:23 +00001379 }
Chris Lattner7e620722007-10-06 20:08:36 +00001380
1381 return new ObjcClassDecl(AtClassLoc, &Interfaces[0], Interfaces.size());
Steve Naroff3536b442007-09-06 21:24:23 +00001382}
1383
Reid Spencer5f016e22007-07-11 17:01:13 +00001384
Steve Naroff08d92e42007-09-15 18:49:24 +00001385/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001386/// former case, Name will be non-null. In the later case, Name will be null.
1387/// TagType indicates what kind of tag this is. TK indicates whether this is a
1388/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001389Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 SourceLocation KWLoc, IdentifierInfo *Name,
1391 SourceLocation NameLoc, AttributeList *Attr) {
1392 // If this is a use of an existing tag, it must have a name.
1393 assert((Name != 0 || TK == TK_Definition) &&
1394 "Nameless record must be a definition!");
1395
1396 Decl::Kind Kind;
1397 switch (TagType) {
1398 default: assert(0 && "Unknown tag type!");
1399 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1400 case DeclSpec::TST_union: Kind = Decl::Union; break;
1401//case DeclSpec::TST_class: Kind = Decl::Class; break;
1402 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1403 }
1404
1405 // If this is a named struct, check to see if there was a previous forward
1406 // declaration or definition.
1407 if (TagDecl *PrevDecl =
1408 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1409 NameLoc, S))) {
1410
1411 // If this is a use of a previous tag, or if the tag is already declared in
1412 // the same scope (so that the definition/declaration completes or
1413 // rementions the tag), reuse the decl.
1414 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1415 // Make sure that this wasn't declared as an enum and now used as a struct
1416 // or something similar.
1417 if (PrevDecl->getKind() != Kind) {
1418 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1419 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1420 }
1421
1422 // If this is a use or a forward declaration, we're good.
1423 if (TK != TK_Definition)
1424 return PrevDecl;
1425
1426 // Diagnose attempts to redefine a tag.
1427 if (PrevDecl->isDefinition()) {
1428 Diag(NameLoc, diag::err_redefinition, Name->getName());
1429 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1430 // If this is a redefinition, recover by making this struct be
1431 // anonymous, which will make any later references get the previous
1432 // definition.
1433 Name = 0;
1434 } else {
1435 // Okay, this is definition of a previously declared or referenced tag.
1436 // Move the location of the decl to be the definition site.
1437 PrevDecl->setLocation(NameLoc);
1438 return PrevDecl;
1439 }
1440 }
1441 // If we get here, this is a definition of a new struct type in a nested
1442 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1443 // type.
1444 }
1445
1446 // If there is an identifier, use the location of the identifier as the
1447 // location of the decl, otherwise use the location of the struct/union
1448 // keyword.
1449 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1450
1451 // Otherwise, if this is the first time we've seen this tag, create the decl.
1452 TagDecl *New;
1453 switch (Kind) {
1454 default: assert(0 && "Unknown tag kind!");
1455 case Decl::Enum:
1456 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1457 // enum X { A, B, C } D; D should chain to X.
1458 New = new EnumDecl(Loc, Name, 0);
1459 // If this is an undefined enum, warn.
1460 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1461 break;
1462 case Decl::Union:
1463 case Decl::Struct:
1464 case Decl::Class:
1465 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1466 // struct X { int A; } D; D should chain to X.
1467 New = new RecordDecl(Kind, Loc, Name, 0);
1468 break;
1469 }
1470
1471 // If this has an identifier, add it to the scope stack.
1472 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001473 // The scope passed in may not be a decl scope. Zip up the scope tree until
1474 // we find one that is.
1475 while ((S->getFlags() & Scope::DeclScope) == 0)
1476 S = S->getParent();
1477
1478 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001479 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 Name->setFETokenInfo(New);
1481 S->AddDecl(New);
1482 }
1483
1484 return New;
1485}
1486
Steve Naroff08d92e42007-09-15 18:49:24 +00001487/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001488/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001489Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 SourceLocation DeclStart,
1491 Declarator &D, ExprTy *BitfieldWidth) {
1492 IdentifierInfo *II = D.getIdentifier();
1493 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 SourceLocation Loc = DeclStart;
1495 if (II) Loc = D.getIdentifierLoc();
1496
1497 // FIXME: Unnamed fields can be handled in various different ways, for
1498 // example, unnamed unions inject all members into the struct namespace!
1499
1500
1501 if (BitWidth) {
1502 // TODO: Validate.
1503 //printf("WARNING: BITFIELDS IGNORED!\n");
1504
1505 // 6.7.2.1p3
1506 // 6.7.2.1p4
1507
1508 } else {
1509 // Not a bitfield.
1510
1511 // validate II.
1512
1513 }
1514
1515 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001516 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1517 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001518
Reid Spencer5f016e22007-07-11 17:01:13 +00001519 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1520 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001521 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1522 Diag(Loc, diag::err_typecheck_illegal_vla,
1523 VAT->getSizeExpr()->getSourceRange());
1524 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001527 FieldDecl *NewFD;
1528
1529 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001530 NewFD = new FieldDecl(Loc, II, T);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001531 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl))
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001532 || isa<ObjcImplementationDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001533 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001534 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001535 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001536
Steve Naroff5912a352007-08-28 20:14:24 +00001537 if (D.getInvalidType() || InvalidDecl)
1538 NewFD->setInvalidDecl();
1539 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001540}
1541
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001542/// TranslateIvarVisibility - Translate visibility from a token ID to an
1543/// AST enum value.
1544static ObjcIvarDecl::AccessControl
1545TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001546 switch (ivarVisibility) {
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001547 case tok::objc_private: return ObjcIvarDecl::Private;
1548 case tok::objc_public: return ObjcIvarDecl::Public;
1549 case tok::objc_protected: return ObjcIvarDecl::Protected;
1550 case tok::objc_package: return ObjcIvarDecl::Package;
1551 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001552 }
1553}
1554
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001555void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001556 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001557 DeclTy **Fields, unsigned NumFields,
1558 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001559 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1560 assert(EnclosingDecl && "missing record or interface decl");
1561 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1562
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001563 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 // Diagnose code like:
1565 // struct S { struct S {} X; };
1566 // We discover this when we complete the outer S. Reject and ignore the
1567 // outer S.
1568 Diag(Record->getLocation(), diag::err_nested_redefinition,
1569 Record->getKindName());
1570 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001571 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 return;
1573 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 // Verify that all the fields are okay.
1575 unsigned NumNamedMembers = 0;
1576 llvm::SmallVector<FieldDecl*, 32> RecFields;
1577 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001578
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001580
Steve Naroff74216642007-09-14 22:20:54 +00001581 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1582 assert(FD && "missing field decl");
1583
1584 // Remember all fields.
1585 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001586
1587 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001588 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001589
Steve Narofff13271f2007-09-14 23:09:53 +00001590 // If we have visibility info, make sure the AST is set accordingly.
1591 if (visibility)
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001592 cast<ObjcIvarDecl>(FD)->setAccessControl(
1593 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001594
Reid Spencer5f016e22007-07-11 17:01:13 +00001595 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001596 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001597 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001598 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001599 FD->setInvalidDecl();
1600 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001601 continue;
1602 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001603 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1604 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001605 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001606 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001607 FD->setInvalidDecl();
1608 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001609 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001610 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 if (i != NumFields-1 || // ... that the last member ...
1612 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001613 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001614 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001615 FD->setInvalidDecl();
1616 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001617 continue;
1618 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001619 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001620 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1621 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001622 FD->setInvalidDecl();
1623 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 continue;
1625 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001627 if (Record)
1628 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001629 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1631 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001632 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1634 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001635 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001636 Record->setHasFlexibleArrayMember(true);
1637 } else {
1638 // If this is a struct/class and this is not the last element, reject
1639 // it. Note that GCC supports variable sized arrays in the middle of
1640 // structures.
1641 if (i != NumFields-1) {
1642 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1643 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001644 FD->setInvalidDecl();
1645 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 continue;
1647 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001648 // We support flexible arrays at the end of structs in other structs
1649 // as an extension.
1650 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1651 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001652 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001653 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001654 }
1655 }
1656 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001657 // Keep track of the number of named members.
1658 if (IdentifierInfo *II = FD->getIdentifier()) {
1659 // Detect duplicate member names.
1660 if (!FieldIDs.insert(II)) {
1661 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1662 // Find the previous decl.
1663 SourceLocation PrevLoc;
1664 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1665 assert(i != e && "Didn't find previous def!");
1666 if (RecFields[i]->getIdentifier() == II) {
1667 PrevLoc = RecFields[i]->getLocation();
1668 break;
1669 }
1670 }
1671 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001672 FD->setInvalidDecl();
1673 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 continue;
1675 }
1676 ++NumNamedMembers;
1677 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001678 }
1679
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 // Okay, we successfully defined 'Record'.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001681 if (Record)
1682 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001683 else {
1684 ObjcIvarDecl **ClsFields =
1685 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001686 if (isa<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1687 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1688 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1689 else if (isa<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1690 ObjcImplementationDecl* IMPDecl =
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001691 cast<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl));
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001692 assert(IMPDecl && "ActOnFields - missing ObjcImplementationDecl");
1693 IMPDecl->ObjcAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Steve Naroffa5997c42007-10-02 21:43:37 +00001694 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size());
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001695 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001696 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001697}
1698
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001699/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1700/// returns true, or false, accordingly.
1701/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1702bool Sema:: MatchTwoMethodDeclarations(const ObjcMethodDecl *Method,
1703 const ObjcMethodDecl *PrevMethod) {
1704 if (Method->getMethodType().getCanonicalType() !=
1705 PrevMethod->getMethodType().getCanonicalType())
1706 return false;
1707 for (int i = 0; i < Method->getNumParams(); i++) {
1708 ParmVarDecl *ParamDecl = Method->getParamDecl(i);
1709 ParmVarDecl *PrevParamDecl = PrevMethod->getParamDecl(i);
1710 if (ParamDecl->getCanonicalType() != PrevParamDecl->getCanonicalType())
1711 return false;
1712 }
1713 return true;
1714}
1715
Chris Lattnerfd5de472007-10-06 22:53:46 +00001716void Sema::ActOnAddMethodsToObjcDecl(Scope* S, DeclTy *classDecl,
Steve Naroff3a165b02007-10-03 21:00:46 +00001717 DeclTy **allMethods, unsigned allNum) {
Chris Lattnerfd5de472007-10-06 22:53:46 +00001718 Decl *ClassDecl = static_cast<Decl *>(classDecl);
1719
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001720 // FIXME: Fix this when we can handle methods declared in protocols.
1721 // See Parser::ParseObjCAtProtocolDeclaration
1722 if (!ClassDecl)
1723 return;
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001724 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1725 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001726
Steve Naroffeefc4182007-10-08 21:05:34 +00001727 llvm::DenseMap<Selector, const ObjcMethodDecl*> InsMap;
1728 llvm::DenseMap<Selector, const ObjcMethodDecl*> ClsMap;
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001729
1730 bool isClassDeclaration =
Chris Lattnerfd5de472007-10-06 22:53:46 +00001731 (isa<ObjcInterfaceDecl>(ClassDecl) || isa<ObjcCategoryDecl>(ClassDecl));
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001732
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001733 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001734 ObjcMethodDecl *Method =
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001735 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1736 if (!Method) continue; // Already issued a diagnostic.
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001737 if (Method->isInstance()) {
1738 if (isClassDeclaration) {
1739 /// Check for instance method of the same name with incompatible types
Steve Naroffeefc4182007-10-08 21:05:34 +00001740 const ObjcMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001741 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001742 Diag(Method->getLocation(), diag::error_duplicate_method_decl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001743 Method->getSelector().getName());
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001744 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
1745 }
1746 else {
1747 insMethods.push_back(Method);
Steve Naroffeefc4182007-10-08 21:05:34 +00001748 InsMap[Method->getSelector()] = Method;
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001749 }
1750 }
1751 else
1752 insMethods.push_back(Method);
1753 }
1754 else {
1755 if (isClassDeclaration) {
1756 /// Check for class method of the same name with incompatible types
Steve Naroffeefc4182007-10-08 21:05:34 +00001757 const ObjcMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001758 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001759 Diag(Method->getLocation(), diag::error_duplicate_method_decl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001760 Method->getSelector().getName());
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001761 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
1762 }
1763 else {
1764 clsMethods.push_back(Method);
Steve Naroffeefc4182007-10-08 21:05:34 +00001765 ClsMap[Method->getSelector()] = Method;
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001766 }
1767 }
1768 else
1769 clsMethods.push_back(Method);
1770 }
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001771 }
Chris Lattnerfd5de472007-10-06 22:53:46 +00001772
1773 if (ObjcInterfaceDecl *I = dyn_cast<ObjcInterfaceDecl>(ClassDecl)) {
1774 I->ObjcAddMethods(&insMethods[0], insMethods.size(),
1775 &clsMethods[0], clsMethods.size());
1776 } else if (ObjcProtocolDecl *P = dyn_cast<ObjcProtocolDecl>(ClassDecl)) {
1777 P->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1778 &clsMethods[0], clsMethods.size());
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001779 }
Chris Lattnerfd5de472007-10-06 22:53:46 +00001780 else if (ObjcCategoryDecl *C = dyn_cast<ObjcCategoryDecl>(ClassDecl)) {
1781 C->ObjcAddCatMethods(&insMethods[0], insMethods.size(),
1782 &clsMethods[0], clsMethods.size());
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001783 }
Chris Lattnerfd5de472007-10-06 22:53:46 +00001784 else if (ObjcImplementationDecl *IC =
1785 dyn_cast<ObjcImplementationDecl>(ClassDecl)) {
1786 IC->ObjcAddImplMethods(&insMethods[0], insMethods.size(),
1787 &clsMethods[0], clsMethods.size());
1788 if (ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(IC->getIdentifier()))
1789 ImplMethodsVsClassMethods(IC, IDecl);
1790 } else {
1791 ObjcCategoryImplDecl* CatImplClass = cast<ObjcCategoryImplDecl>(ClassDecl);
1792 CatImplClass->ObjcAddCatImplMethods(&insMethods[0], insMethods.size(),
1793 &clsMethods[0], clsMethods.size());
1794 ObjcInterfaceDecl* IDecl = CatImplClass->getClassInterface();
1795 // Find category interface decl and then check that all methods declared
1796 // in this interface is implemented in the category @implementation.
1797 if (IDecl) {
1798 for (ObjcCategoryDecl *Categories = IDecl->getListCategories();
1799 Categories; Categories = Categories->getNextClassCategory()) {
Chris Lattner6a0e89e2007-10-06 23:12:31 +00001800 if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
Chris Lattnerfd5de472007-10-06 22:53:46 +00001801 ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
1802 break;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001803 }
1804 }
1805 }
1806 }
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001807}
1808
Steve Naroff37e58d12007-10-02 22:39:18 +00001809Sema::DeclTy *Sema::ActOnMethodDeclaration(SourceLocation MethodLoc,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001810 tok::TokenKind MethodType, TypeTy *ReturnType, Selector Sel,
Steve Naroff68d331a2007-09-27 14:38:14 +00001811 // optional arguments. The number of types/arguments is obtained
1812 // from the Sel.getNumArgs().
1813 TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1814 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001815 llvm::SmallVector<ParmVarDecl*, 16> Params;
1816
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001817 for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001818 // FIXME: arg->AttrList must be stored too!
Steve Naroff68d331a2007-09-27 14:38:14 +00001819 ParmVarDecl* Param = new ParmVarDecl(SourceLocation(/*FIXME*/), ArgNames[i],
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001820 QualType::getFromOpaquePtr(ArgTypes[i]),
1821 VarDecl::None, 0);
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001822 Params.push_back(Param);
1823 }
1824 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Steve Naroff68d331a2007-09-27 14:38:14 +00001825 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc, Sel,
1826 resultDeclType, 0, -1, AttrList,
Fariborz Jahanian3a63da72007-09-29 18:24:58 +00001827 MethodType == tok::minus,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001828 MethodDeclKind == tok::objc_optional ?
1829 ObjcMethodDecl::Optional :
1830 ObjcMethodDecl::Required);
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001831 ObjcMethod->setMethodParams(&Params[0], Sel.getNumArgs());
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001832 return ObjcMethod;
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001833}
1834
Steve Naroff08d92e42007-09-15 18:49:24 +00001835Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001836 DeclTy *lastEnumConst,
1837 SourceLocation IdLoc, IdentifierInfo *Id,
1838 SourceLocation EqualLoc, ExprTy *val) {
1839 theEnumDecl = theEnumDecl; // silence unused warning.
1840 EnumConstantDecl *LastEnumConst =
1841 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1842 Expr *Val = static_cast<Expr*>(val);
1843
Chris Lattner31e05722007-08-26 06:24:45 +00001844 // The scope passed in may not be a decl scope. Zip up the scope tree until
1845 // we find one that is.
1846 while ((S->getFlags() & Scope::DeclScope) == 0)
1847 S = S->getParent();
1848
Reid Spencer5f016e22007-07-11 17:01:13 +00001849 // Verify that there isn't already something declared with this name in this
1850 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001851 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1852 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001853 if (S->isDeclScope(PrevDecl)) {
1854 if (isa<EnumConstantDecl>(PrevDecl))
1855 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1856 else
1857 Diag(IdLoc, diag::err_redefinition, Id->getName());
1858 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1859 // FIXME: Don't leak memory: delete Val;
1860 return 0;
1861 }
1862 }
1863
1864 llvm::APSInt EnumVal(32);
1865 QualType EltTy;
1866 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001867 // Make sure to promote the operand type to int.
1868 UsualUnaryConversions(Val);
1869
Reid Spencer5f016e22007-07-11 17:01:13 +00001870 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1871 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001872 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001873 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1874 Id->getName());
1875 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001876 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001877 } else {
1878 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001879 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001880 }
1881
1882 if (!Val) {
1883 if (LastEnumConst) {
1884 // Assign the last value + 1.
1885 EnumVal = LastEnumConst->getInitVal();
1886 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001887
1888 // Check for overflow on increment.
1889 if (EnumVal < LastEnumConst->getInitVal())
1890 Diag(IdLoc, diag::warn_enum_value_overflow);
1891
Chris Lattnerb7416f92007-08-27 17:37:24 +00001892 EltTy = LastEnumConst->getType();
1893 } else {
1894 // First value, set to zero.
1895 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001896 EnumVal.zextOrTrunc(
1897 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001898 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 }
1900
Reid Spencer5f016e22007-07-11 17:01:13 +00001901 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1902 LastEnumConst);
1903
1904 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001905 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001906 Id->setFETokenInfo(New);
1907 S->AddDecl(New);
1908 return New;
1909}
1910
Steve Naroff08d92e42007-09-15 18:49:24 +00001911void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001912 DeclTy **Elements, unsigned NumElements) {
1913 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1914 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1915
Chris Lattnere37f0be2007-08-28 05:10:31 +00001916 // TODO: If the result value doesn't fit in an int, it must be a long or long
1917 // long value. ISO C does not support this, but GCC does as an extension,
1918 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001919 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001920
1921
Chris Lattnerac609682007-08-28 06:15:15 +00001922 // Verify that all the values are okay, compute the size of the values, and
1923 // reverse the list.
1924 unsigned NumNegativeBits = 0;
1925 unsigned NumPositiveBits = 0;
1926
1927 // Keep track of whether all elements have type int.
1928 bool AllElementsInt = true;
1929
Reid Spencer5f016e22007-07-11 17:01:13 +00001930 EnumConstantDecl *EltList = 0;
1931 for (unsigned i = 0; i != NumElements; ++i) {
1932 EnumConstantDecl *ECD =
1933 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1934 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001935
1936 // If the enum value doesn't fit in an int, emit an extension warning.
1937 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1938 "Should have promoted value to int");
1939 const llvm::APSInt &InitVal = ECD->getInitVal();
1940 if (InitVal.getBitWidth() > IntWidth) {
1941 llvm::APSInt V(InitVal);
1942 V.trunc(IntWidth);
1943 V.extend(InitVal.getBitWidth());
1944 if (V != InitVal)
1945 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1946 InitVal.toString());
1947 }
Chris Lattnerac609682007-08-28 06:15:15 +00001948
1949 // Keep track of the size of positive and negative values.
1950 if (InitVal.isUnsigned() || !InitVal.isNegative())
1951 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1952 else
1953 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001954
Chris Lattnerac609682007-08-28 06:15:15 +00001955 // Keep track of whether every enum element has type int (very commmon).
1956 if (AllElementsInt)
1957 AllElementsInt = ECD->getType() == Context.IntTy;
1958
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 ECD->setNextDeclarator(EltList);
1960 EltList = ECD;
1961 }
1962
Chris Lattnerac609682007-08-28 06:15:15 +00001963 // Figure out the type that should be used for this enum.
1964 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1965 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001966 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001967
1968 if (NumNegativeBits) {
1969 // If there is a negative value, figure out the smallest integer type (of
1970 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001971 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001972 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001973 BestWidth = IntWidth;
1974 } else {
1975 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1976 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001977 BestType = Context.LongTy;
1978 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001979 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1980 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001981 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1982 BestType = Context.LongLongTy;
1983 }
1984 }
1985 } else {
1986 // If there is no negative value, figure out which of uint, ulong, ulonglong
1987 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001988 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001989 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001990 BestWidth = IntWidth;
1991 } else if (NumPositiveBits <=
1992 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001993 BestType = Context.UnsignedLongTy;
1994 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001995 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1996 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001997 "How could an initializer get larger than ULL?");
1998 BestType = Context.UnsignedLongLongTy;
1999 }
2000 }
2001
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002002 // Loop over all of the enumerator constants, changing their types to match
2003 // the type of the enum if needed.
2004 for (unsigned i = 0; i != NumElements; ++i) {
2005 EnumConstantDecl *ECD =
2006 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2007 if (!ECD) continue; // Already issued a diagnostic.
2008
2009 // Standard C says the enumerators have int type, but we allow, as an
2010 // extension, the enumerators to be larger than int size. If each
2011 // enumerator value fits in an int, type it as an int, otherwise type it the
2012 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2013 // that X has type 'int', not 'unsigned'.
2014 if (ECD->getType() == Context.IntTy)
2015 continue; // Already int type.
2016
2017 // Determine whether the value fits into an int.
2018 llvm::APSInt InitVal = ECD->getInitVal();
2019 bool FitsInInt;
2020 if (InitVal.isUnsigned() || !InitVal.isNegative())
2021 FitsInInt = InitVal.getActiveBits() < IntWidth;
2022 else
2023 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2024
2025 // If it fits into an integer type, force it. Otherwise force it to match
2026 // the enum decl type.
2027 QualType NewTy;
2028 unsigned NewWidth;
2029 bool NewSign;
2030 if (FitsInInt) {
2031 NewTy = Context.IntTy;
2032 NewWidth = IntWidth;
2033 NewSign = true;
2034 } else if (ECD->getType() == BestType) {
2035 // Already the right type!
2036 continue;
2037 } else {
2038 NewTy = BestType;
2039 NewWidth = BestWidth;
2040 NewSign = BestType->isSignedIntegerType();
2041 }
2042
2043 // Adjust the APSInt value.
2044 InitVal.extOrTrunc(NewWidth);
2045 InitVal.setIsSigned(NewSign);
2046 ECD->setInitVal(InitVal);
2047
2048 // Adjust the Expr initializer and type.
2049 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2050 ECD->setType(NewTy);
2051 }
Chris Lattnerac609682007-08-28 06:15:15 +00002052
Chris Lattnere00b18c2007-08-28 18:24:31 +00002053 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00002054}
2055
2056void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
2057 if (!current) return;
2058
2059 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
2060 // remember this in the LastInGroupList list.
2061 if (last)
2062 LastInGroupList.push_back((Decl*)last);
2063}
2064
2065void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
2066 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
2067 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2068 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
2069 if (!newType.isNull()) // install the new vector type into the decl
2070 vDecl->setType(newType);
2071 }
2072 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2073 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
2074 rawAttr);
2075 if (!newType.isNull()) // install the new vector type into the decl
2076 tDecl->setUnderlyingType(newType);
2077 }
2078 }
Steve Naroff73322922007-07-18 18:00:27 +00002079 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00002080 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
2081 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
2082 else
Steve Naroff73322922007-07-18 18:00:27 +00002083 Diag(rawAttr->getAttributeLoc(),
2084 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00002085 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002086 // FIXME: add other attributes...
2087}
2088
2089void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2090 AttributeList *declarator_postfix) {
2091 while (declspec_prefix) {
2092 HandleDeclAttribute(New, declspec_prefix);
2093 declspec_prefix = declspec_prefix->getNext();
2094 }
2095 while (declarator_postfix) {
2096 HandleDeclAttribute(New, declarator_postfix);
2097 declarator_postfix = declarator_postfix->getNext();
2098 }
2099}
2100
Steve Naroffbea0b342007-07-29 16:33:31 +00002101void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2102 AttributeList *rawAttr) {
2103 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00002104 // check the attribute arugments.
2105 if (rawAttr->getNumArgs() != 1) {
2106 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2107 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002108 return;
Steve Naroff73322922007-07-18 18:00:27 +00002109 }
2110 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2111 llvm::APSInt vecSize(32);
2112 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
2113 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2114 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002115 return;
Steve Naroff73322922007-07-18 18:00:27 +00002116 }
2117 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2118 // in conjunction with complex types (pointers, arrays, functions, etc.).
2119 Type *canonType = curType.getCanonicalType().getTypePtr();
2120 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2121 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2122 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002123 return;
Steve Naroff73322922007-07-18 18:00:27 +00002124 }
2125 // unlike gcc's vector_size attribute, the size is specified as the
2126 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002127 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002128
2129 if (vectorSize == 0) {
2130 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2131 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002132 return;
Steve Naroff73322922007-07-18 18:00:27 +00002133 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002134 // Instantiate/Install the vector type, the number of elements is > 0.
2135 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2136 // Remember this typedef decl, we will need it later for diagnostics.
2137 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002138}
2139
Reid Spencer5f016e22007-07-11 17:01:13 +00002140QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002141 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002142 // check the attribute arugments.
2143 if (rawAttr->getNumArgs() != 1) {
2144 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2145 std::string("1"));
2146 return QualType();
2147 }
2148 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2149 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002150 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002151 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2152 sizeExpr->getSourceRange());
2153 return QualType();
2154 }
2155 // navigate to the base type - we need to provide for vector pointers,
2156 // vector arrays, and functions returning vectors.
2157 Type *canonType = curType.getCanonicalType().getTypePtr();
2158
Steve Naroff73322922007-07-18 18:00:27 +00002159 if (canonType->isPointerType() || canonType->isArrayType() ||
2160 canonType->isFunctionType()) {
2161 assert(1 && "HandleVector(): Complex type construction unimplemented");
2162 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2163 do {
2164 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2165 canonType = PT->getPointeeType().getTypePtr();
2166 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2167 canonType = AT->getElementType().getTypePtr();
2168 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2169 canonType = FT->getResultType().getTypePtr();
2170 } while (canonType->isPointerType() || canonType->isArrayType() ||
2171 canonType->isFunctionType());
2172 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002173 }
2174 // the base type must be integer or float.
2175 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2176 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2177 curType.getCanonicalType().getAsString());
2178 return QualType();
2179 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00002180 unsigned typeSize = static_cast<unsigned>(
2181 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002182 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002183 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002184
2185 // the vector size needs to be an integral multiple of the type size.
2186 if (vectorSize % typeSize) {
2187 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
2188 sizeExpr->getSourceRange());
2189 return QualType();
2190 }
2191 if (vectorSize == 0) {
2192 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2193 sizeExpr->getSourceRange());
2194 return QualType();
2195 }
2196 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
2197 // the number of elements to be a power of two (unlike GCC).
2198 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00002199 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002200}
2201