blob: f7d8dd8493b7b4015ec7e3910ded94deb0e9dc83 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroff3fafa102007-10-01 19:00:59 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/Type.h"
21#include "clang/Parse/DeclSpec.h"
22#include "clang/Parse/Scope.h"
23#include "clang/Lex/IdentifierTable.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000026#include "llvm/ADT/SmallString.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian67907bd2007-10-05 18:00:57 +000028#include "llvm/ADT/DenseSet.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30
Chris Lattner4b009652007-07-25 00:24:17 +000031Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Chris Lattner3c9e4da2007-09-30 08:31:00 +000032 if (Decl *IIDecl = II.getFETokenInfo<Decl>())
33 if (isa<TypedefDecl>(IIDecl) || isa<ObjcInterfaceDecl>(IIDecl))
34 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000035 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000036}
37
38void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000039 if (S->decl_empty()) return;
40 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
41
Chris Lattner4b009652007-07-25 00:24:17 +000042 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
43 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +000044 Decl *TmpD = static_cast<Decl*>(*I);
45 assert(TmpD && "This decl didn't get pushed??");
46 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
47 assert(D && "This decl isn't a ScopedDecl?");
48
Chris Lattner4b009652007-07-25 00:24:17 +000049 IdentifierInfo *II = D->getIdentifier();
50 if (!II) continue;
51
52 // Unlink this decl from the identifier. Because the scope contains decls
53 // in an unordered collection, and because we have multiple identifier
54 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
55 if (II->getFETokenInfo<Decl>() == D) {
56 // Normal case, no multiple decls in different namespaces.
57 II->setFETokenInfo(D->getNext());
58 } else {
59 // Scan ahead. There are only three namespaces in C, so this loop can
60 // never execute more than 3 times.
Steve Naroffd21bc0d2007-09-13 18:10:37 +000061 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Chris Lattner4b009652007-07-25 00:24:17 +000062 while (SomeDecl->getNext() != D) {
63 SomeDecl = SomeDecl->getNext();
64 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
65 }
66 SomeDecl->setNext(D->getNext());
67 }
68
69 // This will have to be revisited for C++: there we want to nest stuff in
70 // namespace decls etc. Even for C, we might want a top-level translation
71 // unit decl or something.
72 if (!CurFunctionDecl)
73 continue;
74
75 // Chain this decl to the containing function, it now owns the memory for
76 // the decl.
77 D->setNext(CurFunctionDecl->getDeclChain());
78 CurFunctionDecl->setDeclChain(D);
79 }
80}
81
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +000082/// getObjcInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +000083/// return 0 if one not found.
Steve Narofffa465d12007-10-02 20:01:56 +000084ObjcInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
85
86 // Scan up the scope chain looking for a decl that matches this identifier
87 // that is in the appropriate namespace. This search should not take long, as
88 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
89 ScopedDecl *IdDecl = NULL;
90 for (ScopedDecl *D = Id->getFETokenInfo<ScopedDecl>(); D; D = D->getNext()) {
91 if (D->getIdentifierNamespace() == Decl::IDNS_Ordinary) {
92 IdDecl = D;
93 break;
94 }
95 }
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +000096 if (IdDecl && !isa<ObjcInterfaceDecl>(IdDecl))
97 IdDecl = 0;
98 return cast_or_null<ObjcInterfaceDecl>(static_cast<Decl*>(IdDecl));
99}
100
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +0000101/// getObjcProtocolDecl - Look up a for a protocol declaration in the scope.
102/// return 0 if one not found.
103ObjcProtocolDecl *Sema::getObjCProtocolDecl(Scope *S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +0000104 IdentifierInfo *Id,
105 SourceLocation IdLoc) {
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +0000106 // Note that Protocols have their own namespace.
107 ScopedDecl *PrDecl = LookupScopedDecl(Id, Decl::IDNS_Protocol,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +0000108 IdLoc, S);
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +0000109 if (PrDecl && !isa<ObjcProtocolDecl>(PrDecl))
110 PrDecl = 0;
111 return cast_or_null<ObjcProtocolDecl>(static_cast<Decl*>(PrDecl));
112}
113
Chris Lattner4b009652007-07-25 00:24:17 +0000114/// LookupScopedDecl - Look up the inner-most declaration in the specified
115/// namespace.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000116ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
117 SourceLocation IdLoc, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000118 if (II == 0) return 0;
119 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
120
121 // Scan up the scope chain looking for a decl that matches this identifier
122 // that is in the appropriate namespace. This search should not take long, as
123 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000124 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner4b009652007-07-25 00:24:17 +0000125 if (D->getIdentifierNamespace() == NS)
126 return D;
127
128 // If we didn't find a use of this identifier, and if the identifier
129 // corresponds to a compiler builtin, create the decl object for the builtin
130 // now, injecting it into translation unit scope, and return it.
131 if (NS == Decl::IDNS_Ordinary) {
132 // If this is a builtin on some other target, or if this builtin varies
133 // across targets (e.g. in type), emit a diagnostic and mark the translation
134 // unit non-portable for using it.
135 if (II->isNonPortableBuiltin()) {
136 // Only emit this diagnostic once for this builtin.
137 II->setNonPortableBuiltin(false);
138 Context.Target.DiagnoseNonPortability(IdLoc,
139 diag::port_target_builtin_use);
140 }
141 // If this is a builtin on this (or all) targets, create the decl.
142 if (unsigned BuiltinID = II->getBuiltinID())
143 return LazilyCreateBuiltin(II, BuiltinID, S);
144 }
145 return 0;
146}
147
148/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
149/// lazily create a decl for it.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000150ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000151 Builtin::ID BID = (Builtin::ID)bid;
152
153 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
154 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner987058a2007-08-26 04:02:13 +0000155 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000156
157 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000158 if (Scope *FnS = S->getFnParent())
159 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000160 while (S->getParent())
161 S = S->getParent();
162 S->AddDecl(New);
163
164 // Add this decl to the end of the identifier info.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000165 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000166 // Scan until we find the last (outermost) decl in the id chain.
167 while (LastDecl->getNext())
168 LastDecl = LastDecl->getNext();
169 // Insert before (outside) it.
170 LastDecl->setNext(New);
171 } else {
172 II->setFETokenInfo(New);
173 }
174 // Make sure clients iterating over decls see this.
175 LastInGroupList.push_back(New);
176
177 return New;
178}
179
180/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
181/// and scope as a previous declaration 'Old'. Figure out how to resolve this
182/// situation, merging decls or emitting diagnostics as appropriate.
183///
Steve Naroffcb597472007-09-13 21:41:19 +0000184TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000185 // Verify the old decl was also a typedef.
186 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
187 if (!Old) {
188 Diag(New->getLocation(), diag::err_redefinition_different_kind,
189 New->getName());
190 Diag(OldD->getLocation(), diag::err_previous_definition);
191 return New;
192 }
193
194 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
195 // TODO: This is totally simplistic. It should handle merging functions
196 // together etc, merging extern int X; int X; ...
197 Diag(New->getLocation(), diag::err_redefinition, New->getName());
198 Diag(Old->getLocation(), diag::err_previous_definition);
199 return New;
200}
201
202/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
203/// and scope as a previous declaration 'Old'. Figure out how to resolve this
204/// situation, merging decls or emitting diagnostics as appropriate.
205///
Steve Naroffcb597472007-09-13 21:41:19 +0000206FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000207 // Verify the old decl was also a function.
208 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
209 if (!Old) {
210 Diag(New->getLocation(), diag::err_redefinition_different_kind,
211 New->getName());
212 Diag(OldD->getLocation(), diag::err_previous_definition);
213 return New;
214 }
215
216 // This is not right, but it's a start. If 'Old' is a function prototype with
217 // the same type as 'New', silently allow this. FIXME: We should link up decl
218 // objects here.
219 if (Old->getBody() == 0 &&
220 Old->getCanonicalType() == New->getCanonicalType()) {
221 return New;
222 }
223
224 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
225 // TODO: This is totally simplistic. It should handle merging functions
226 // together etc, merging extern int X; int X; ...
227 Diag(New->getLocation(), diag::err_redefinition, New->getName());
228 Diag(Old->getLocation(), diag::err_previous_definition);
229 return New;
230}
231
232/// MergeVarDecl - We just parsed a variable 'New' which has the same name
233/// and scope as a previous declaration 'Old'. Figure out how to resolve this
234/// situation, merging decls or emitting diagnostics as appropriate.
235///
236/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
237/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
238///
Steve Naroffcb597472007-09-13 21:41:19 +0000239VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000240 // Verify the old decl was also a variable.
241 VarDecl *Old = dyn_cast<VarDecl>(OldD);
242 if (!Old) {
243 Diag(New->getLocation(), diag::err_redefinition_different_kind,
244 New->getName());
245 Diag(OldD->getLocation(), diag::err_previous_definition);
246 return New;
247 }
Steve Naroff83c13012007-08-30 01:06:46 +0000248 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
249 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
250 bool OldIsTentative = false;
251
252 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
253 // Handle C "tentative" external object definitions. FIXME: finish!
254 if (!OldFSDecl->getInit() &&
255 (OldFSDecl->getStorageClass() == VarDecl::None ||
256 OldFSDecl->getStorageClass() == VarDecl::Static))
257 OldIsTentative = true;
258 }
Chris Lattner4b009652007-07-25 00:24:17 +0000259 // Verify the types match.
260 if (Old->getCanonicalType() != New->getCanonicalType()) {
261 Diag(New->getLocation(), diag::err_redefinition, New->getName());
262 Diag(Old->getLocation(), diag::err_previous_definition);
263 return New;
264 }
265 // We've verified the types match, now check if Old is "extern".
266 if (Old->getStorageClass() != VarDecl::Extern) {
267 Diag(New->getLocation(), diag::err_redefinition, New->getName());
268 Diag(Old->getLocation(), diag::err_previous_definition);
269 }
270 return New;
271}
272
273/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
274/// no declarator (e.g. "struct foo;") is parsed.
275Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
276 // TODO: emit error on 'int;' or 'const enum foo;'.
277 // TODO: emit error on 'typedef int;'
278 // if (!DS.isMissingDeclaratorOk()) Diag(...);
279
280 return 0;
281}
282
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000283bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000284 AssignmentCheckResult result;
285 SourceLocation loc = Init->getLocStart();
286 // Get the type before calling CheckSingleAssignmentConstraints(), since
287 // it can promote the expression.
288 QualType rhsType = Init->getType();
289
290 result = CheckSingleAssignmentConstraints(DeclType, Init);
291
292 // decode the result (notice that extensions still return a type).
293 switch (result) {
294 case Compatible:
295 break;
296 case Incompatible:
Steve Naroff9091f3f2007-09-02 15:34:30 +0000297 // FIXME: tighten up this check which should allow:
298 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
299 if (rhsType == Context.getPointerType(Context.CharTy))
300 break;
Steve Naroffe14e5542007-09-02 02:04:30 +0000301 Diag(loc, diag::err_typecheck_assign_incompatible,
302 DeclType.getAsString(), rhsType.getAsString(),
303 Init->getSourceRange());
304 return true;
305 case PointerFromInt:
306 // check for null pointer constant (C99 6.3.2.3p3)
307 if (!Init->isNullPointerConstant(Context)) {
308 Diag(loc, diag::ext_typecheck_assign_pointer_int,
309 DeclType.getAsString(), rhsType.getAsString(),
310 Init->getSourceRange());
311 return true;
312 }
313 break;
314 case IntFromPointer:
315 Diag(loc, diag::ext_typecheck_assign_pointer_int,
316 DeclType.getAsString(), rhsType.getAsString(),
317 Init->getSourceRange());
318 break;
319 case IncompatiblePointer:
320 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
321 DeclType.getAsString(), rhsType.getAsString(),
322 Init->getSourceRange());
323 break;
324 case CompatiblePointerDiscardsQualifiers:
325 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
326 DeclType.getAsString(), rhsType.getAsString(),
327 Init->getSourceRange());
328 break;
329 }
330 return false;
331}
332
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000333bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
334 bool isStatic, QualType ElementType) {
Steve Naroff509d0b52007-09-04 02:20:04 +0000335 SourceLocation loc;
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000336 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff509d0b52007-09-04 02:20:04 +0000337
338 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
339 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
340 return true;
341 } else if (CheckSingleInitializer(expr, ElementType)) {
342 return true; // types weren't compatible.
343 }
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000344 if (savExpr != expr) // The type was promoted, update initializer list.
345 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000346 return false;
347}
348
349void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
350 QualType ElementType, bool isStatic,
351 int &nInitializers, bool &hadError) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000352 for (unsigned i = 0; i < IList->getNumInits(); i++) {
353 Expr *expr = IList->getInit(i);
354
Steve Naroff509d0b52007-09-04 02:20:04 +0000355 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
356 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000357 int maxElements = CAT->getMaximumElements();
Steve Naroff509d0b52007-09-04 02:20:04 +0000358 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
359 maxElements, hadError);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000360 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000361 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000362 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000363 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000364 nInitializers++;
365 }
366 return;
367}
368
369// FIXME: Doesn't deal with arrays of structures yet.
370void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
371 QualType ElementType, bool isStatic,
372 int &totalInits, bool &hadError) {
373 int maxElementsAtThisLevel = 0;
374 int nInitsAtLevel = 0;
375
376 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
377 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff4f910992007-09-04 21:13:33 +0000378 maxElementsAtThisLevel = CAT->getMaximumElements();
379 // Set DeclType, used below to recurse (for multi-dimensional arrays).
380 DeclType = CAT->getElementType();
Steve Naroff509d0b52007-09-04 02:20:04 +0000381 } else if (DeclType->isScalarType()) {
382 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
383 IList->getSourceRange());
384 maxElementsAtThisLevel = 1;
385 }
386 // The empty init list "{ }" is treated specially below.
387 unsigned numInits = IList->getNumInits();
388 if (numInits) {
389 for (unsigned i = 0; i < numInits; i++) {
390 Expr *expr = IList->getInit(i);
391
392 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
393 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
394 totalInits, hadError);
395 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000396 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff509d0b52007-09-04 02:20:04 +0000397 nInitsAtLevel++; // increment the number of initializers at this level.
398 totalInits--; // decrement the total number of initializers.
399
400 // Check if we have space for another initializer.
401 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
402 Diag(expr->getLocStart(), diag::warn_excess_initializers,
403 expr->getSourceRange());
404 }
405 }
406 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
407 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
408 } else {
409 // we have an initializer list with no elements.
410 totalInits -= maxElementsAtThisLevel;
411 if (totalInits < 0)
412 Diag(IList->getLocStart(), diag::warn_excess_initializers,
413 IList->getSourceRange());
Steve Naroff9091f3f2007-09-02 15:34:30 +0000414 }
Steve Naroff1c9de712007-09-03 01:24:23 +0000415 return;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000416}
417
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000418bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000419 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroff1c9de712007-09-03 01:24:23 +0000420 if (!InitList)
421 return CheckSingleInitializer(Init, DeclType);
422
Steve Naroffe14e5542007-09-02 02:04:30 +0000423 // We have an InitListExpr, make sure we set the type.
424 Init->setType(DeclType);
Steve Naroff1c9de712007-09-03 01:24:23 +0000425
426 bool hadError = false;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000427
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000428 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
429 // of unknown size ("[]") or an object type that is not a variable array type.
430 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
431 Expr *expr = VAT->getSizeExpr();
Steve Naroff1c9de712007-09-03 01:24:23 +0000432 if (expr)
433 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
434 expr->getSourceRange());
435
Steve Naroff4f910992007-09-04 21:13:33 +0000436 // We have a VariableArrayType with unknown size. Note that only the first
437 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff509d0b52007-09-04 02:20:04 +0000438 int numInits = 0;
Steve Naroff4f910992007-09-04 21:13:33 +0000439 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
440 isStatic, numInits, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000441 if (!hadError) {
442 // Return a new array type from the number of initializers (C99 6.7.8p22).
443 llvm::APSInt ConstVal(32);
Steve Naroff509d0b52007-09-04 02:20:04 +0000444 ConstVal = numInits;
445 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroff1c9de712007-09-03 01:24:23 +0000446 ArrayType::Normal, 0);
447 }
448 return hadError;
449 }
450 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000451 int maxElements = CAT->getMaximumElements();
452 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
453 isStatic, maxElements, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000454 return hadError;
455 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000456 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
457 int maxElements = 1;
458 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
459 hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000460 return hadError;
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000461 }
462 // FIXME: Handle struct/union types.
Steve Naroff1c9de712007-09-03 01:24:23 +0000463 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +0000464}
465
Chris Lattner4b009652007-07-25 00:24:17 +0000466Sema::DeclTy *
Steve Naroff0acc9c92007-09-15 18:49:24 +0000467Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000468 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000469 IdentifierInfo *II = D.getIdentifier();
470
471 // All of these full declarators require an identifier. If it doesn't have
472 // one, the ParsedFreeStandingDeclSpec action should be used.
473 if (II == 0) {
Chris Lattner87492f42007-08-28 06:17:15 +0000474 Diag(D.getDeclSpec().getSourceRange().Begin(),
475 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000476 D.getDeclSpec().getSourceRange(), D.getSourceRange());
477 return 0;
478 }
479
Chris Lattnera7549902007-08-26 06:24:45 +0000480 // The scope passed in may not be a decl scope. Zip up the scope tree until
481 // we find one that is.
482 while ((S->getFlags() & Scope::DeclScope) == 0)
483 S = S->getParent();
484
Chris Lattner4b009652007-07-25 00:24:17 +0000485 // See if this is a redefinition of a variable in the same scope.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000486 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
487 D.getIdentifierLoc(), S);
Chris Lattner4b009652007-07-25 00:24:17 +0000488 if (PrevDecl && !S->isDeclScope(PrevDecl))
489 PrevDecl = 0; // If in outer scope, it isn't the same thing.
490
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000491 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000492 bool InvalidDecl = false;
493
Chris Lattner4b009652007-07-25 00:24:17 +0000494 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner4b009652007-07-25 00:24:17 +0000495 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
496 if (!NewTD) return 0;
497
498 // Handle attributes prior to checking for duplicates in MergeVarDecl
499 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
500 D.getAttributes());
501 // Merge the decl with the existing one if appropriate.
502 if (PrevDecl) {
503 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
504 if (NewTD == 0) return 0;
505 }
506 New = NewTD;
507 if (S->getParent() == 0) {
508 // C99 6.7.7p2: If a typedef name specifies a variably modified type
509 // then it shall have block scope.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000510 if (const VariableArrayType *VAT =
511 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
512 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
513 VAT->getSizeExpr()->getSourceRange());
514 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000515 }
516 }
517 } else if (D.isFunctionDeclarator()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000518 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000519 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000520
Chris Lattner265c8172007-09-27 15:15:46 +0000521 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000522 switch (D.getDeclSpec().getStorageClassSpec()) {
523 default: assert(0 && "Unknown storage class!");
524 case DeclSpec::SCS_auto:
525 case DeclSpec::SCS_register:
526 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
527 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000528 InvalidDecl = true;
529 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000530 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
531 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
532 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
533 }
534
535 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000536 D.getDeclSpec().isInlineSpecified(),
Chris Lattner4b009652007-07-25 00:24:17 +0000537 LastDeclarator);
538
539 // Merge the decl with the existing one if appropriate.
540 if (PrevDecl) {
541 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
542 if (NewFD == 0) return 0;
543 }
544 New = NewFD;
545 } else {
546 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffcae537d2007-08-28 18:45:29 +0000547 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000548
549 VarDecl *NewVD;
550 VarDecl::StorageClass SC;
551 switch (D.getDeclSpec().getStorageClassSpec()) {
552 default: assert(0 && "Unknown storage class!");
553 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
554 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
555 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
556 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
557 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
558 }
559 if (S->getParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000560 // C99 6.9p2: The storage-class specifiers auto and register shall not
561 // appear in the declaration specifiers in an external declaration.
562 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
563 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
564 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000565 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000566 }
Chris Lattner4b009652007-07-25 00:24:17 +0000567 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000568 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000569 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000570 }
Chris Lattner4b009652007-07-25 00:24:17 +0000571 // Handle attributes prior to checking for duplicates in MergeVarDecl
572 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
573 D.getAttributes());
574
575 // Merge the decl with the existing one if appropriate.
576 if (PrevDecl) {
577 NewVD = MergeVarDecl(NewVD, PrevDecl);
578 if (NewVD == 0) return 0;
579 }
Chris Lattner4b009652007-07-25 00:24:17 +0000580 New = NewVD;
581 }
582
583 // If this has an identifier, add it to the scope stack.
584 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000585 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000586 II->setFETokenInfo(New);
587 S->AddDecl(New);
588 }
589
590 if (S->getParent() == 0)
591 AddTopLevelDecl(New, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000592
593 // If any semantic error occurred, mark the decl as invalid.
594 if (D.getInvalidType() || InvalidDecl)
595 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000596
597 return New;
598}
599
Steve Naroff6a0e2092007-09-12 14:07:44 +0000600void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000601 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000602 Expr *Init = static_cast<Expr *>(init);
603
Steve Naroff420d0f52007-09-12 20:13:48 +0000604 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +0000605
Steve Naroff420d0f52007-09-12 20:13:48 +0000606 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
607 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +0000608 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
609 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +0000610 RealDecl->setInvalidDecl();
611 return;
612 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000613 // Get the decls type and save a reference for later, since
614 // CheckInitializer may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +0000615 QualType DclT = VDecl->getType(), SavT = DclT;
616 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000617 VarDecl::StorageClass SC = BVD->getStorageClass();
618 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +0000619 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000620 BVD->setInvalidDecl();
621 } else if (!BVD->isInvalidDecl()) {
622 CheckInitializer(Init, DclT, SC == VarDecl::Static);
623 }
Steve Naroff420d0f52007-09-12 20:13:48 +0000624 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000625 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +0000626 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000627 if (!FVD->isInvalidDecl())
628 CheckInitializer(Init, DclT, true);
629 }
630 // If the type changed, it means we had an incomplete type that was
631 // completed by the initializer. For example:
632 // int ary[] = { 1, 3, 5 };
633 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff420d0f52007-09-12 20:13:48 +0000634 if (!VDecl->isInvalidDecl() && (DclT != SavT))
635 VDecl->setType(DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000636
637 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +0000638 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000639 return;
640}
641
Chris Lattner4b009652007-07-25 00:24:17 +0000642/// The declarators are chained together backwards, reverse the list.
643Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
644 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000645 Decl *GroupDecl = static_cast<Decl*>(group);
646 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +0000647 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +0000648
649 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
650 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000651 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000652 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000653 else { // reverse the list.
654 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000655 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +0000656 Group->setNextDeclarator(NewGroup);
657 NewGroup = Group;
658 Group = Next;
659 }
660 }
661 // Perform semantic analysis that depends on having fully processed both
662 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000663 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000664 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
665 if (!IDecl)
666 continue;
667 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
668 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
669 QualType T = IDecl->getType();
670
671 // C99 6.7.5.2p2: If an identifier is declared to be an object with
672 // static storage duration, it shall not have a variable length array.
673 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
674 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
675 if (VLA->getSizeExpr()) {
676 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
677 IDecl->setInvalidDecl();
678 }
679 }
680 }
681 // Block scope. C99 6.7p7: If an identifier for an object is declared with
682 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
683 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
684 if (T->isIncompleteType()) {
685 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
686 T.getAsString());
687 IDecl->setInvalidDecl();
688 }
689 }
690 // File scope. C99 6.9.2p2: A declaration of an identifier for and
691 // object that has file scope without an initializer, and without a
692 // storage-class specifier or with the storage-class specifier "static",
693 // constitutes a tentative definition. Note: A tentative definition with
694 // external linkage is valid (C99 6.2.2p5).
695 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
696 // C99 6.9.2p3: If the declaration of an identifier for an object is
697 // a tentative definition and has internal linkage (C99 6.2.2p3), the
698 // declared type shall not be an incomplete type.
699 if (T->isIncompleteType()) {
700 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
701 T.getAsString());
702 IDecl->setInvalidDecl();
703 }
704 }
Chris Lattner4b009652007-07-25 00:24:17 +0000705 }
706 return NewGroup;
707}
Steve Naroff91b03f72007-08-28 03:03:08 +0000708
709// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000710ParmVarDecl *
711Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
712 Scope *FnScope) {
713 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
714
715 IdentifierInfo *II = PI.Ident;
716 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
717 // Can this happen for params? We already checked that they don't conflict
718 // among each other. Here they can only shadow globals, which is ok.
719 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
720 PI.IdentLoc, FnScope)) {
721
722 }
723
724 // FIXME: Handle storage class (auto, register). No declarator?
725 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000726
727 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
728 // Doing the promotion here has a win and a loss. The win is the type for
729 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
730 // code generator). The loss is the orginal type isn't preserved. For example:
731 //
732 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
733 // int blockvardecl[5];
734 // sizeof(parmvardecl); // size == 4
735 // sizeof(blockvardecl); // size == 20
736 // }
737 //
738 // For expressions, all implicit conversions are captured using the
739 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
740 //
741 // FIXME: If a source translation tool needs to see the original type, then
742 // we need to consider storing both types (in ParmVarDecl)...
743 //
744 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
745 if (const ArrayType *AT = parmDeclType->getAsArrayType())
746 parmDeclType = Context.getPointerType(AT->getElementType());
747 else if (parmDeclType->isFunctionType())
748 parmDeclType = Context.getPointerType(parmDeclType);
749
750 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffcae537d2007-08-28 18:45:29 +0000751 VarDecl::None, 0);
752 if (PI.InvalidType)
753 New->setInvalidDecl();
754
Chris Lattner4b009652007-07-25 00:24:17 +0000755 // If this has an identifier, add it to the scope stack.
756 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000757 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000758 II->setFETokenInfo(New);
759 FnScope->AddDecl(New);
760 }
761
762 return New;
763}
764
765
766Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
767 assert(CurFunctionDecl == 0 && "Function parsing confused");
768 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
769 "Not a function declarator!");
770 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
771
772 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
773 // for a K&R function.
774 if (!FTI.hasPrototype) {
775 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
776 if (FTI.ArgInfo[i].TypeInfo == 0) {
777 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
778 FTI.ArgInfo[i].Ident->getName());
779 // Implicitly declare the argument as type 'int' for lack of a better
780 // type.
781 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
782 }
783 }
784
785 // Since this is a function definition, act as though we have information
786 // about the arguments.
787 FTI.hasPrototype = true;
788 } else {
789 // FIXME: Diagnose arguments without names in C.
790
791 }
792
793 Scope *GlobalScope = FnBodyScope->getParent();
794
795 FunctionDecl *FD =
Steve Naroff0acc9c92007-09-15 18:49:24 +0000796 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattner4b009652007-07-25 00:24:17 +0000797 CurFunctionDecl = FD;
798
799 // Create Decl objects for each parameter, adding them to the FunctionDecl.
800 llvm::SmallVector<ParmVarDecl*, 16> Params;
801
802 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
803 // no arguments, not a function that takes a single void argument.
804 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
805 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
806 // empty arg list, don't push any params.
807 } else {
808 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
809 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
810 }
811
812 FD->setParams(&Params[0], Params.size());
813
814 return FD;
815}
816
817Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
818 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
819 FD->setBody((Stmt*)Body);
820
821 assert(FD == CurFunctionDecl && "Function parsing confused");
822 CurFunctionDecl = 0;
823
824 // Verify and clean out per-function state.
825
826 // Check goto/label use.
827 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
828 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
829 // Verify that we have no forward references left. If so, there was a goto
830 // or address of a label taken, but no definition of it. Label fwd
831 // definitions are indicated with a null substmt.
832 if (I->second->getSubStmt() == 0) {
833 LabelStmt *L = I->second;
834 // Emit error.
835 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
836
837 // At this point, we have gotos that use the bogus label. Stitch it into
838 // the function body so that they aren't leaked and that the AST is well
839 // formed.
840 L->setSubStmt(new NullStmt(L->getIdentLoc()));
841 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
842 }
843 }
844 LabelMap.clear();
845
846 return FD;
847}
848
849
850/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
851/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +0000852ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
853 IdentifierInfo &II, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000854 if (getLangOptions().C99) // Extension in C99.
855 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
856 else // Legal in C90, but warn about it.
857 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
858
859 // FIXME: handle stuff like:
860 // void foo() { extern float X(); }
861 // void bar() { X(); } <-- implicit decl for X in another scope.
862
863 // Set a Declarator for the implicit definition: int foo();
864 const char *Dummy;
865 DeclSpec DS;
866 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
867 Error = Error; // Silence warning.
868 assert(!Error && "Error setting up implicit decl!");
869 Declarator D(DS, Declarator::BlockContext);
870 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
871 D.SetIdentifier(&II, Loc);
872
873 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000874 if (Scope *FnS = S->getFnParent())
875 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000876 while (S->getParent())
877 S = S->getParent();
878
Steve Narofff0c31dd2007-09-16 16:16:00 +0000879 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattner4b009652007-07-25 00:24:17 +0000880}
881
882
883TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
Steve Naroff2591e1b2007-09-13 23:52:58 +0000884 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +0000885 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
886
887 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000888 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000889
890 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000891 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
892 T, LastDeclarator);
893 if (D.getInvalidType())
894 NewTD->setInvalidDecl();
895 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +0000896}
897
Steve Naroff25aace82007-10-03 21:00:46 +0000898Sema::DeclTy *Sema::ActOnStartClassInterface(Scope* S,
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000899 SourceLocation AtInterfaceLoc,
Steve Naroff81f1bba2007-09-06 21:24:23 +0000900 IdentifierInfo *ClassName, SourceLocation ClassLoc,
901 IdentifierInfo *SuperName, SourceLocation SuperLoc,
902 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
903 AttributeList *AttrList) {
904 assert(ClassName && "Missing class identifier");
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000905
906 // Check for another declaration kind with the same name.
907 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
908 ClassLoc, S);
909 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
910 && !isa<ObjcProtocolDecl>(PrevDecl)) {
911 Diag(ClassLoc, diag::err_redefinition_different_kind,
912 ClassName->getName());
913 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
914 }
915
Steve Narofffa465d12007-10-02 20:01:56 +0000916 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahaniana5f40402007-09-20 20:26:44 +0000917 if (IDecl) {
918 // Class already seen. Is it a forward declaration?
Steve Narofff4bc79a2007-10-02 20:26:23 +0000919 if (!IDecl->isForwardDecl())
Fariborz Jahaniana5f40402007-09-20 20:26:44 +0000920 Diag(AtInterfaceLoc, diag::err_duplicate_class_def, ClassName->getName());
Fariborz Jahanianac775832007-09-22 00:01:35 +0000921 else {
Steve Narofff4bc79a2007-10-02 20:26:23 +0000922 IDecl->setForwardDecl(false);
Fariborz Jahanianac775832007-09-22 00:01:35 +0000923 IDecl->AllocIntfRefProtocols(NumProtocols);
924 }
Fariborz Jahaniana5f40402007-09-20 20:26:44 +0000925 }
926 else {
Fariborz Jahanianac775832007-09-22 00:01:35 +0000927 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, NumProtocols, ClassName);
Fariborz Jahanian0b59d9c2007-09-20 17:54:07 +0000928
Fariborz Jahaniana5f40402007-09-20 20:26:44 +0000929 // Chain & install the interface decl into the identifier.
930 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
931 ClassName->setFETokenInfo(IDecl);
932 }
Fariborz Jahanian0b59d9c2007-09-20 17:54:07 +0000933
934 if (SuperName) {
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000935 ObjcInterfaceDecl* SuperClassEntry = 0;
936 // Check if a different kind of symbol declared in this scope.
937 PrevDecl = LookupScopedDecl(SuperName, Decl::IDNS_Ordinary,
938 SuperLoc, S);
939 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
940 && !isa<ObjcProtocolDecl>(PrevDecl)) {
941 Diag(SuperLoc, diag::err_redefinition_different_kind,
942 SuperName->getName());
943 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Fariborz Jahanian0b59d9c2007-09-20 17:54:07 +0000944 }
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000945 else {
946 // Check that super class is previously defined
Steve Narofffa465d12007-10-02 20:01:56 +0000947 SuperClassEntry = getObjCInterfaceDecl(SuperName);
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000948
Steve Narofff4bc79a2007-10-02 20:26:23 +0000949 if (!SuperClassEntry || SuperClassEntry->isForwardDecl()) {
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000950 Diag(AtInterfaceLoc, diag::err_undef_superclass, SuperName->getName(),
951 ClassName->getName());
952 }
953 }
954 IDecl->setSuperClass(SuperClassEntry);
Fariborz Jahanian0b59d9c2007-09-20 17:54:07 +0000955 }
956
Fariborz Jahanianac775832007-09-22 00:01:35 +0000957 /// Check then save referenced protocols
958 for (unsigned int i = 0; i != NumProtocols; i++) {
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +0000959 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtocolNames[i],
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +0000960 ClassLoc);
Steve Narofff4bc79a2007-10-02 20:26:23 +0000961 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanianac775832007-09-22 00:01:35 +0000962 Diag(ClassLoc, diag::err_undef_protocolref,
963 ProtocolNames[i]->getName(),
964 ClassName->getName());
965 IDecl->setIntfRefProtocols((int)i, RefPDecl);
966 }
967
Steve Naroff81f1bba2007-09-06 21:24:23 +0000968 return IDecl;
969}
970
Steve Naroff25aace82007-10-03 21:00:46 +0000971Sema::DeclTy *Sema::ActOnStartProtocolInterface(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +0000972 SourceLocation AtProtoInterfaceLoc,
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +0000973 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
974 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
975 assert(ProtocolName && "Missing protocol identifier");
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +0000976 ObjcProtocolDecl *PDecl = getObjCProtocolDecl(S, ProtocolName, ProtocolLoc);
Fariborz Jahanianc716c942007-09-21 15:40:54 +0000977 if (PDecl) {
978 // Protocol already seen. Better be a forward protocol declaration
Steve Narofff4bc79a2007-10-02 20:26:23 +0000979 if (!PDecl->isForwardDecl())
Fariborz Jahanianc716c942007-09-21 15:40:54 +0000980 Diag(ProtocolLoc, diag::err_duplicate_protocol_def,
981 ProtocolName->getName());
982 else {
Steve Narofff4bc79a2007-10-02 20:26:23 +0000983 PDecl->setForwardDecl(false);
Fariborz Jahanianc716c942007-09-21 15:40:54 +0000984 PDecl->AllocReferencedProtocols(NumProtoRefs);
985 }
986 }
987 else {
988 PDecl = new ObjcProtocolDecl(AtProtoInterfaceLoc, NumProtoRefs,
989 ProtocolName);
Steve Narofff4bc79a2007-10-02 20:26:23 +0000990 PDecl->setForwardDecl(false);
Fariborz Jahanianc716c942007-09-21 15:40:54 +0000991 // Chain & install the protocol decl into the identifier.
992 PDecl->setNext(ProtocolName->getFETokenInfo<ScopedDecl>());
993 ProtocolName->setFETokenInfo(PDecl);
Fariborz Jahanianc716c942007-09-21 15:40:54 +0000994 }
995
996 /// Check then save referenced protocols
997 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +0000998 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtoRefNames[i],
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +0000999 ProtocolLoc);
Steve Narofff4bc79a2007-10-02 20:26:23 +00001000 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001001 Diag(ProtocolLoc, diag::err_undef_protocolref,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001002 ProtoRefNames[i]->getName(),
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001003 ProtocolName->getName());
1004 PDecl->setReferencedProtocols((int)i, RefPDecl);
1005 }
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001006
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001007 return PDecl;
1008}
1009
Steve Naroffb4dfe362007-10-02 22:39:18 +00001010/// ActOnForwardProtocolDeclaration -
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001011/// Scope will always be top level file scope.
1012Action::DeclTy *
Steve Naroffb4dfe362007-10-02 22:39:18 +00001013Sema::ActOnForwardProtocolDeclaration(Scope *S, SourceLocation AtProtocolLoc,
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001014 IdentifierInfo **IdentList, unsigned NumElts) {
1015 ObjcForwardProtocolDecl *FDecl = new ObjcForwardProtocolDecl(AtProtocolLoc,
1016 NumElts);
1017
1018 for (unsigned i = 0; i != NumElts; ++i) {
1019 ObjcProtocolDecl *PDecl;
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +00001020 PDecl = getObjCProtocolDecl(S, IdentList[i], AtProtocolLoc);
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001021 if (!PDecl) {// Already seen?
1022 PDecl = new ObjcProtocolDecl(SourceLocation(), 0, IdentList[i], true);
1023 // Chain & install the protocol decl into the identifier.
1024 PDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1025 IdentList[i]->setFETokenInfo(PDecl);
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001026 }
1027 // Remember that this needs to be removed when the scope is popped.
1028 S->AddDecl(IdentList[i]);
1029
1030 FDecl->setForwardProtocolDecl((int)i, PDecl);
1031 }
1032 return FDecl;
1033}
1034
Steve Naroff25aace82007-10-03 21:00:46 +00001035Sema::DeclTy *Sema::ActOnStartCategoryInterface(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001036 SourceLocation AtInterfaceLoc,
Fariborz Jahanianf25220e2007-09-18 20:26:58 +00001037 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1038 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1039 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
1040 ObjcCategoryDecl *CDecl;
Steve Narofffa465d12007-10-02 20:01:56 +00001041 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanian97456452007-10-02 17:36:55 +00001042 CDecl = new ObjcCategoryDecl(AtInterfaceLoc, NumProtoRefs);
Fariborz Jahanianac775832007-09-22 00:01:35 +00001043 CDecl->setClassInterface(IDecl);
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +00001044
Fariborz Jahanianac775832007-09-22 00:01:35 +00001045 /// Check that class of this category is already completely declared.
Steve Narofff4bc79a2007-10-02 20:26:23 +00001046 if (!IDecl || IDecl->isForwardDecl())
Fariborz Jahanianac775832007-09-22 00:01:35 +00001047 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
1048 else {
1049 /// Check for duplicate interface declaration for this category
1050 ObjcCategoryDecl *CDeclChain;
1051 for (CDeclChain = IDecl->getListCategories(); CDeclChain;
1052 CDeclChain = CDeclChain->getNextClassCategory()) {
1053 if (CDeclChain->getCatName() == CategoryName) {
1054 Diag(CategoryLoc, diag::err_dup_category_def, ClassName->getName(),
1055 CategoryName->getName());
1056 break;
1057 }
1058 }
1059 if (!CDeclChain) {
1060 CDecl->setCatName(CategoryName);
1061 CDecl->insertNextClassCategory();
1062 }
1063 }
1064
1065 /// Check then save referenced protocols
1066 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +00001067 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtoRefNames[i],
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001068 CategoryLoc);
Steve Narofff4bc79a2007-10-02 20:26:23 +00001069 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanianac775832007-09-22 00:01:35 +00001070 Diag(CategoryLoc, diag::err_undef_protocolref,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001071 ProtoRefNames[i]->getName(),
Fariborz Jahanianac775832007-09-22 00:01:35 +00001072 CategoryName->getName());
1073 CDecl->setCatReferencedProtocols((int)i, RefPDecl);
1074 }
1075
Fariborz Jahanianf25220e2007-09-18 20:26:58 +00001076 return CDecl;
1077}
Fariborz Jahaniana5f40402007-09-20 20:26:44 +00001078
Steve Naroff25aace82007-10-03 21:00:46 +00001079/// ActOnStartCategoryImplementation - Perform semantic checks on the
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001080/// category implementation declaration and build an ObjcCategoryImplDecl
1081/// object.
Steve Naroff25aace82007-10-03 21:00:46 +00001082Sema::DeclTy *Sema::ActOnStartCategoryImplementation(Scope* S,
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001083 SourceLocation AtCatImplLoc,
1084 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1085 IdentifierInfo *CatName, SourceLocation CatLoc) {
Steve Narofffa465d12007-10-02 20:01:56 +00001086 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001087 ObjcCategoryImplDecl *CDecl = new ObjcCategoryImplDecl(AtCatImplLoc,
1088 ClassName, IDecl,
1089 CatName);
1090 /// Check that class of this category is already completely declared.
Steve Narofff4bc79a2007-10-02 20:26:23 +00001091 if (!IDecl || IDecl->isForwardDecl())
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001092 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
1093 /// TODO: Check that CatName, category name, is not used in another
1094 // implementation.
1095 return CDecl;
1096}
1097
Steve Naroff25aace82007-10-03 21:00:46 +00001098Sema::DeclTy *Sema::ActOnStartClassImplementation(Scope *S,
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001099 SourceLocation AtClassImplLoc,
1100 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1101 IdentifierInfo *SuperClassname,
1102 SourceLocation SuperClassLoc) {
1103 ObjcInterfaceDecl* IDecl = 0;
1104 // Check for another declaration kind with the same name.
1105 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
1106 ClassLoc, S);
1107 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
1108 Diag(ClassLoc, diag::err_redefinition_different_kind,
1109 ClassName->getName());
1110 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1111 }
1112 else {
1113 // Is there an interface declaration of this class; if not, warn!
Steve Narofffa465d12007-10-02 20:01:56 +00001114 IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001115 if (!IDecl)
1116 Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
1117 }
1118
1119 // Check that super class name is valid class name
1120 ObjcInterfaceDecl* SDecl = 0;
1121 if (SuperClassname) {
1122 // Check if a different kind of symbol declared in this scope.
1123 PrevDecl = LookupScopedDecl(SuperClassname, Decl::IDNS_Ordinary,
1124 SuperClassLoc, S);
1125 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
1126 && !isa<ObjcProtocolDecl>(PrevDecl)) {
1127 Diag(SuperClassLoc, diag::err_redefinition_different_kind,
1128 SuperClassname->getName());
1129 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1130 }
1131 else {
Steve Narofffa465d12007-10-02 20:01:56 +00001132 SDecl = getObjCInterfaceDecl(SuperClassname);
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001133 if (!SDecl)
1134 Diag(SuperClassLoc, diag::err_undef_superclass,
1135 SuperClassname->getName(), ClassName->getName());
1136 else if (IDecl && IDecl->getSuperClass() != SDecl) {
1137 // This implementation and its interface do not have the same
1138 // super class.
1139 Diag(SuperClassLoc, diag::err_conflicting_super_class,
1140 SuperClassname->getName());
1141 Diag(SDecl->getLocation(), diag::err_previous_definition);
1142 }
1143 }
1144 }
1145
1146 ObjcImplementationDecl* IMPDecl =
1147 new ObjcImplementationDecl(AtClassImplLoc, ClassName, SDecl);
Fariborz Jahanian1c0eedb2007-09-25 21:00:20 +00001148 if (!IDecl) {
1149 // Legacy case of @implementation with no corresponding @interface.
1150 // Build, chain & install the interface decl into the identifier.
Fariborz Jahanianfa601d52007-10-04 00:22:33 +00001151 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, ClassName);
Fariborz Jahanian1c0eedb2007-09-25 21:00:20 +00001152 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
1153 ClassName->setFETokenInfo(IDecl);
1154
1155 }
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001156
1157 // Check that there is no duplicate implementation of this class.
1158 bool err = false;
1159 for (unsigned i = 0; i != Context.sizeObjcImplementationClass(); i++) {
1160 if (Context.getObjcImplementationClass(i)->getIdentifier() == ClassName) {
1161 Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
1162 err = true;
1163 break;
1164 }
1165 }
1166 if (!err)
1167 Context.setObjcImplementationClass(IMPDecl);
1168
1169 return IMPDecl;
1170}
1171
Steve Naroff89529b12007-10-02 21:43:37 +00001172void Sema::CheckImplementationIvars(ObjcImplementationDecl *ImpDecl,
1173 ObjcIvarDecl **ivars, unsigned numIvars) {
1174 assert(ImpDecl && "missing implementation decl");
1175 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ImpDecl->getIdentifier());
Fariborz Jahanianfa601d52007-10-04 00:22:33 +00001176 /// 2nd check is added to accomodate case of non-existing @interface decl.
1177 /// (legacy objective-c @implementation decl without an @interface decl).
1178 if (!IDecl || IDecl->ImplicitInterfaceDecl())
Steve Naroff89529b12007-10-02 21:43:37 +00001179 return;
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001180 assert(ivars && "missing @implementation ivars");
1181
Steve Naroff89529b12007-10-02 21:43:37 +00001182 // Check interface's Ivar list against those in the implementation.
1183 // names and types must match.
1184 //
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001185 ObjcIvarDecl** IntfIvars = IDecl->getIntfDeclIvars();
1186 int IntfNumIvars = IDecl->getIntfDeclNumIvars();
1187 unsigned j = 0;
1188 bool err = false;
1189 while (numIvars > 0 && IntfNumIvars > 0) {
1190 ObjcIvarDecl* ImplIvar = ivars[j];
1191 ObjcIvarDecl* ClsIvar = IntfIvars[j++];
1192 assert (ImplIvar && "missing implementation ivar");
1193 assert (ClsIvar && "missing class ivar");
1194 if (ImplIvar->getCanonicalType() != ClsIvar->getCanonicalType()) {
1195 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
1196 ImplIvar->getIdentifier()->getName());
1197 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1198 ClsIvar->getIdentifier()->getName());
1199 }
1200 // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
1201 // as error.
1202 else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1203 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
1204 ImplIvar->getIdentifier()->getName());
1205 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1206 ClsIvar->getIdentifier()->getName());
1207 err = true;
1208 break;
1209 }
1210 --numIvars;
1211 --IntfNumIvars;
1212 }
1213 if (!err && (numIvars > 0 || IntfNumIvars > 0))
1214 Diag(numIvars > 0 ? ivars[j]->getLocation() : IntfIvars[j]->getLocation(),
1215 diag::err_inconsistant_ivar);
1216
1217}
1218
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001219/// CheckProtocolMethodDefs - This routine checks unimpletented methods
1220/// Declared in protocol, and those referenced by it.
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001221void Sema::CheckProtocolMethodDefs(ObjcProtocolDecl *PDecl,
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001222 bool& IncompleteImpl,
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001223 const llvm::DenseSet<void *>& InsMap,
1224 const llvm::DenseSet<void *>& ClsMap) {
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001225 // check unimplemented instance methods.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001226 ObjcMethodDecl** methods = PDecl->getInstanceMethods();
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001227 for (int j = 0; j < PDecl->getNumInstanceMethods(); j++) {
1228 void * cpv = methods[j]->getSelector().getAsOpaquePtr();
1229 if (!InsMap.count(cpv)) {
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001230 llvm::SmallString<128> buf;
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001231 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1232 methods[j]->getSelector().getName(buf));
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001233 IncompleteImpl = true;
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001234 }
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001235 }
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001236 // check unimplemented class methods
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001237 methods = PDecl->getClassMethods();
1238 for (int j = 0; j < PDecl->getNumClassMethods(); j++)
Steve Naroff6cb1d362007-09-28 22:22:11 +00001239 if (!ClsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001240 llvm::SmallString<128> buf;
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001241 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1242 methods[j]->getSelector().getName(buf));
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001243 IncompleteImpl = true;
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001244 }
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001245
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001246 // Check on this protocols's referenced protocols, recursively
1247 ObjcProtocolDecl** RefPDecl = PDecl->getReferencedProtocols();
1248 for (int i = 0; i < PDecl->getNumReferencedProtocols(); i++)
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001249 CheckProtocolMethodDefs(RefPDecl[i], IncompleteImpl, InsMap, ClsMap);
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001250}
1251
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001252void Sema::ImplMethodsVsClassMethods(ObjcImplementationDecl* IMPDecl,
1253 ObjcInterfaceDecl* IDecl) {
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001254 llvm::DenseSet<void *> InsMap;
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001255 // Check and see if instance methods in class interface have been
1256 // implemented in the implementation class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001257 ObjcMethodDecl **methods = IMPDecl->getInstanceMethods();
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001258 for (int i=0; i < IMPDecl->getNumInstanceMethods(); i++)
1259 InsMap.insert(methods[i]->getSelector().getAsOpaquePtr());
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001260
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001261 bool IncompleteImpl = false;
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001262 methods = IDecl->getInstanceMethods();
1263 for (int j = 0; j < IDecl->getNumInstanceMethods(); j++)
Steve Naroff6cb1d362007-09-28 22:22:11 +00001264 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001265 llvm::SmallString<128> buf;
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001266 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1267 methods[j]->getSelector().getName(buf));
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001268 IncompleteImpl = true;
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001269 }
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001270 llvm::DenseSet<void *> ClsMap;
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001271 // Check and see if class methods in class interface have been
1272 // implemented in the implementation class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001273 methods = IMPDecl->getClassMethods();
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001274 for (int i=0; i < IMPDecl->getNumClassMethods(); i++)
1275 ClsMap.insert(methods[i]->getSelector().getAsOpaquePtr());
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001276
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001277 methods = IDecl->getClassMethods();
1278 for (int j = 0; j < IDecl->getNumClassMethods(); j++)
Steve Naroff6cb1d362007-09-28 22:22:11 +00001279 if (!ClsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001280 llvm::SmallString<128> buf;
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001281 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1282 methods[j]->getSelector().getName(buf));
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001283 IncompleteImpl = true;
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001284 }
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001285
1286 // Check the protocol list for unimplemented methods in the @implementation
1287 // class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001288 ObjcProtocolDecl** protocols = IDecl->getReferencedProtocols();
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001289 for (int i = 0; i < IDecl->getNumIntfRefProtocols(); i++) {
1290 ObjcProtocolDecl* PDecl = protocols[i];
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001291 CheckProtocolMethodDefs(PDecl, IncompleteImpl, InsMap, ClsMap);
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001292 }
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001293 if (IncompleteImpl)
Fariborz Jahanianfa601d52007-10-04 00:22:33 +00001294 Diag(IMPDecl->getLocation(), diag::warn_incomplete_impl_class,
1295 IMPDecl->getName());
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001296}
1297
1298/// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
1299/// category interface is implemented in the category @implementation.
1300void Sema::ImplCategoryMethodsVsIntfMethods(ObjcCategoryImplDecl *CatImplDecl,
1301 ObjcCategoryDecl *CatClassDecl) {
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001302 llvm::DenseSet<void *> InsMap;
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001303 // Check and see if instance methods in category interface have been
1304 // implemented in its implementation class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001305 ObjcMethodDecl **methods = CatImplDecl->getInstanceMethods();
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001306 for (int i=0; i < CatImplDecl->getNumInstanceMethods(); i++)
1307 InsMap.insert(methods[i]->getSelector().getAsOpaquePtr());
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001308
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001309 bool IncompleteImpl = false;
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001310 methods = CatClassDecl->getInstanceMethods();
1311 for (int j = 0; j < CatClassDecl->getNumInstanceMethods(); j++)
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001312 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
1313 llvm::SmallString<128> buf;
1314 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1315 methods[j]->getSelector().getName(buf));
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001316 IncompleteImpl = true;
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001317 }
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001318 llvm::DenseSet<void *> ClsMap;
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001319 // Check and see if class methods in category interface have been
1320 // implemented in its implementation class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001321 methods = CatImplDecl->getClassMethods();
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001322 for (int i=0; i < CatImplDecl->getNumClassMethods(); i++)
1323 ClsMap.insert(methods[i]->getSelector().getAsOpaquePtr());
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001324
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001325 methods = CatClassDecl->getClassMethods();
1326 for (int j = 0; j < CatClassDecl->getNumClassMethods(); j++)
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001327 if (!ClsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
1328 llvm::SmallString<128> buf;
1329 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1330 methods[j]->getSelector().getName(buf));
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001331 IncompleteImpl = true;
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001332 }
1333
1334 // Check the protocol list for unimplemented methods in the @implementation
1335 // class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001336 ObjcProtocolDecl** protocols = CatClassDecl->getReferencedProtocols();
1337 for (int i = 0; i < CatClassDecl->getNumReferencedProtocols(); i++) {
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001338 ObjcProtocolDecl* PDecl = protocols[i];
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001339 CheckProtocolMethodDefs(PDecl, IncompleteImpl, InsMap, ClsMap);
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001340 }
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001341 if (IncompleteImpl)
Fariborz Jahanianfa601d52007-10-04 00:22:33 +00001342 Diag(CatImplDecl->getLocation(), diag::warn_incomplete_impl_category,
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001343 CatClassDecl->getCatName()->getName());
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001344}
1345
Steve Naroffb4dfe362007-10-02 22:39:18 +00001346/// ActOnForwardClassDeclaration -
Steve Naroff81f1bba2007-09-06 21:24:23 +00001347/// Scope will always be top level file scope.
1348Action::DeclTy *
Steve Naroffb4dfe362007-10-02 22:39:18 +00001349Sema::ActOnForwardClassDeclaration(Scope *S, SourceLocation AtClassLoc,
1350 IdentifierInfo **IdentList, unsigned NumElts)
1351{
Steve Naroff81f1bba2007-09-06 21:24:23 +00001352 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
1353
1354 for (unsigned i = 0; i != NumElts; ++i) {
1355 ObjcInterfaceDecl *IDecl;
Steve Narofffa465d12007-10-02 20:01:56 +00001356 IDecl = getObjCInterfaceDecl(IdentList[i]);
Fariborz Jahaniana5f40402007-09-20 20:26:44 +00001357 if (!IDecl) {// Already seen?
Fariborz Jahanianac775832007-09-22 00:01:35 +00001358 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, IdentList[i], true);
Fariborz Jahaniana5f40402007-09-20 20:26:44 +00001359 // Chain & install the interface decl into the identifier.
1360 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1361 IdentList[i]->setFETokenInfo(IDecl);
Fariborz Jahaniana5f40402007-09-20 20:26:44 +00001362 }
Steve Naroff81f1bba2007-09-06 21:24:23 +00001363 // Remember that this needs to be removed when the scope is popped.
1364 S->AddDecl(IdentList[i]);
1365
1366 CDecl->setInterfaceDecl((int)i, IDecl);
1367 }
1368 return CDecl;
1369}
1370
Chris Lattner4b009652007-07-25 00:24:17 +00001371
Steve Naroff0acc9c92007-09-15 18:49:24 +00001372/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001373/// former case, Name will be non-null. In the later case, Name will be null.
1374/// TagType indicates what kind of tag this is. TK indicates whether this is a
1375/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001376Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001377 SourceLocation KWLoc, IdentifierInfo *Name,
1378 SourceLocation NameLoc, AttributeList *Attr) {
1379 // If this is a use of an existing tag, it must have a name.
1380 assert((Name != 0 || TK == TK_Definition) &&
1381 "Nameless record must be a definition!");
1382
1383 Decl::Kind Kind;
1384 switch (TagType) {
1385 default: assert(0 && "Unknown tag type!");
1386 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1387 case DeclSpec::TST_union: Kind = Decl::Union; break;
1388//case DeclSpec::TST_class: Kind = Decl::Class; break;
1389 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1390 }
1391
1392 // If this is a named struct, check to see if there was a previous forward
1393 // declaration or definition.
1394 if (TagDecl *PrevDecl =
1395 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1396 NameLoc, S))) {
1397
1398 // If this is a use of a previous tag, or if the tag is already declared in
1399 // the same scope (so that the definition/declaration completes or
1400 // rementions the tag), reuse the decl.
1401 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1402 // Make sure that this wasn't declared as an enum and now used as a struct
1403 // or something similar.
1404 if (PrevDecl->getKind() != Kind) {
1405 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1406 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1407 }
1408
1409 // If this is a use or a forward declaration, we're good.
1410 if (TK != TK_Definition)
1411 return PrevDecl;
1412
1413 // Diagnose attempts to redefine a tag.
1414 if (PrevDecl->isDefinition()) {
1415 Diag(NameLoc, diag::err_redefinition, Name->getName());
1416 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1417 // If this is a redefinition, recover by making this struct be
1418 // anonymous, which will make any later references get the previous
1419 // definition.
1420 Name = 0;
1421 } else {
1422 // Okay, this is definition of a previously declared or referenced tag.
1423 // Move the location of the decl to be the definition site.
1424 PrevDecl->setLocation(NameLoc);
1425 return PrevDecl;
1426 }
1427 }
1428 // If we get here, this is a definition of a new struct type in a nested
1429 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1430 // type.
1431 }
1432
1433 // If there is an identifier, use the location of the identifier as the
1434 // location of the decl, otherwise use the location of the struct/union
1435 // keyword.
1436 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1437
1438 // Otherwise, if this is the first time we've seen this tag, create the decl.
1439 TagDecl *New;
1440 switch (Kind) {
1441 default: assert(0 && "Unknown tag kind!");
1442 case Decl::Enum:
1443 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1444 // enum X { A, B, C } D; D should chain to X.
1445 New = new EnumDecl(Loc, Name, 0);
1446 // If this is an undefined enum, warn.
1447 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1448 break;
1449 case Decl::Union:
1450 case Decl::Struct:
1451 case Decl::Class:
1452 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1453 // struct X { int A; } D; D should chain to X.
1454 New = new RecordDecl(Kind, Loc, Name, 0);
1455 break;
1456 }
1457
1458 // If this has an identifier, add it to the scope stack.
1459 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001460 // The scope passed in may not be a decl scope. Zip up the scope tree until
1461 // we find one that is.
1462 while ((S->getFlags() & Scope::DeclScope) == 0)
1463 S = S->getParent();
1464
1465 // Add it to the decl chain.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001466 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001467 Name->setFETokenInfo(New);
1468 S->AddDecl(New);
1469 }
1470
1471 return New;
1472}
1473
Steve Naroff0acc9c92007-09-15 18:49:24 +00001474/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001475/// to create a FieldDecl object for it.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001476Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001477 SourceLocation DeclStart,
1478 Declarator &D, ExprTy *BitfieldWidth) {
1479 IdentifierInfo *II = D.getIdentifier();
1480 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001481 SourceLocation Loc = DeclStart;
1482 if (II) Loc = D.getIdentifierLoc();
1483
1484 // FIXME: Unnamed fields can be handled in various different ways, for
1485 // example, unnamed unions inject all members into the struct namespace!
1486
1487
1488 if (BitWidth) {
1489 // TODO: Validate.
1490 //printf("WARNING: BITFIELDS IGNORED!\n");
1491
1492 // 6.7.2.1p3
1493 // 6.7.2.1p4
1494
1495 } else {
1496 // Not a bitfield.
1497
1498 // validate II.
1499
1500 }
1501
1502 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001503 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1504 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001505
Chris Lattner4b009652007-07-25 00:24:17 +00001506 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1507 // than a variably modified type.
Steve Naroff5eb879b2007-08-31 17:20:07 +00001508 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1509 Diag(Loc, diag::err_typecheck_illegal_vla,
1510 VAT->getSizeExpr()->getSourceRange());
1511 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001512 }
Chris Lattner4b009652007-07-25 00:24:17 +00001513 // FIXME: Chain fielddecls together.
Steve Naroff75494892007-09-11 21:17:26 +00001514 FieldDecl *NewFD;
1515
1516 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Naroffdc1ad762007-09-14 02:20:46 +00001517 NewFD = new FieldDecl(Loc, II, T);
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001518 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl))
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001519 || isa<ObjcImplementationDecl>(static_cast<Decl *>(TagDecl)))
Steve Naroffdc1ad762007-09-14 02:20:46 +00001520 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff75494892007-09-11 21:17:26 +00001521 else
Steve Naroff0acc9c92007-09-15 18:49:24 +00001522 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff75494892007-09-11 21:17:26 +00001523
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001524 if (D.getInvalidType() || InvalidDecl)
1525 NewFD->setInvalidDecl();
1526 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001527}
1528
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001529/// TranslateIvarVisibility - Translate visibility from a token ID to an
1530/// AST enum value.
1531static ObjcIvarDecl::AccessControl
1532TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001533 switch (ivarVisibility) {
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001534 case tok::objc_private: return ObjcIvarDecl::Private;
1535 case tok::objc_public: return ObjcIvarDecl::Public;
1536 case tok::objc_protected: return ObjcIvarDecl::Protected;
1537 case tok::objc_package: return ObjcIvarDecl::Package;
1538 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001539 }
1540}
1541
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00001542void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001543 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001544 DeclTy **Fields, unsigned NumFields,
1545 tok::ObjCKeywordKind *visibility) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001546 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1547 assert(EnclosingDecl && "missing record or interface decl");
1548 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1549
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001550 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001551 // Diagnose code like:
1552 // struct S { struct S {} X; };
1553 // We discover this when we complete the outer S. Reject and ignore the
1554 // outer S.
1555 Diag(Record->getLocation(), diag::err_nested_redefinition,
1556 Record->getKindName());
1557 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001558 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001559 return;
1560 }
Chris Lattner4b009652007-07-25 00:24:17 +00001561 // Verify that all the fields are okay.
1562 unsigned NumNamedMembers = 0;
1563 llvm::SmallVector<FieldDecl*, 32> RecFields;
1564 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00001565
Chris Lattner4b009652007-07-25 00:24:17 +00001566 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001567
Steve Naroff9bb759f2007-09-14 22:20:54 +00001568 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1569 assert(FD && "missing field decl");
1570
1571 // Remember all fields.
1572 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00001573
1574 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001575 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +00001576
Steve Naroffffeaa552007-09-14 23:09:53 +00001577 // If we have visibility info, make sure the AST is set accordingly.
1578 if (visibility)
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001579 cast<ObjcIvarDecl>(FD)->setAccessControl(
1580 TranslateIvarVisibility(visibility[i]));
Steve Naroffffeaa552007-09-14 23:09:53 +00001581
Chris Lattner4b009652007-07-25 00:24:17 +00001582 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001583 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001584 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00001585 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001586 FD->setInvalidDecl();
1587 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001588 continue;
1589 }
Chris Lattner4b009652007-07-25 00:24:17 +00001590 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1591 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001592 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001593 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001594 FD->setInvalidDecl();
1595 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001596 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001597 }
Chris Lattner4b009652007-07-25 00:24:17 +00001598 if (i != NumFields-1 || // ... that the last member ...
1599 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001600 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001601 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001602 FD->setInvalidDecl();
1603 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001604 continue;
1605 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001606 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00001607 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1608 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001609 FD->setInvalidDecl();
1610 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001611 continue;
1612 }
Chris Lattner4b009652007-07-25 00:24:17 +00001613 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001614 if (Record)
1615 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001616 }
Chris Lattner4b009652007-07-25 00:24:17 +00001617 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1618 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001619 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001620 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1621 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001622 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner4b009652007-07-25 00:24:17 +00001623 Record->setHasFlexibleArrayMember(true);
1624 } else {
1625 // If this is a struct/class and this is not the last element, reject
1626 // it. Note that GCC supports variable sized arrays in the middle of
1627 // structures.
1628 if (i != NumFields-1) {
1629 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1630 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001631 FD->setInvalidDecl();
1632 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001633 continue;
1634 }
Chris Lattner4b009652007-07-25 00:24:17 +00001635 // We support flexible arrays at the end of structs in other structs
1636 // as an extension.
1637 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1638 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001639 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001640 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001641 }
1642 }
1643 }
Chris Lattner4b009652007-07-25 00:24:17 +00001644 // Keep track of the number of named members.
1645 if (IdentifierInfo *II = FD->getIdentifier()) {
1646 // Detect duplicate member names.
1647 if (!FieldIDs.insert(II)) {
1648 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1649 // Find the previous decl.
1650 SourceLocation PrevLoc;
1651 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1652 assert(i != e && "Didn't find previous def!");
1653 if (RecFields[i]->getIdentifier() == II) {
1654 PrevLoc = RecFields[i]->getLocation();
1655 break;
1656 }
1657 }
1658 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001659 FD->setInvalidDecl();
1660 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001661 continue;
1662 }
1663 ++NumNamedMembers;
1664 }
Chris Lattner4b009652007-07-25 00:24:17 +00001665 }
1666
Chris Lattner4b009652007-07-25 00:24:17 +00001667 // Okay, we successfully defined 'Record'.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001668 if (Record)
1669 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001670 else {
1671 ObjcIvarDecl **ClsFields =
1672 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001673 if (isa<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1674 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1675 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1676 else if (isa<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1677 ObjcImplementationDecl* IMPDecl =
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001678 cast<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl));
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001679 assert(IMPDecl && "ActOnFields - missing ObjcImplementationDecl");
1680 IMPDecl->ObjcAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Steve Naroff89529b12007-10-02 21:43:37 +00001681 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size());
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001682 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001683 }
Chris Lattner4b009652007-07-25 00:24:17 +00001684}
1685
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001686/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1687/// returns true, or false, accordingly.
1688/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1689bool Sema:: MatchTwoMethodDeclarations(const ObjcMethodDecl *Method,
1690 const ObjcMethodDecl *PrevMethod) {
1691 if (Method->getMethodType().getCanonicalType() !=
1692 PrevMethod->getMethodType().getCanonicalType())
1693 return false;
1694 for (int i = 0; i < Method->getNumParams(); i++) {
1695 ParmVarDecl *ParamDecl = Method->getParamDecl(i);
1696 ParmVarDecl *PrevParamDecl = PrevMethod->getParamDecl(i);
1697 if (ParamDecl->getCanonicalType() != PrevParamDecl->getCanonicalType())
1698 return false;
1699 }
1700 return true;
1701}
1702
Steve Naroff25aace82007-10-03 21:00:46 +00001703void Sema::ActOnAddMethodsToObjcDecl(Scope* S, DeclTy *ClassDecl,
1704 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001705 // FIXME: Fix this when we can handle methods declared in protocols.
1706 // See Parser::ParseObjCAtProtocolDeclaration
1707 if (!ClassDecl)
1708 return;
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001709 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1710 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001711
1712 llvm::DenseMap<void *, const ObjcMethodDecl*> InsMap;
1713 llvm::DenseMap<void *, const ObjcMethodDecl*> ClsMap;
1714
1715 bool isClassDeclaration =
1716 (isa<ObjcInterfaceDecl>(static_cast<Decl *>(ClassDecl))
1717 || isa<ObjcCategoryDecl>(static_cast<Decl *>(ClassDecl)));
1718
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001719 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001720 ObjcMethodDecl *Method =
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001721 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1722 if (!Method) continue; // Already issued a diagnostic.
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001723 if (Method->isInstance()) {
1724 if (isClassDeclaration) {
1725 /// Check for instance method of the same name with incompatible types
1726 const ObjcMethodDecl *&PrevMethod =
1727 InsMap[Method->getSelector().getAsOpaquePtr()];
1728 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
1729 llvm::SmallString<128> buf;
1730 Diag(Method->getLocation(), diag::error_duplicate_method_decl,
1731 Method->getSelector().getName(buf));
1732 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
1733 }
1734 else {
1735 insMethods.push_back(Method);
1736 InsMap[Method->getSelector().getAsOpaquePtr()] = Method;
1737 }
1738 }
1739 else
1740 insMethods.push_back(Method);
1741 }
1742 else {
1743 if (isClassDeclaration) {
1744 /// Check for class method of the same name with incompatible types
1745 const ObjcMethodDecl *&PrevMethod =
1746 ClsMap[Method->getSelector().getAsOpaquePtr()];
1747 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
1748 llvm::SmallString<128> buf;
1749 Diag(Method->getLocation(), diag::error_duplicate_method_decl,
1750 Method->getSelector().getName(buf));
1751 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
1752 }
1753 else {
1754 clsMethods.push_back(Method);
1755 ClsMap[Method->getSelector().getAsOpaquePtr()] = Method;
1756 }
1757 }
1758 else
1759 clsMethods.push_back(Method);
1760 }
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001761 }
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001762 if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(ClassDecl))) {
1763 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1764 static_cast<Decl*>(ClassDecl));
1765 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1766 &clsMethods[0], clsMethods.size());
1767 }
1768 else if (isa<ObjcProtocolDecl>(static_cast<Decl *>(ClassDecl))) {
1769 ObjcProtocolDecl *Protocol = cast<ObjcProtocolDecl>(
1770 static_cast<Decl*>(ClassDecl));
1771 Protocol->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1772 &clsMethods[0], clsMethods.size());
1773 }
Fariborz Jahanianf25220e2007-09-18 20:26:58 +00001774 else if (isa<ObjcCategoryDecl>(static_cast<Decl *>(ClassDecl))) {
1775 ObjcCategoryDecl *Category = cast<ObjcCategoryDecl>(
1776 static_cast<Decl*>(ClassDecl));
1777 Category->ObjcAddCatMethods(&insMethods[0], insMethods.size(),
1778 &clsMethods[0], clsMethods.size());
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001779 }
1780 else if (isa<ObjcImplementationDecl>(static_cast<Decl *>(ClassDecl))) {
1781 ObjcImplementationDecl* ImplClass = cast<ObjcImplementationDecl>(
1782 static_cast<Decl*>(ClassDecl));
1783 ImplClass->ObjcAddImplMethods(&insMethods[0], insMethods.size(),
1784 &clsMethods[0], clsMethods.size());
Steve Narofffa465d12007-10-02 20:01:56 +00001785 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ImplClass->getIdentifier());
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001786 if (IDecl)
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001787 ImplMethodsVsClassMethods(ImplClass, IDecl);
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001788 }
Fariborz Jahanian37c9c612007-10-04 20:19:06 +00001789 else {
1790 ObjcCategoryImplDecl* CatImplClass = dyn_cast<ObjcCategoryImplDecl>(
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001791 static_cast<Decl*>(ClassDecl));
Fariborz Jahanian37c9c612007-10-04 20:19:06 +00001792 if (CatImplClass) {
1793 CatImplClass->ObjcAddCatImplMethods(&insMethods[0], insMethods.size(),
1794 &clsMethods[0], clsMethods.size());
1795 ObjcInterfaceDecl* IDecl = CatImplClass->getClassInterface();
1796 // Find category interface decl and then check that all methods declared
1797 // in this interface is implemented in the category @implementation.
1798 if (IDecl) {
1799 for (ObjcCategoryDecl *Categories = IDecl->getListCategories();
1800 Categories; Categories = Categories->getNextClassCategory()) {
1801 if (Categories->getCatName() == CatImplClass->getObjcCatName()) {
1802 ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
1803 break;
1804 }
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001805 }
1806 }
1807 }
Fariborz Jahanian37c9c612007-10-04 20:19:06 +00001808 else
1809 assert(0 && "Sema::ActOnAddMethodsToObjcDecl(): Unknown DeclTy");
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001810 }
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001811}
1812
Steve Naroffb4dfe362007-10-02 22:39:18 +00001813Sema::DeclTy *Sema::ActOnMethodDeclaration(SourceLocation MethodLoc,
Steve Naroff6cb1d362007-09-28 22:22:11 +00001814 tok::TokenKind MethodType, TypeTy *ReturnType, Selector Sel,
Steve Naroff4ed9d662007-09-27 14:38:14 +00001815 // optional arguments. The number of types/arguments is obtained
1816 // from the Sel.getNumArgs().
1817 TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1818 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind) {
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001819 llvm::SmallVector<ParmVarDecl*, 16> Params;
1820
Steve Naroff6cb1d362007-09-28 22:22:11 +00001821 for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001822 // FIXME: arg->AttrList must be stored too!
Steve Naroff4ed9d662007-09-27 14:38:14 +00001823 ParmVarDecl* Param = new ParmVarDecl(SourceLocation(/*FIXME*/), ArgNames[i],
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001824 QualType::getFromOpaquePtr(ArgTypes[i]),
1825 VarDecl::None, 0);
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001826 Params.push_back(Param);
1827 }
1828 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Steve Naroff4ed9d662007-09-27 14:38:14 +00001829 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc, Sel,
1830 resultDeclType, 0, -1, AttrList,
Fariborz Jahaniana00e0742007-09-29 18:24:58 +00001831 MethodType == tok::minus,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001832 MethodDeclKind == tok::objc_optional ?
1833 ObjcMethodDecl::Optional :
1834 ObjcMethodDecl::Required);
Steve Naroff6cb1d362007-09-28 22:22:11 +00001835 ObjcMethod->setMethodParams(&Params[0], Sel.getNumArgs());
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001836 return ObjcMethod;
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001837}
1838
Steve Naroff0acc9c92007-09-15 18:49:24 +00001839Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001840 DeclTy *lastEnumConst,
1841 SourceLocation IdLoc, IdentifierInfo *Id,
1842 SourceLocation EqualLoc, ExprTy *val) {
1843 theEnumDecl = theEnumDecl; // silence unused warning.
1844 EnumConstantDecl *LastEnumConst =
1845 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1846 Expr *Val = static_cast<Expr*>(val);
1847
Chris Lattnera7549902007-08-26 06:24:45 +00001848 // The scope passed in may not be a decl scope. Zip up the scope tree until
1849 // we find one that is.
1850 while ((S->getFlags() & Scope::DeclScope) == 0)
1851 S = S->getParent();
1852
Chris Lattner4b009652007-07-25 00:24:17 +00001853 // Verify that there isn't already something declared with this name in this
1854 // scope.
Steve Naroffcb597472007-09-13 21:41:19 +00001855 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1856 IdLoc, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001857 if (S->isDeclScope(PrevDecl)) {
1858 if (isa<EnumConstantDecl>(PrevDecl))
1859 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1860 else
1861 Diag(IdLoc, diag::err_redefinition, Id->getName());
1862 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1863 // FIXME: Don't leak memory: delete Val;
1864 return 0;
1865 }
1866 }
1867
1868 llvm::APSInt EnumVal(32);
1869 QualType EltTy;
1870 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001871 // Make sure to promote the operand type to int.
1872 UsualUnaryConversions(Val);
1873
Chris Lattner4b009652007-07-25 00:24:17 +00001874 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1875 SourceLocation ExpLoc;
1876 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1877 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1878 Id->getName());
1879 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001880 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001881 } else {
1882 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001883 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001884 }
1885
1886 if (!Val) {
1887 if (LastEnumConst) {
1888 // Assign the last value + 1.
1889 EnumVal = LastEnumConst->getInitVal();
1890 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001891
1892 // Check for overflow on increment.
1893 if (EnumVal < LastEnumConst->getInitVal())
1894 Diag(IdLoc, diag::warn_enum_value_overflow);
1895
Chris Lattnere7f53a42007-08-27 17:37:24 +00001896 EltTy = LastEnumConst->getType();
1897 } else {
1898 // First value, set to zero.
1899 EltTy = Context.IntTy;
Chris Lattner3496d522007-09-04 02:45:27 +00001900 EnumVal.zextOrTrunc(
1901 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001902 }
Chris Lattner4b009652007-07-25 00:24:17 +00001903 }
1904
Chris Lattner4b009652007-07-25 00:24:17 +00001905 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1906 LastEnumConst);
1907
1908 // Register this decl in the current scope stack.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001909 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001910 Id->setFETokenInfo(New);
1911 S->AddDecl(New);
1912 return New;
1913}
1914
Steve Naroff0acc9c92007-09-15 18:49:24 +00001915void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00001916 DeclTy **Elements, unsigned NumElements) {
1917 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1918 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1919
Chris Lattner435c3fd2007-08-28 05:10:31 +00001920 // TODO: If the result value doesn't fit in an int, it must be a long or long
1921 // long value. ISO C does not support this, but GCC does as an extension,
1922 // emit a warning.
Chris Lattner206754a2007-08-28 06:15:15 +00001923 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner435c3fd2007-08-28 05:10:31 +00001924
1925
Chris Lattner206754a2007-08-28 06:15:15 +00001926 // Verify that all the values are okay, compute the size of the values, and
1927 // reverse the list.
1928 unsigned NumNegativeBits = 0;
1929 unsigned NumPositiveBits = 0;
1930
1931 // Keep track of whether all elements have type int.
1932 bool AllElementsInt = true;
1933
Chris Lattner4b009652007-07-25 00:24:17 +00001934 EnumConstantDecl *EltList = 0;
1935 for (unsigned i = 0; i != NumElements; ++i) {
1936 EnumConstantDecl *ECD =
1937 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1938 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001939
1940 // If the enum value doesn't fit in an int, emit an extension warning.
1941 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1942 "Should have promoted value to int");
1943 const llvm::APSInt &InitVal = ECD->getInitVal();
1944 if (InitVal.getBitWidth() > IntWidth) {
1945 llvm::APSInt V(InitVal);
1946 V.trunc(IntWidth);
1947 V.extend(InitVal.getBitWidth());
1948 if (V != InitVal)
1949 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1950 InitVal.toString());
1951 }
Chris Lattner206754a2007-08-28 06:15:15 +00001952
1953 // Keep track of the size of positive and negative values.
1954 if (InitVal.isUnsigned() || !InitVal.isNegative())
1955 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1956 else
1957 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001958
Chris Lattner206754a2007-08-28 06:15:15 +00001959 // Keep track of whether every enum element has type int (very commmon).
1960 if (AllElementsInt)
1961 AllElementsInt = ECD->getType() == Context.IntTy;
1962
Chris Lattner4b009652007-07-25 00:24:17 +00001963 ECD->setNextDeclarator(EltList);
1964 EltList = ECD;
1965 }
1966
Chris Lattner206754a2007-08-28 06:15:15 +00001967 // Figure out the type that should be used for this enum.
1968 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1969 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001970 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001971
1972 if (NumNegativeBits) {
1973 // If there is a negative value, figure out the smallest integer type (of
1974 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001975 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001976 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001977 BestWidth = IntWidth;
1978 } else {
1979 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1980 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001981 BestType = Context.LongTy;
1982 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001983 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1984 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001985 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1986 BestType = Context.LongLongTy;
1987 }
1988 }
1989 } else {
1990 // If there is no negative value, figure out which of uint, ulong, ulonglong
1991 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001992 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001993 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001994 BestWidth = IntWidth;
1995 } else if (NumPositiveBits <=
1996 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattner206754a2007-08-28 06:15:15 +00001997 BestType = Context.UnsignedLongTy;
1998 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001999 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
2000 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00002001 "How could an initializer get larger than ULL?");
2002 BestType = Context.UnsignedLongLongTy;
2003 }
2004 }
2005
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002006 // Loop over all of the enumerator constants, changing their types to match
2007 // the type of the enum if needed.
2008 for (unsigned i = 0; i != NumElements; ++i) {
2009 EnumConstantDecl *ECD =
2010 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2011 if (!ECD) continue; // Already issued a diagnostic.
2012
2013 // Standard C says the enumerators have int type, but we allow, as an
2014 // extension, the enumerators to be larger than int size. If each
2015 // enumerator value fits in an int, type it as an int, otherwise type it the
2016 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2017 // that X has type 'int', not 'unsigned'.
2018 if (ECD->getType() == Context.IntTy)
2019 continue; // Already int type.
2020
2021 // Determine whether the value fits into an int.
2022 llvm::APSInt InitVal = ECD->getInitVal();
2023 bool FitsInInt;
2024 if (InitVal.isUnsigned() || !InitVal.isNegative())
2025 FitsInInt = InitVal.getActiveBits() < IntWidth;
2026 else
2027 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2028
2029 // If it fits into an integer type, force it. Otherwise force it to match
2030 // the enum decl type.
2031 QualType NewTy;
2032 unsigned NewWidth;
2033 bool NewSign;
2034 if (FitsInInt) {
2035 NewTy = Context.IntTy;
2036 NewWidth = IntWidth;
2037 NewSign = true;
2038 } else if (ECD->getType() == BestType) {
2039 // Already the right type!
2040 continue;
2041 } else {
2042 NewTy = BestType;
2043 NewWidth = BestWidth;
2044 NewSign = BestType->isSignedIntegerType();
2045 }
2046
2047 // Adjust the APSInt value.
2048 InitVal.extOrTrunc(NewWidth);
2049 InitVal.setIsSigned(NewSign);
2050 ECD->setInitVal(InitVal);
2051
2052 // Adjust the Expr initializer and type.
2053 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2054 ECD->setType(NewTy);
2055 }
Chris Lattner206754a2007-08-28 06:15:15 +00002056
Chris Lattner90a018d2007-08-28 18:24:31 +00002057 Enum->defineElements(EltList, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00002058}
2059
2060void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
2061 if (!current) return;
2062
2063 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
2064 // remember this in the LastInGroupList list.
2065 if (last)
2066 LastInGroupList.push_back((Decl*)last);
2067}
2068
2069void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
2070 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
2071 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2072 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
2073 if (!newType.isNull()) // install the new vector type into the decl
2074 vDecl->setType(newType);
2075 }
2076 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2077 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
2078 rawAttr);
2079 if (!newType.isNull()) // install the new vector type into the decl
2080 tDecl->setUnderlyingType(newType);
2081 }
2082 }
2083 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroff82113e32007-07-29 16:33:31 +00002084 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
2085 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
2086 else
Chris Lattner4b009652007-07-25 00:24:17 +00002087 Diag(rawAttr->getAttributeLoc(),
2088 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner4b009652007-07-25 00:24:17 +00002089 }
2090 // FIXME: add other attributes...
2091}
2092
2093void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2094 AttributeList *declarator_postfix) {
2095 while (declspec_prefix) {
2096 HandleDeclAttribute(New, declspec_prefix);
2097 declspec_prefix = declspec_prefix->getNext();
2098 }
2099 while (declarator_postfix) {
2100 HandleDeclAttribute(New, declarator_postfix);
2101 declarator_postfix = declarator_postfix->getNext();
2102 }
2103}
2104
Steve Naroff82113e32007-07-29 16:33:31 +00002105void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2106 AttributeList *rawAttr) {
2107 QualType curType = tDecl->getUnderlyingType();
Chris Lattner4b009652007-07-25 00:24:17 +00002108 // check the attribute arugments.
2109 if (rawAttr->getNumArgs() != 1) {
2110 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2111 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00002112 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002113 }
2114 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2115 llvm::APSInt vecSize(32);
2116 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
2117 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2118 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00002119 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002120 }
2121 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2122 // in conjunction with complex types (pointers, arrays, functions, etc.).
2123 Type *canonType = curType.getCanonicalType().getTypePtr();
2124 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2125 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2126 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00002127 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002128 }
2129 // unlike gcc's vector_size attribute, the size is specified as the
2130 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00002131 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00002132
2133 if (vectorSize == 0) {
2134 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2135 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00002136 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002137 }
Steve Naroff82113e32007-07-29 16:33:31 +00002138 // Instantiate/Install the vector type, the number of elements is > 0.
2139 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2140 // Remember this typedef decl, we will need it later for diagnostics.
2141 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002142}
2143
2144QualType Sema::HandleVectorTypeAttribute(QualType curType,
2145 AttributeList *rawAttr) {
2146 // check the attribute arugments.
2147 if (rawAttr->getNumArgs() != 1) {
2148 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2149 std::string("1"));
2150 return QualType();
2151 }
2152 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2153 llvm::APSInt vecSize(32);
2154 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
2155 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2156 sizeExpr->getSourceRange());
2157 return QualType();
2158 }
2159 // navigate to the base type - we need to provide for vector pointers,
2160 // vector arrays, and functions returning vectors.
2161 Type *canonType = curType.getCanonicalType().getTypePtr();
2162
2163 if (canonType->isPointerType() || canonType->isArrayType() ||
2164 canonType->isFunctionType()) {
2165 assert(1 && "HandleVector(): Complex type construction unimplemented");
2166 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2167 do {
2168 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2169 canonType = PT->getPointeeType().getTypePtr();
2170 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2171 canonType = AT->getElementType().getTypePtr();
2172 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2173 canonType = FT->getResultType().getTypePtr();
2174 } while (canonType->isPointerType() || canonType->isArrayType() ||
2175 canonType->isFunctionType());
2176 */
2177 }
2178 // the base type must be integer or float.
2179 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2180 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2181 curType.getCanonicalType().getAsString());
2182 return QualType();
2183 }
Chris Lattner3496d522007-09-04 02:45:27 +00002184 unsigned typeSize = static_cast<unsigned>(
2185 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Chris Lattner4b009652007-07-25 00:24:17 +00002186 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00002187 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00002188
2189 // the vector size needs to be an integral multiple of the type size.
2190 if (vectorSize % typeSize) {
2191 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
2192 sizeExpr->getSourceRange());
2193 return QualType();
2194 }
2195 if (vectorSize == 0) {
2196 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2197 sizeExpr->getSourceRange());
2198 return QualType();
2199 }
2200 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
2201 // the number of elements to be a power of two (unlike GCC).
2202 // Instantiate the vector type, the number of elements is > 0.
2203 return Context.getVectorType(curType, vectorSize/typeSize);
2204}
2205