blob: d870ab4d21a9a57f2f7231014dc14eb00adb6bbb [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.
Fariborz Jahaniana096e1d2007-10-05 21:01:53 +0000107 ScopedDecl *PrDecl = NULL;
108 for (ScopedDecl *D = Id->getFETokenInfo<ScopedDecl>(); D; D = D->getNext()) {
109 if (D->getIdentifierNamespace() == Decl::IDNS_Protocol) {
110 PrDecl = D;
111 break;
112 }
113 }
114
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +0000115 if (PrDecl && !isa<ObjcProtocolDecl>(PrDecl))
116 PrDecl = 0;
117 return cast_or_null<ObjcProtocolDecl>(static_cast<Decl*>(PrDecl));
118}
119
Chris Lattner4b009652007-07-25 00:24:17 +0000120/// LookupScopedDecl - Look up the inner-most declaration in the specified
121/// namespace.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000122ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
123 SourceLocation IdLoc, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000124 if (II == 0) return 0;
125 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
126
127 // Scan up the scope chain looking for a decl that matches this identifier
128 // that is in the appropriate namespace. This search should not take long, as
129 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000130 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner4b009652007-07-25 00:24:17 +0000131 if (D->getIdentifierNamespace() == NS)
132 return D;
133
134 // If we didn't find a use of this identifier, and if the identifier
135 // corresponds to a compiler builtin, create the decl object for the builtin
136 // now, injecting it into translation unit scope, and return it.
137 if (NS == Decl::IDNS_Ordinary) {
138 // If this is a builtin on some other target, or if this builtin varies
139 // across targets (e.g. in type), emit a diagnostic and mark the translation
140 // unit non-portable for using it.
141 if (II->isNonPortableBuiltin()) {
142 // Only emit this diagnostic once for this builtin.
143 II->setNonPortableBuiltin(false);
144 Context.Target.DiagnoseNonPortability(IdLoc,
145 diag::port_target_builtin_use);
146 }
147 // If this is a builtin on this (or all) targets, create the decl.
148 if (unsigned BuiltinID = II->getBuiltinID())
149 return LazilyCreateBuiltin(II, BuiltinID, S);
150 }
151 return 0;
152}
153
154/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
155/// lazily create a decl for it.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000156ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000157 Builtin::ID BID = (Builtin::ID)bid;
158
159 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
160 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner987058a2007-08-26 04:02:13 +0000161 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000162
163 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000164 if (Scope *FnS = S->getFnParent())
165 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000166 while (S->getParent())
167 S = S->getParent();
168 S->AddDecl(New);
169
170 // Add this decl to the end of the identifier info.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000171 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000172 // Scan until we find the last (outermost) decl in the id chain.
173 while (LastDecl->getNext())
174 LastDecl = LastDecl->getNext();
175 // Insert before (outside) it.
176 LastDecl->setNext(New);
177 } else {
178 II->setFETokenInfo(New);
179 }
180 // Make sure clients iterating over decls see this.
181 LastInGroupList.push_back(New);
182
183 return New;
184}
185
186/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
187/// and scope as a previous declaration 'Old'. Figure out how to resolve this
188/// situation, merging decls or emitting diagnostics as appropriate.
189///
Steve Naroffcb597472007-09-13 21:41:19 +0000190TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000191 // Verify the old decl was also a typedef.
192 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
193 if (!Old) {
194 Diag(New->getLocation(), diag::err_redefinition_different_kind,
195 New->getName());
196 Diag(OldD->getLocation(), diag::err_previous_definition);
197 return New;
198 }
199
200 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
201 // TODO: This is totally simplistic. It should handle merging functions
202 // together etc, merging extern int X; int X; ...
203 Diag(New->getLocation(), diag::err_redefinition, New->getName());
204 Diag(Old->getLocation(), diag::err_previous_definition);
205 return New;
206}
207
208/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
209/// and scope as a previous declaration 'Old'. Figure out how to resolve this
210/// situation, merging decls or emitting diagnostics as appropriate.
211///
Steve Naroffcb597472007-09-13 21:41:19 +0000212FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000213 // Verify the old decl was also a function.
214 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
215 if (!Old) {
216 Diag(New->getLocation(), diag::err_redefinition_different_kind,
217 New->getName());
218 Diag(OldD->getLocation(), diag::err_previous_definition);
219 return New;
220 }
221
222 // This is not right, but it's a start. If 'Old' is a function prototype with
223 // the same type as 'New', silently allow this. FIXME: We should link up decl
224 // objects here.
225 if (Old->getBody() == 0 &&
226 Old->getCanonicalType() == New->getCanonicalType()) {
227 return New;
228 }
229
230 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
231 // TODO: This is totally simplistic. It should handle merging functions
232 // together etc, merging extern int X; int X; ...
233 Diag(New->getLocation(), diag::err_redefinition, New->getName());
234 Diag(Old->getLocation(), diag::err_previous_definition);
235 return New;
236}
237
238/// MergeVarDecl - We just parsed a variable 'New' which has the same name
239/// and scope as a previous declaration 'Old'. Figure out how to resolve this
240/// situation, merging decls or emitting diagnostics as appropriate.
241///
242/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
243/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
244///
Steve Naroffcb597472007-09-13 21:41:19 +0000245VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000246 // Verify the old decl was also a variable.
247 VarDecl *Old = dyn_cast<VarDecl>(OldD);
248 if (!Old) {
249 Diag(New->getLocation(), diag::err_redefinition_different_kind,
250 New->getName());
251 Diag(OldD->getLocation(), diag::err_previous_definition);
252 return New;
253 }
Steve Naroff83c13012007-08-30 01:06:46 +0000254 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
255 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
256 bool OldIsTentative = false;
257
258 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
259 // Handle C "tentative" external object definitions. FIXME: finish!
260 if (!OldFSDecl->getInit() &&
261 (OldFSDecl->getStorageClass() == VarDecl::None ||
262 OldFSDecl->getStorageClass() == VarDecl::Static))
263 OldIsTentative = true;
264 }
Chris Lattner4b009652007-07-25 00:24:17 +0000265 // Verify the types match.
266 if (Old->getCanonicalType() != New->getCanonicalType()) {
267 Diag(New->getLocation(), diag::err_redefinition, New->getName());
268 Diag(Old->getLocation(), diag::err_previous_definition);
269 return New;
270 }
271 // We've verified the types match, now check if Old is "extern".
272 if (Old->getStorageClass() != VarDecl::Extern) {
273 Diag(New->getLocation(), diag::err_redefinition, New->getName());
274 Diag(Old->getLocation(), diag::err_previous_definition);
275 }
276 return New;
277}
278
279/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
280/// no declarator (e.g. "struct foo;") is parsed.
281Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
282 // TODO: emit error on 'int;' or 'const enum foo;'.
283 // TODO: emit error on 'typedef int;'
284 // if (!DS.isMissingDeclaratorOk()) Diag(...);
285
286 return 0;
287}
288
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000289bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000290 AssignmentCheckResult result;
291 SourceLocation loc = Init->getLocStart();
292 // Get the type before calling CheckSingleAssignmentConstraints(), since
293 // it can promote the expression.
294 QualType rhsType = Init->getType();
295
296 result = CheckSingleAssignmentConstraints(DeclType, Init);
297
298 // decode the result (notice that extensions still return a type).
299 switch (result) {
300 case Compatible:
301 break;
302 case Incompatible:
Steve Naroff9091f3f2007-09-02 15:34:30 +0000303 // FIXME: tighten up this check which should allow:
304 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
305 if (rhsType == Context.getPointerType(Context.CharTy))
306 break;
Steve Naroffe14e5542007-09-02 02:04:30 +0000307 Diag(loc, diag::err_typecheck_assign_incompatible,
308 DeclType.getAsString(), rhsType.getAsString(),
309 Init->getSourceRange());
310 return true;
311 case PointerFromInt:
312 // check for null pointer constant (C99 6.3.2.3p3)
313 if (!Init->isNullPointerConstant(Context)) {
314 Diag(loc, diag::ext_typecheck_assign_pointer_int,
315 DeclType.getAsString(), rhsType.getAsString(),
316 Init->getSourceRange());
317 return true;
318 }
319 break;
320 case IntFromPointer:
321 Diag(loc, diag::ext_typecheck_assign_pointer_int,
322 DeclType.getAsString(), rhsType.getAsString(),
323 Init->getSourceRange());
324 break;
325 case IncompatiblePointer:
326 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
327 DeclType.getAsString(), rhsType.getAsString(),
328 Init->getSourceRange());
329 break;
330 case CompatiblePointerDiscardsQualifiers:
331 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
332 DeclType.getAsString(), rhsType.getAsString(),
333 Init->getSourceRange());
334 break;
335 }
336 return false;
337}
338
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000339bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
340 bool isStatic, QualType ElementType) {
Steve Naroff509d0b52007-09-04 02:20:04 +0000341 SourceLocation loc;
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000342 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff509d0b52007-09-04 02:20:04 +0000343
344 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
345 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
346 return true;
347 } else if (CheckSingleInitializer(expr, ElementType)) {
348 return true; // types weren't compatible.
349 }
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000350 if (savExpr != expr) // The type was promoted, update initializer list.
351 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000352 return false;
353}
354
355void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
356 QualType ElementType, bool isStatic,
357 int &nInitializers, bool &hadError) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000358 for (unsigned i = 0; i < IList->getNumInits(); i++) {
359 Expr *expr = IList->getInit(i);
360
Steve Naroff509d0b52007-09-04 02:20:04 +0000361 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
362 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000363 int maxElements = CAT->getMaximumElements();
Steve Naroff509d0b52007-09-04 02:20:04 +0000364 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
365 maxElements, hadError);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000366 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000367 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000368 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000369 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000370 nInitializers++;
371 }
372 return;
373}
374
375// FIXME: Doesn't deal with arrays of structures yet.
376void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
377 QualType ElementType, bool isStatic,
378 int &totalInits, bool &hadError) {
379 int maxElementsAtThisLevel = 0;
380 int nInitsAtLevel = 0;
381
382 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
383 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff4f910992007-09-04 21:13:33 +0000384 maxElementsAtThisLevel = CAT->getMaximumElements();
385 // Set DeclType, used below to recurse (for multi-dimensional arrays).
386 DeclType = CAT->getElementType();
Steve Naroff509d0b52007-09-04 02:20:04 +0000387 } else if (DeclType->isScalarType()) {
388 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
389 IList->getSourceRange());
390 maxElementsAtThisLevel = 1;
391 }
392 // The empty init list "{ }" is treated specially below.
393 unsigned numInits = IList->getNumInits();
394 if (numInits) {
395 for (unsigned i = 0; i < numInits; i++) {
396 Expr *expr = IList->getInit(i);
397
398 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
399 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
400 totalInits, hadError);
401 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000402 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff509d0b52007-09-04 02:20:04 +0000403 nInitsAtLevel++; // increment the number of initializers at this level.
404 totalInits--; // decrement the total number of initializers.
405
406 // Check if we have space for another initializer.
407 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
408 Diag(expr->getLocStart(), diag::warn_excess_initializers,
409 expr->getSourceRange());
410 }
411 }
412 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
413 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
414 } else {
415 // we have an initializer list with no elements.
416 totalInits -= maxElementsAtThisLevel;
417 if (totalInits < 0)
418 Diag(IList->getLocStart(), diag::warn_excess_initializers,
419 IList->getSourceRange());
Steve Naroff9091f3f2007-09-02 15:34:30 +0000420 }
Steve Naroff1c9de712007-09-03 01:24:23 +0000421 return;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000422}
423
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000424bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000425 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroff1c9de712007-09-03 01:24:23 +0000426 if (!InitList)
427 return CheckSingleInitializer(Init, DeclType);
428
Steve Naroffe14e5542007-09-02 02:04:30 +0000429 // We have an InitListExpr, make sure we set the type.
430 Init->setType(DeclType);
Steve Naroff1c9de712007-09-03 01:24:23 +0000431
432 bool hadError = false;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000433
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000434 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
435 // of unknown size ("[]") or an object type that is not a variable array type.
436 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
437 Expr *expr = VAT->getSizeExpr();
Steve Naroff1c9de712007-09-03 01:24:23 +0000438 if (expr)
439 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
440 expr->getSourceRange());
441
Steve Naroff4f910992007-09-04 21:13:33 +0000442 // We have a VariableArrayType with unknown size. Note that only the first
443 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff509d0b52007-09-04 02:20:04 +0000444 int numInits = 0;
Steve Naroff4f910992007-09-04 21:13:33 +0000445 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
446 isStatic, numInits, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000447 if (!hadError) {
448 // Return a new array type from the number of initializers (C99 6.7.8p22).
449 llvm::APSInt ConstVal(32);
Steve Naroff509d0b52007-09-04 02:20:04 +0000450 ConstVal = numInits;
451 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroff1c9de712007-09-03 01:24:23 +0000452 ArrayType::Normal, 0);
453 }
454 return hadError;
455 }
456 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000457 int maxElements = CAT->getMaximumElements();
458 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
459 isStatic, maxElements, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000460 return hadError;
461 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000462 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
463 int maxElements = 1;
464 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
465 hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000466 return hadError;
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000467 }
468 // FIXME: Handle struct/union types.
Steve Naroff1c9de712007-09-03 01:24:23 +0000469 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +0000470}
471
Chris Lattner4b009652007-07-25 00:24:17 +0000472Sema::DeclTy *
Steve Naroff0acc9c92007-09-15 18:49:24 +0000473Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000474 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000475 IdentifierInfo *II = D.getIdentifier();
476
477 // All of these full declarators require an identifier. If it doesn't have
478 // one, the ParsedFreeStandingDeclSpec action should be used.
479 if (II == 0) {
Chris Lattner87492f42007-08-28 06:17:15 +0000480 Diag(D.getDeclSpec().getSourceRange().Begin(),
481 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000482 D.getDeclSpec().getSourceRange(), D.getSourceRange());
483 return 0;
484 }
485
Chris Lattnera7549902007-08-26 06:24:45 +0000486 // The scope passed in may not be a decl scope. Zip up the scope tree until
487 // we find one that is.
488 while ((S->getFlags() & Scope::DeclScope) == 0)
489 S = S->getParent();
490
Chris Lattner4b009652007-07-25 00:24:17 +0000491 // See if this is a redefinition of a variable in the same scope.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000492 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
493 D.getIdentifierLoc(), S);
Chris Lattner4b009652007-07-25 00:24:17 +0000494 if (PrevDecl && !S->isDeclScope(PrevDecl))
495 PrevDecl = 0; // If in outer scope, it isn't the same thing.
496
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000497 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000498 bool InvalidDecl = false;
499
Chris Lattner4b009652007-07-25 00:24:17 +0000500 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner4b009652007-07-25 00:24:17 +0000501 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
502 if (!NewTD) return 0;
503
504 // Handle attributes prior to checking for duplicates in MergeVarDecl
505 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
506 D.getAttributes());
507 // Merge the decl with the existing one if appropriate.
508 if (PrevDecl) {
509 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
510 if (NewTD == 0) return 0;
511 }
512 New = NewTD;
513 if (S->getParent() == 0) {
514 // C99 6.7.7p2: If a typedef name specifies a variably modified type
515 // then it shall have block scope.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000516 if (const VariableArrayType *VAT =
517 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
518 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
519 VAT->getSizeExpr()->getSourceRange());
520 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000521 }
522 }
523 } else if (D.isFunctionDeclarator()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000524 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000525 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000526
Chris Lattner265c8172007-09-27 15:15:46 +0000527 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000528 switch (D.getDeclSpec().getStorageClassSpec()) {
529 default: assert(0 && "Unknown storage class!");
530 case DeclSpec::SCS_auto:
531 case DeclSpec::SCS_register:
532 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
533 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000534 InvalidDecl = true;
535 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000536 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
537 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
538 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
539 }
540
541 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000542 D.getDeclSpec().isInlineSpecified(),
Chris Lattner4b009652007-07-25 00:24:17 +0000543 LastDeclarator);
544
545 // Merge the decl with the existing one if appropriate.
546 if (PrevDecl) {
547 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
548 if (NewFD == 0) return 0;
549 }
550 New = NewFD;
551 } else {
552 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffcae537d2007-08-28 18:45:29 +0000553 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000554
555 VarDecl *NewVD;
556 VarDecl::StorageClass SC;
557 switch (D.getDeclSpec().getStorageClassSpec()) {
558 default: assert(0 && "Unknown storage class!");
559 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
560 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
561 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
562 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
563 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
564 }
565 if (S->getParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000566 // C99 6.9p2: The storage-class specifiers auto and register shall not
567 // appear in the declaration specifiers in an external declaration.
568 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
569 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
570 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000571 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000572 }
Chris Lattner4b009652007-07-25 00:24:17 +0000573 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000574 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000575 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000576 }
Chris Lattner4b009652007-07-25 00:24:17 +0000577 // Handle attributes prior to checking for duplicates in MergeVarDecl
578 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
579 D.getAttributes());
580
581 // Merge the decl with the existing one if appropriate.
582 if (PrevDecl) {
583 NewVD = MergeVarDecl(NewVD, PrevDecl);
584 if (NewVD == 0) return 0;
585 }
Chris Lattner4b009652007-07-25 00:24:17 +0000586 New = NewVD;
587 }
588
589 // If this has an identifier, add it to the scope stack.
590 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000591 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000592 II->setFETokenInfo(New);
593 S->AddDecl(New);
594 }
595
596 if (S->getParent() == 0)
597 AddTopLevelDecl(New, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000598
599 // If any semantic error occurred, mark the decl as invalid.
600 if (D.getInvalidType() || InvalidDecl)
601 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000602
603 return New;
604}
605
Steve Naroff6a0e2092007-09-12 14:07:44 +0000606void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000607 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000608 Expr *Init = static_cast<Expr *>(init);
609
Steve Naroff420d0f52007-09-12 20:13:48 +0000610 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +0000611
Steve Naroff420d0f52007-09-12 20:13:48 +0000612 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
613 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +0000614 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
615 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +0000616 RealDecl->setInvalidDecl();
617 return;
618 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000619 // Get the decls type and save a reference for later, since
620 // CheckInitializer may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +0000621 QualType DclT = VDecl->getType(), SavT = DclT;
622 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000623 VarDecl::StorageClass SC = BVD->getStorageClass();
624 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +0000625 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000626 BVD->setInvalidDecl();
627 } else if (!BVD->isInvalidDecl()) {
628 CheckInitializer(Init, DclT, SC == VarDecl::Static);
629 }
Steve Naroff420d0f52007-09-12 20:13:48 +0000630 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000631 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +0000632 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000633 if (!FVD->isInvalidDecl())
634 CheckInitializer(Init, DclT, true);
635 }
636 // If the type changed, it means we had an incomplete type that was
637 // completed by the initializer. For example:
638 // int ary[] = { 1, 3, 5 };
639 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff420d0f52007-09-12 20:13:48 +0000640 if (!VDecl->isInvalidDecl() && (DclT != SavT))
641 VDecl->setType(DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000642
643 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +0000644 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000645 return;
646}
647
Chris Lattner4b009652007-07-25 00:24:17 +0000648/// The declarators are chained together backwards, reverse the list.
649Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
650 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000651 Decl *GroupDecl = static_cast<Decl*>(group);
652 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +0000653 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +0000654
655 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
656 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000657 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000658 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000659 else { // reverse the list.
660 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000661 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +0000662 Group->setNextDeclarator(NewGroup);
663 NewGroup = Group;
664 Group = Next;
665 }
666 }
667 // Perform semantic analysis that depends on having fully processed both
668 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000669 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000670 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
671 if (!IDecl)
672 continue;
673 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
674 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
675 QualType T = IDecl->getType();
676
677 // C99 6.7.5.2p2: If an identifier is declared to be an object with
678 // static storage duration, it shall not have a variable length array.
679 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
680 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
681 if (VLA->getSizeExpr()) {
682 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
683 IDecl->setInvalidDecl();
684 }
685 }
686 }
687 // Block scope. C99 6.7p7: If an identifier for an object is declared with
688 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
689 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
690 if (T->isIncompleteType()) {
691 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
692 T.getAsString());
693 IDecl->setInvalidDecl();
694 }
695 }
696 // File scope. C99 6.9.2p2: A declaration of an identifier for and
697 // object that has file scope without an initializer, and without a
698 // storage-class specifier or with the storage-class specifier "static",
699 // constitutes a tentative definition. Note: A tentative definition with
700 // external linkage is valid (C99 6.2.2p5).
701 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
702 // C99 6.9.2p3: If the declaration of an identifier for an object is
703 // a tentative definition and has internal linkage (C99 6.2.2p3), the
704 // declared type shall not be an incomplete type.
705 if (T->isIncompleteType()) {
706 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
707 T.getAsString());
708 IDecl->setInvalidDecl();
709 }
710 }
Chris Lattner4b009652007-07-25 00:24:17 +0000711 }
712 return NewGroup;
713}
Steve Naroff91b03f72007-08-28 03:03:08 +0000714
715// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000716ParmVarDecl *
717Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
718 Scope *FnScope) {
719 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
720
721 IdentifierInfo *II = PI.Ident;
722 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
723 // Can this happen for params? We already checked that they don't conflict
724 // among each other. Here they can only shadow globals, which is ok.
725 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
726 PI.IdentLoc, FnScope)) {
727
728 }
729
730 // FIXME: Handle storage class (auto, register). No declarator?
731 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000732
733 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
734 // Doing the promotion here has a win and a loss. The win is the type for
735 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
736 // code generator). The loss is the orginal type isn't preserved. For example:
737 //
738 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
739 // int blockvardecl[5];
740 // sizeof(parmvardecl); // size == 4
741 // sizeof(blockvardecl); // size == 20
742 // }
743 //
744 // For expressions, all implicit conversions are captured using the
745 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
746 //
747 // FIXME: If a source translation tool needs to see the original type, then
748 // we need to consider storing both types (in ParmVarDecl)...
749 //
750 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
751 if (const ArrayType *AT = parmDeclType->getAsArrayType())
752 parmDeclType = Context.getPointerType(AT->getElementType());
753 else if (parmDeclType->isFunctionType())
754 parmDeclType = Context.getPointerType(parmDeclType);
755
756 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffcae537d2007-08-28 18:45:29 +0000757 VarDecl::None, 0);
758 if (PI.InvalidType)
759 New->setInvalidDecl();
760
Chris Lattner4b009652007-07-25 00:24:17 +0000761 // If this has an identifier, add it to the scope stack.
762 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000763 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000764 II->setFETokenInfo(New);
765 FnScope->AddDecl(New);
766 }
767
768 return New;
769}
770
771
772Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
773 assert(CurFunctionDecl == 0 && "Function parsing confused");
774 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
775 "Not a function declarator!");
776 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
777
778 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
779 // for a K&R function.
780 if (!FTI.hasPrototype) {
781 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
782 if (FTI.ArgInfo[i].TypeInfo == 0) {
783 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
784 FTI.ArgInfo[i].Ident->getName());
785 // Implicitly declare the argument as type 'int' for lack of a better
786 // type.
787 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
788 }
789 }
790
791 // Since this is a function definition, act as though we have information
792 // about the arguments.
793 FTI.hasPrototype = true;
794 } else {
795 // FIXME: Diagnose arguments without names in C.
796
797 }
798
799 Scope *GlobalScope = FnBodyScope->getParent();
800
801 FunctionDecl *FD =
Steve Naroff0acc9c92007-09-15 18:49:24 +0000802 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattner4b009652007-07-25 00:24:17 +0000803 CurFunctionDecl = FD;
804
805 // Create Decl objects for each parameter, adding them to the FunctionDecl.
806 llvm::SmallVector<ParmVarDecl*, 16> Params;
807
808 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
809 // no arguments, not a function that takes a single void argument.
810 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
811 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
812 // empty arg list, don't push any params.
813 } else {
814 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
815 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
816 }
817
818 FD->setParams(&Params[0], Params.size());
819
820 return FD;
821}
822
823Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
824 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
825 FD->setBody((Stmt*)Body);
826
827 assert(FD == CurFunctionDecl && "Function parsing confused");
828 CurFunctionDecl = 0;
829
830 // Verify and clean out per-function state.
831
832 // Check goto/label use.
833 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
834 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
835 // Verify that we have no forward references left. If so, there was a goto
836 // or address of a label taken, but no definition of it. Label fwd
837 // definitions are indicated with a null substmt.
838 if (I->second->getSubStmt() == 0) {
839 LabelStmt *L = I->second;
840 // Emit error.
841 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
842
843 // At this point, we have gotos that use the bogus label. Stitch it into
844 // the function body so that they aren't leaked and that the AST is well
845 // formed.
846 L->setSubStmt(new NullStmt(L->getIdentLoc()));
847 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
848 }
849 }
850 LabelMap.clear();
851
852 return FD;
853}
854
855
856/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
857/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +0000858ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
859 IdentifierInfo &II, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000860 if (getLangOptions().C99) // Extension in C99.
861 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
862 else // Legal in C90, but warn about it.
863 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
864
865 // FIXME: handle stuff like:
866 // void foo() { extern float X(); }
867 // void bar() { X(); } <-- implicit decl for X in another scope.
868
869 // Set a Declarator for the implicit definition: int foo();
870 const char *Dummy;
871 DeclSpec DS;
872 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
873 Error = Error; // Silence warning.
874 assert(!Error && "Error setting up implicit decl!");
875 Declarator D(DS, Declarator::BlockContext);
876 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
877 D.SetIdentifier(&II, Loc);
878
879 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000880 if (Scope *FnS = S->getFnParent())
881 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000882 while (S->getParent())
883 S = S->getParent();
884
Steve Narofff0c31dd2007-09-16 16:16:00 +0000885 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattner4b009652007-07-25 00:24:17 +0000886}
887
888
889TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
Steve Naroff2591e1b2007-09-13 23:52:58 +0000890 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +0000891 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
892
893 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000894 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000895
896 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000897 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
898 T, LastDeclarator);
899 if (D.getInvalidType())
900 NewTD->setInvalidDecl();
901 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +0000902}
903
Steve Naroff25aace82007-10-03 21:00:46 +0000904Sema::DeclTy *Sema::ActOnStartClassInterface(Scope* S,
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000905 SourceLocation AtInterfaceLoc,
Steve Naroff81f1bba2007-09-06 21:24:23 +0000906 IdentifierInfo *ClassName, SourceLocation ClassLoc,
907 IdentifierInfo *SuperName, SourceLocation SuperLoc,
908 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
909 AttributeList *AttrList) {
910 assert(ClassName && "Missing class identifier");
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000911
912 // Check for another declaration kind with the same name.
913 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
914 ClassLoc, S);
915 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
916 && !isa<ObjcProtocolDecl>(PrevDecl)) {
917 Diag(ClassLoc, diag::err_redefinition_different_kind,
918 ClassName->getName());
919 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
920 }
921
Steve Narofffa465d12007-10-02 20:01:56 +0000922 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahaniana5f40402007-09-20 20:26:44 +0000923 if (IDecl) {
924 // Class already seen. Is it a forward declaration?
Steve Narofff4bc79a2007-10-02 20:26:23 +0000925 if (!IDecl->isForwardDecl())
Fariborz Jahaniana5f40402007-09-20 20:26:44 +0000926 Diag(AtInterfaceLoc, diag::err_duplicate_class_def, ClassName->getName());
Fariborz Jahanianac775832007-09-22 00:01:35 +0000927 else {
Steve Narofff4bc79a2007-10-02 20:26:23 +0000928 IDecl->setForwardDecl(false);
Fariborz Jahanianac775832007-09-22 00:01:35 +0000929 IDecl->AllocIntfRefProtocols(NumProtocols);
930 }
Fariborz Jahaniana5f40402007-09-20 20:26:44 +0000931 }
932 else {
Fariborz Jahanianac775832007-09-22 00:01:35 +0000933 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, NumProtocols, ClassName);
Fariborz Jahanian0b59d9c2007-09-20 17:54:07 +0000934
Fariborz Jahaniana5f40402007-09-20 20:26:44 +0000935 // Chain & install the interface decl into the identifier.
936 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
937 ClassName->setFETokenInfo(IDecl);
938 }
Fariborz Jahanian0b59d9c2007-09-20 17:54:07 +0000939
940 if (SuperName) {
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000941 ObjcInterfaceDecl* SuperClassEntry = 0;
942 // Check if a different kind of symbol declared in this scope.
943 PrevDecl = LookupScopedDecl(SuperName, Decl::IDNS_Ordinary,
944 SuperLoc, S);
945 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
946 && !isa<ObjcProtocolDecl>(PrevDecl)) {
947 Diag(SuperLoc, diag::err_redefinition_different_kind,
948 SuperName->getName());
949 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Fariborz Jahanian0b59d9c2007-09-20 17:54:07 +0000950 }
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000951 else {
952 // Check that super class is previously defined
Steve Narofffa465d12007-10-02 20:01:56 +0000953 SuperClassEntry = getObjCInterfaceDecl(SuperName);
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000954
Steve Narofff4bc79a2007-10-02 20:26:23 +0000955 if (!SuperClassEntry || SuperClassEntry->isForwardDecl()) {
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000956 Diag(AtInterfaceLoc, diag::err_undef_superclass, SuperName->getName(),
957 ClassName->getName());
958 }
959 }
960 IDecl->setSuperClass(SuperClassEntry);
Fariborz Jahanian0b59d9c2007-09-20 17:54:07 +0000961 }
962
Fariborz Jahanianac775832007-09-22 00:01:35 +0000963 /// Check then save referenced protocols
964 for (unsigned int i = 0; i != NumProtocols; i++) {
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +0000965 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtocolNames[i],
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +0000966 ClassLoc);
Steve Narofff4bc79a2007-10-02 20:26:23 +0000967 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanianac775832007-09-22 00:01:35 +0000968 Diag(ClassLoc, diag::err_undef_protocolref,
969 ProtocolNames[i]->getName(),
970 ClassName->getName());
971 IDecl->setIntfRefProtocols((int)i, RefPDecl);
972 }
973
Steve Naroff81f1bba2007-09-06 21:24:23 +0000974 return IDecl;
975}
976
Steve Naroff25aace82007-10-03 21:00:46 +0000977Sema::DeclTy *Sema::ActOnStartProtocolInterface(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +0000978 SourceLocation AtProtoInterfaceLoc,
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +0000979 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
980 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
981 assert(ProtocolName && "Missing protocol identifier");
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +0000982 ObjcProtocolDecl *PDecl = getObjCProtocolDecl(S, ProtocolName, ProtocolLoc);
Fariborz Jahanianc716c942007-09-21 15:40:54 +0000983 if (PDecl) {
984 // Protocol already seen. Better be a forward protocol declaration
Steve Narofff4bc79a2007-10-02 20:26:23 +0000985 if (!PDecl->isForwardDecl())
Fariborz Jahanianc716c942007-09-21 15:40:54 +0000986 Diag(ProtocolLoc, diag::err_duplicate_protocol_def,
987 ProtocolName->getName());
988 else {
Steve Narofff4bc79a2007-10-02 20:26:23 +0000989 PDecl->setForwardDecl(false);
Fariborz Jahanianc716c942007-09-21 15:40:54 +0000990 PDecl->AllocReferencedProtocols(NumProtoRefs);
991 }
992 }
993 else {
994 PDecl = new ObjcProtocolDecl(AtProtoInterfaceLoc, NumProtoRefs,
995 ProtocolName);
Steve Narofff4bc79a2007-10-02 20:26:23 +0000996 PDecl->setForwardDecl(false);
Fariborz Jahanianc716c942007-09-21 15:40:54 +0000997 // Chain & install the protocol decl into the identifier.
998 PDecl->setNext(ProtocolName->getFETokenInfo<ScopedDecl>());
999 ProtocolName->setFETokenInfo(PDecl);
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001000 }
1001
1002 /// Check then save referenced protocols
1003 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +00001004 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtoRefNames[i],
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001005 ProtocolLoc);
Steve Narofff4bc79a2007-10-02 20:26:23 +00001006 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001007 Diag(ProtocolLoc, diag::err_undef_protocolref,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001008 ProtoRefNames[i]->getName(),
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001009 ProtocolName->getName());
1010 PDecl->setReferencedProtocols((int)i, RefPDecl);
1011 }
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001012
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001013 return PDecl;
1014}
1015
Fariborz Jahaniana096e1d2007-10-05 21:01:53 +00001016/// ActOnFindProtocolDeclaration - This routine looks for a previously
1017/// declared protocol and returns it. If not found, issues diagnostic.
1018/// Will build a list of previously protocol declarations found in the list.
1019Action::DeclTy **
1020Sema::ActOnFindProtocolDeclaration(Scope *S,
1021 SourceLocation TypeLoc,
1022 IdentifierInfo **ProtocolId,
1023 unsigned NumProtocols) {
1024 for (unsigned i = 0; i != NumProtocols; ++i) {
1025 ObjcProtocolDecl *PDecl = getObjCProtocolDecl(S, ProtocolId[i],
1026 TypeLoc);
1027 if (!PDecl)
1028 Diag(TypeLoc, diag::err_undeclared_protocol,
1029 ProtocolId[i]->getName());
1030 }
1031 return 0;
1032}
1033
Steve Naroffb4dfe362007-10-02 22:39:18 +00001034/// ActOnForwardProtocolDeclaration -
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001035/// Scope will always be top level file scope.
1036Action::DeclTy *
Steve Naroffb4dfe362007-10-02 22:39:18 +00001037Sema::ActOnForwardProtocolDeclaration(Scope *S, SourceLocation AtProtocolLoc,
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001038 IdentifierInfo **IdentList, unsigned NumElts) {
Chris Lattner6b1ed8d2007-10-06 20:05:59 +00001039 llvm::SmallVector<ObjcProtocolDecl*, 32> Protocols;
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001040
1041 for (unsigned i = 0; i != NumElts; ++i) {
Chris Lattner680f7052007-10-07 07:05:08 +00001042 IdentifierInfo *P = IdentList[i];
1043 ObjcProtocolDecl *PDecl = getObjCProtocolDecl(S, P, AtProtocolLoc);
1044 if (!PDecl) { // Not already seen?
1045 // FIXME: Pass in the location of the identifier!
1046 PDecl = new ObjcProtocolDecl(AtProtocolLoc, 0, P, true);
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001047 // Chain & install the protocol decl into the identifier.
1048 PDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1049 IdentList[i]->setFETokenInfo(PDecl);
Chris Lattner680f7052007-10-07 07:05:08 +00001050
1051 // Remember that this needs to be removed when the scope is popped.
1052 S->AddDecl(PDecl);
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001053 }
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001054
Chris Lattner6b1ed8d2007-10-06 20:05:59 +00001055 Protocols.push_back(PDecl);
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001056 }
Chris Lattner6b1ed8d2007-10-06 20:05:59 +00001057 return new ObjcForwardProtocolDecl(AtProtocolLoc,
1058 &Protocols[0], Protocols.size());
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001059}
1060
Steve Naroff25aace82007-10-03 21:00:46 +00001061Sema::DeclTy *Sema::ActOnStartCategoryInterface(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001062 SourceLocation AtInterfaceLoc,
Fariborz Jahanianf25220e2007-09-18 20:26:58 +00001063 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1064 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1065 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
Chris Lattner910435b2007-10-06 22:53:46 +00001066 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
1067 ObjcCategoryDecl *CDecl = new ObjcCategoryDecl(AtInterfaceLoc, NumProtoRefs,
1068 CategoryName);
Fariborz Jahanianac775832007-09-22 00:01:35 +00001069 CDecl->setClassInterface(IDecl);
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +00001070
Fariborz Jahanianac775832007-09-22 00:01:35 +00001071 /// Check that class of this category is already completely declared.
Steve Narofff4bc79a2007-10-02 20:26:23 +00001072 if (!IDecl || IDecl->isForwardDecl())
Fariborz Jahanianac775832007-09-22 00:01:35 +00001073 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
1074 else {
1075 /// Check for duplicate interface declaration for this category
1076 ObjcCategoryDecl *CDeclChain;
1077 for (CDeclChain = IDecl->getListCategories(); CDeclChain;
1078 CDeclChain = CDeclChain->getNextClassCategory()) {
Chris Lattner910435b2007-10-06 22:53:46 +00001079 if (CDeclChain->getIdentifier() == CategoryName) {
Fariborz Jahanianac775832007-09-22 00:01:35 +00001080 Diag(CategoryLoc, diag::err_dup_category_def, ClassName->getName(),
1081 CategoryName->getName());
1082 break;
1083 }
1084 }
Chris Lattner910435b2007-10-06 22:53:46 +00001085 if (!CDeclChain)
Fariborz Jahanianac775832007-09-22 00:01:35 +00001086 CDecl->insertNextClassCategory();
Fariborz Jahanianac775832007-09-22 00:01:35 +00001087 }
1088
1089 /// Check then save referenced protocols
1090 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +00001091 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtoRefNames[i],
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001092 CategoryLoc);
Steve Narofff4bc79a2007-10-02 20:26:23 +00001093 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanianac775832007-09-22 00:01:35 +00001094 Diag(CategoryLoc, diag::err_undef_protocolref,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001095 ProtoRefNames[i]->getName(),
Fariborz Jahanianac775832007-09-22 00:01:35 +00001096 CategoryName->getName());
1097 CDecl->setCatReferencedProtocols((int)i, RefPDecl);
1098 }
1099
Fariborz Jahanianf25220e2007-09-18 20:26:58 +00001100 return CDecl;
1101}
Fariborz Jahaniana5f40402007-09-20 20:26:44 +00001102
Steve Naroff25aace82007-10-03 21:00:46 +00001103/// ActOnStartCategoryImplementation - Perform semantic checks on the
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001104/// category implementation declaration and build an ObjcCategoryImplDecl
1105/// object.
Steve Naroff25aace82007-10-03 21:00:46 +00001106Sema::DeclTy *Sema::ActOnStartCategoryImplementation(Scope* S,
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001107 SourceLocation AtCatImplLoc,
1108 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1109 IdentifierInfo *CatName, SourceLocation CatLoc) {
Steve Narofffa465d12007-10-02 20:01:56 +00001110 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001111 ObjcCategoryImplDecl *CDecl = new ObjcCategoryImplDecl(AtCatImplLoc,
Chris Lattner79b00842007-10-06 23:12:31 +00001112 CatName, IDecl);
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001113 /// Check that class of this category is already completely declared.
Steve Narofff4bc79a2007-10-02 20:26:23 +00001114 if (!IDecl || IDecl->isForwardDecl())
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001115 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
1116 /// TODO: Check that CatName, category name, is not used in another
1117 // implementation.
1118 return CDecl;
1119}
1120
Steve Naroff25aace82007-10-03 21:00:46 +00001121Sema::DeclTy *Sema::ActOnStartClassImplementation(Scope *S,
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001122 SourceLocation AtClassImplLoc,
1123 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1124 IdentifierInfo *SuperClassname,
1125 SourceLocation SuperClassLoc) {
1126 ObjcInterfaceDecl* IDecl = 0;
1127 // Check for another declaration kind with the same name.
1128 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
1129 ClassLoc, S);
1130 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
1131 Diag(ClassLoc, diag::err_redefinition_different_kind,
1132 ClassName->getName());
1133 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1134 }
1135 else {
1136 // Is there an interface declaration of this class; if not, warn!
Steve Narofffa465d12007-10-02 20:01:56 +00001137 IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001138 if (!IDecl)
1139 Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
1140 }
1141
1142 // Check that super class name is valid class name
1143 ObjcInterfaceDecl* SDecl = 0;
1144 if (SuperClassname) {
1145 // Check if a different kind of symbol declared in this scope.
1146 PrevDecl = LookupScopedDecl(SuperClassname, Decl::IDNS_Ordinary,
1147 SuperClassLoc, S);
1148 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
1149 && !isa<ObjcProtocolDecl>(PrevDecl)) {
1150 Diag(SuperClassLoc, diag::err_redefinition_different_kind,
1151 SuperClassname->getName());
1152 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1153 }
1154 else {
Steve Narofffa465d12007-10-02 20:01:56 +00001155 SDecl = getObjCInterfaceDecl(SuperClassname);
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001156 if (!SDecl)
1157 Diag(SuperClassLoc, diag::err_undef_superclass,
1158 SuperClassname->getName(), ClassName->getName());
1159 else if (IDecl && IDecl->getSuperClass() != SDecl) {
1160 // This implementation and its interface do not have the same
1161 // super class.
1162 Diag(SuperClassLoc, diag::err_conflicting_super_class,
1163 SuperClassname->getName());
1164 Diag(SDecl->getLocation(), diag::err_previous_definition);
1165 }
1166 }
1167 }
1168
1169 ObjcImplementationDecl* IMPDecl =
1170 new ObjcImplementationDecl(AtClassImplLoc, ClassName, SDecl);
Fariborz Jahanian1c0eedb2007-09-25 21:00:20 +00001171 if (!IDecl) {
1172 // Legacy case of @implementation with no corresponding @interface.
1173 // Build, chain & install the interface decl into the identifier.
Fariborz Jahanianfa601d52007-10-04 00:22:33 +00001174 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, ClassName);
Fariborz Jahanian1c0eedb2007-09-25 21:00:20 +00001175 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
1176 ClassName->setFETokenInfo(IDecl);
1177
1178 }
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001179
1180 // Check that there is no duplicate implementation of this class.
Chris Lattnera7a191c2007-10-07 01:13:46 +00001181 if (!ObjcImplementations.insert(ClassName))
1182 Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001183
1184 return IMPDecl;
1185}
1186
Steve Naroff89529b12007-10-02 21:43:37 +00001187void Sema::CheckImplementationIvars(ObjcImplementationDecl *ImpDecl,
1188 ObjcIvarDecl **ivars, unsigned numIvars) {
1189 assert(ImpDecl && "missing implementation decl");
1190 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ImpDecl->getIdentifier());
Fariborz Jahanianfa601d52007-10-04 00:22:33 +00001191 /// 2nd check is added to accomodate case of non-existing @interface decl.
1192 /// (legacy objective-c @implementation decl without an @interface decl).
1193 if (!IDecl || IDecl->ImplicitInterfaceDecl())
Steve Naroff89529b12007-10-02 21:43:37 +00001194 return;
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001195 assert(ivars && "missing @implementation ivars");
1196
Steve Naroff89529b12007-10-02 21:43:37 +00001197 // Check interface's Ivar list against those in the implementation.
1198 // names and types must match.
1199 //
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001200 ObjcIvarDecl** IntfIvars = IDecl->getIntfDeclIvars();
1201 int IntfNumIvars = IDecl->getIntfDeclNumIvars();
1202 unsigned j = 0;
1203 bool err = false;
1204 while (numIvars > 0 && IntfNumIvars > 0) {
1205 ObjcIvarDecl* ImplIvar = ivars[j];
1206 ObjcIvarDecl* ClsIvar = IntfIvars[j++];
1207 assert (ImplIvar && "missing implementation ivar");
1208 assert (ClsIvar && "missing class ivar");
1209 if (ImplIvar->getCanonicalType() != ClsIvar->getCanonicalType()) {
1210 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
1211 ImplIvar->getIdentifier()->getName());
1212 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1213 ClsIvar->getIdentifier()->getName());
1214 }
1215 // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
1216 // as error.
1217 else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1218 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
1219 ImplIvar->getIdentifier()->getName());
1220 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1221 ClsIvar->getIdentifier()->getName());
1222 err = true;
1223 break;
1224 }
1225 --numIvars;
1226 --IntfNumIvars;
1227 }
1228 if (!err && (numIvars > 0 || IntfNumIvars > 0))
1229 Diag(numIvars > 0 ? ivars[j]->getLocation() : IntfIvars[j]->getLocation(),
1230 diag::err_inconsistant_ivar);
1231
1232}
1233
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001234/// CheckProtocolMethodDefs - This routine checks unimpletented methods
1235/// Declared in protocol, and those referenced by it.
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001236void Sema::CheckProtocolMethodDefs(ObjcProtocolDecl *PDecl,
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001237 bool& IncompleteImpl,
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001238 const llvm::DenseSet<void *>& InsMap,
Chris Lattner48ed6f82007-10-05 20:15:24 +00001239 const llvm::DenseSet<Selector> &ClsMap) {
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001240 // check unimplemented instance methods.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001241 ObjcMethodDecl** methods = PDecl->getInstanceMethods();
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001242 for (int j = 0; j < PDecl->getNumInstanceMethods(); j++) {
1243 void * cpv = methods[j]->getSelector().getAsOpaquePtr();
1244 if (!InsMap.count(cpv)) {
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001245 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattner64610dd2007-10-07 01:33:16 +00001246 methods[j]->getSelector().getName());
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001247 IncompleteImpl = true;
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001248 }
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001249 }
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001250 // check unimplemented class methods
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001251 methods = PDecl->getClassMethods();
1252 for (int j = 0; j < PDecl->getNumClassMethods(); j++)
Chris Lattner48ed6f82007-10-05 20:15:24 +00001253 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001254 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattner64610dd2007-10-07 01:33:16 +00001255 methods[j]->getSelector().getName());
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001256 IncompleteImpl = true;
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001257 }
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001258
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001259 // Check on this protocols's referenced protocols, recursively
1260 ObjcProtocolDecl** RefPDecl = PDecl->getReferencedProtocols();
1261 for (int i = 0; i < PDecl->getNumReferencedProtocols(); i++)
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001262 CheckProtocolMethodDefs(RefPDecl[i], IncompleteImpl, InsMap, ClsMap);
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001263}
1264
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001265void Sema::ImplMethodsVsClassMethods(ObjcImplementationDecl* IMPDecl,
1266 ObjcInterfaceDecl* IDecl) {
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001267 llvm::DenseSet<void *> InsMap;
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001268 // Check and see if instance methods in class interface have been
1269 // implemented in the implementation class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001270 ObjcMethodDecl **methods = IMPDecl->getInstanceMethods();
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001271 for (int i=0; i < IMPDecl->getNumInstanceMethods(); i++)
1272 InsMap.insert(methods[i]->getSelector().getAsOpaquePtr());
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001273
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001274 bool IncompleteImpl = false;
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001275 methods = IDecl->getInstanceMethods();
1276 for (int j = 0; j < IDecl->getNumInstanceMethods(); j++)
Steve Naroff6cb1d362007-09-28 22:22:11 +00001277 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001278 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattner64610dd2007-10-07 01:33:16 +00001279 methods[j]->getSelector().getName());
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001280 IncompleteImpl = true;
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001281 }
Chris Lattner48ed6f82007-10-05 20:15:24 +00001282 llvm::DenseSet<Selector> ClsMap;
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001283 // Check and see if class methods in class interface have been
1284 // implemented in the implementation class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001285 methods = IMPDecl->getClassMethods();
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001286 for (int i=0; i < IMPDecl->getNumClassMethods(); i++)
Chris Lattner48ed6f82007-10-05 20:15:24 +00001287 ClsMap.insert(methods[i]->getSelector());
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001288
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001289 methods = IDecl->getClassMethods();
1290 for (int j = 0; j < IDecl->getNumClassMethods(); j++)
Chris Lattner48ed6f82007-10-05 20:15:24 +00001291 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001292 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattner64610dd2007-10-07 01:33:16 +00001293 methods[j]->getSelector().getName());
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001294 IncompleteImpl = true;
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001295 }
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001296
1297 // Check the protocol list for unimplemented methods in the @implementation
1298 // class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001299 ObjcProtocolDecl** protocols = IDecl->getReferencedProtocols();
Chris Lattner48ed6f82007-10-05 20:15:24 +00001300 for (int i = 0; i < IDecl->getNumIntfRefProtocols(); i++)
1301 CheckProtocolMethodDefs(protocols[i], IncompleteImpl, InsMap, ClsMap);
1302
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001303 if (IncompleteImpl)
Fariborz Jahanianfa601d52007-10-04 00:22:33 +00001304 Diag(IMPDecl->getLocation(), diag::warn_incomplete_impl_class,
1305 IMPDecl->getName());
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001306}
1307
1308/// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
1309/// category interface is implemented in the category @implementation.
1310void Sema::ImplCategoryMethodsVsIntfMethods(ObjcCategoryImplDecl *CatImplDecl,
1311 ObjcCategoryDecl *CatClassDecl) {
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001312 llvm::DenseSet<void *> InsMap;
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001313 // Check and see if instance methods in category interface have been
1314 // implemented in its implementation class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001315 ObjcMethodDecl **methods = CatImplDecl->getInstanceMethods();
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001316 for (int i=0; i < CatImplDecl->getNumInstanceMethods(); i++)
1317 InsMap.insert(methods[i]->getSelector().getAsOpaquePtr());
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001318
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001319 bool IncompleteImpl = false;
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001320 methods = CatClassDecl->getInstanceMethods();
1321 for (int j = 0; j < CatClassDecl->getNumInstanceMethods(); j++)
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001322 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001323 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattner64610dd2007-10-07 01:33:16 +00001324 methods[j]->getSelector().getName());
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001325 IncompleteImpl = true;
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001326 }
Chris Lattner48ed6f82007-10-05 20:15:24 +00001327 llvm::DenseSet<Selector> ClsMap;
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001328 // Check and see if class methods in category interface have been
1329 // implemented in its implementation class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001330 methods = CatImplDecl->getClassMethods();
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001331 for (int i=0; i < CatImplDecl->getNumClassMethods(); i++)
Chris Lattner48ed6f82007-10-05 20:15:24 +00001332 ClsMap.insert(methods[i]->getSelector());
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001333
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001334 methods = CatClassDecl->getClassMethods();
1335 for (int j = 0; j < CatClassDecl->getNumClassMethods(); j++)
Chris Lattner48ed6f82007-10-05 20:15:24 +00001336 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001337 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattner64610dd2007-10-07 01:33:16 +00001338 methods[j]->getSelector().getName());
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001339 IncompleteImpl = true;
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001340 }
1341
1342 // Check the protocol list for unimplemented methods in the @implementation
1343 // class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001344 ObjcProtocolDecl** protocols = CatClassDecl->getReferencedProtocols();
1345 for (int i = 0; i < CatClassDecl->getNumReferencedProtocols(); i++) {
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001346 ObjcProtocolDecl* PDecl = protocols[i];
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001347 CheckProtocolMethodDefs(PDecl, IncompleteImpl, InsMap, ClsMap);
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001348 }
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001349 if (IncompleteImpl)
Fariborz Jahanianfa601d52007-10-04 00:22:33 +00001350 Diag(CatImplDecl->getLocation(), diag::warn_incomplete_impl_category,
Chris Lattner910435b2007-10-06 22:53:46 +00001351 CatClassDecl->getName());
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001352}
1353
Steve Naroffb4dfe362007-10-02 22:39:18 +00001354/// ActOnForwardClassDeclaration -
Steve Naroff81f1bba2007-09-06 21:24:23 +00001355/// Scope will always be top level file scope.
1356Action::DeclTy *
Steve Naroffb4dfe362007-10-02 22:39:18 +00001357Sema::ActOnForwardClassDeclaration(Scope *S, SourceLocation AtClassLoc,
1358 IdentifierInfo **IdentList, unsigned NumElts)
1359{
Chris Lattner2443d912007-10-06 20:08:36 +00001360 llvm::SmallVector<ObjcInterfaceDecl*, 32> Interfaces;
1361
Steve Naroff81f1bba2007-09-06 21:24:23 +00001362 for (unsigned i = 0; i != NumElts; ++i) {
Chris Lattner2443d912007-10-06 20:08:36 +00001363 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(IdentList[i]);
1364 if (!IDecl) { // Not already seen? Make a forward decl.
Fariborz Jahanianac775832007-09-22 00:01:35 +00001365 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, IdentList[i], true);
Fariborz Jahaniana5f40402007-09-20 20:26:44 +00001366 // Chain & install the interface decl into the identifier.
1367 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1368 IdentList[i]->setFETokenInfo(IDecl);
Chris Lattner680f7052007-10-07 07:05:08 +00001369
1370 // Remember that this needs to be removed when the scope is popped.
1371 S->AddDecl(IDecl);
Fariborz Jahaniana5f40402007-09-20 20:26:44 +00001372 }
Chris Lattner2443d912007-10-06 20:08:36 +00001373
1374 Interfaces.push_back(IDecl);
Steve Naroff81f1bba2007-09-06 21:24:23 +00001375 }
Chris Lattner2443d912007-10-06 20:08:36 +00001376
1377 return new ObjcClassDecl(AtClassLoc, &Interfaces[0], Interfaces.size());
Steve Naroff81f1bba2007-09-06 21:24:23 +00001378}
1379
Chris Lattner4b009652007-07-25 00:24:17 +00001380
Steve Naroff0acc9c92007-09-15 18:49:24 +00001381/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001382/// former case, Name will be non-null. In the later case, Name will be null.
1383/// TagType indicates what kind of tag this is. TK indicates whether this is a
1384/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001385Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001386 SourceLocation KWLoc, IdentifierInfo *Name,
1387 SourceLocation NameLoc, AttributeList *Attr) {
1388 // If this is a use of an existing tag, it must have a name.
1389 assert((Name != 0 || TK == TK_Definition) &&
1390 "Nameless record must be a definition!");
1391
1392 Decl::Kind Kind;
1393 switch (TagType) {
1394 default: assert(0 && "Unknown tag type!");
1395 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1396 case DeclSpec::TST_union: Kind = Decl::Union; break;
1397//case DeclSpec::TST_class: Kind = Decl::Class; break;
1398 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1399 }
1400
1401 // If this is a named struct, check to see if there was a previous forward
1402 // declaration or definition.
1403 if (TagDecl *PrevDecl =
1404 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1405 NameLoc, S))) {
1406
1407 // If this is a use of a previous tag, or if the tag is already declared in
1408 // the same scope (so that the definition/declaration completes or
1409 // rementions the tag), reuse the decl.
1410 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1411 // Make sure that this wasn't declared as an enum and now used as a struct
1412 // or something similar.
1413 if (PrevDecl->getKind() != Kind) {
1414 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1415 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1416 }
1417
1418 // If this is a use or a forward declaration, we're good.
1419 if (TK != TK_Definition)
1420 return PrevDecl;
1421
1422 // Diagnose attempts to redefine a tag.
1423 if (PrevDecl->isDefinition()) {
1424 Diag(NameLoc, diag::err_redefinition, Name->getName());
1425 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1426 // If this is a redefinition, recover by making this struct be
1427 // anonymous, which will make any later references get the previous
1428 // definition.
1429 Name = 0;
1430 } else {
1431 // Okay, this is definition of a previously declared or referenced tag.
1432 // Move the location of the decl to be the definition site.
1433 PrevDecl->setLocation(NameLoc);
1434 return PrevDecl;
1435 }
1436 }
1437 // If we get here, this is a definition of a new struct type in a nested
1438 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1439 // type.
1440 }
1441
1442 // If there is an identifier, use the location of the identifier as the
1443 // location of the decl, otherwise use the location of the struct/union
1444 // keyword.
1445 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1446
1447 // Otherwise, if this is the first time we've seen this tag, create the decl.
1448 TagDecl *New;
1449 switch (Kind) {
1450 default: assert(0 && "Unknown tag kind!");
1451 case Decl::Enum:
1452 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1453 // enum X { A, B, C } D; D should chain to X.
1454 New = new EnumDecl(Loc, Name, 0);
1455 // If this is an undefined enum, warn.
1456 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1457 break;
1458 case Decl::Union:
1459 case Decl::Struct:
1460 case Decl::Class:
1461 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1462 // struct X { int A; } D; D should chain to X.
1463 New = new RecordDecl(Kind, Loc, Name, 0);
1464 break;
1465 }
1466
1467 // If this has an identifier, add it to the scope stack.
1468 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001469 // The scope passed in may not be a decl scope. Zip up the scope tree until
1470 // we find one that is.
1471 while ((S->getFlags() & Scope::DeclScope) == 0)
1472 S = S->getParent();
1473
1474 // Add it to the decl chain.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001475 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001476 Name->setFETokenInfo(New);
1477 S->AddDecl(New);
1478 }
1479
1480 return New;
1481}
1482
Steve Naroff0acc9c92007-09-15 18:49:24 +00001483/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001484/// to create a FieldDecl object for it.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001485Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001486 SourceLocation DeclStart,
1487 Declarator &D, ExprTy *BitfieldWidth) {
1488 IdentifierInfo *II = D.getIdentifier();
1489 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001490 SourceLocation Loc = DeclStart;
1491 if (II) Loc = D.getIdentifierLoc();
1492
1493 // FIXME: Unnamed fields can be handled in various different ways, for
1494 // example, unnamed unions inject all members into the struct namespace!
1495
1496
1497 if (BitWidth) {
1498 // TODO: Validate.
1499 //printf("WARNING: BITFIELDS IGNORED!\n");
1500
1501 // 6.7.2.1p3
1502 // 6.7.2.1p4
1503
1504 } else {
1505 // Not a bitfield.
1506
1507 // validate II.
1508
1509 }
1510
1511 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001512 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1513 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001514
Chris Lattner4b009652007-07-25 00:24:17 +00001515 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1516 // than a variably modified type.
Steve Naroff5eb879b2007-08-31 17:20:07 +00001517 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1518 Diag(Loc, diag::err_typecheck_illegal_vla,
1519 VAT->getSizeExpr()->getSourceRange());
1520 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001521 }
Chris Lattner4b009652007-07-25 00:24:17 +00001522 // FIXME: Chain fielddecls together.
Steve Naroff75494892007-09-11 21:17:26 +00001523 FieldDecl *NewFD;
1524
1525 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Naroffdc1ad762007-09-14 02:20:46 +00001526 NewFD = new FieldDecl(Loc, II, T);
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001527 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl))
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001528 || isa<ObjcImplementationDecl>(static_cast<Decl *>(TagDecl)))
Steve Naroffdc1ad762007-09-14 02:20:46 +00001529 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff75494892007-09-11 21:17:26 +00001530 else
Steve Naroff0acc9c92007-09-15 18:49:24 +00001531 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff75494892007-09-11 21:17:26 +00001532
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001533 if (D.getInvalidType() || InvalidDecl)
1534 NewFD->setInvalidDecl();
1535 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001536}
1537
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001538/// TranslateIvarVisibility - Translate visibility from a token ID to an
1539/// AST enum value.
1540static ObjcIvarDecl::AccessControl
1541TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001542 switch (ivarVisibility) {
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001543 case tok::objc_private: return ObjcIvarDecl::Private;
1544 case tok::objc_public: return ObjcIvarDecl::Public;
1545 case tok::objc_protected: return ObjcIvarDecl::Protected;
1546 case tok::objc_package: return ObjcIvarDecl::Package;
1547 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001548 }
1549}
1550
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00001551void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001552 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001553 DeclTy **Fields, unsigned NumFields,
1554 tok::ObjCKeywordKind *visibility) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001555 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1556 assert(EnclosingDecl && "missing record or interface decl");
1557 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1558
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001559 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001560 // Diagnose code like:
1561 // struct S { struct S {} X; };
1562 // We discover this when we complete the outer S. Reject and ignore the
1563 // outer S.
1564 Diag(Record->getLocation(), diag::err_nested_redefinition,
1565 Record->getKindName());
1566 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001567 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001568 return;
1569 }
Chris Lattner4b009652007-07-25 00:24:17 +00001570 // Verify that all the fields are okay.
1571 unsigned NumNamedMembers = 0;
1572 llvm::SmallVector<FieldDecl*, 32> RecFields;
1573 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00001574
Chris Lattner4b009652007-07-25 00:24:17 +00001575 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001576
Steve Naroff9bb759f2007-09-14 22:20:54 +00001577 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1578 assert(FD && "missing field decl");
1579
1580 // Remember all fields.
1581 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00001582
1583 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001584 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +00001585
Steve Naroffffeaa552007-09-14 23:09:53 +00001586 // If we have visibility info, make sure the AST is set accordingly.
1587 if (visibility)
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001588 cast<ObjcIvarDecl>(FD)->setAccessControl(
1589 TranslateIvarVisibility(visibility[i]));
Steve Naroffffeaa552007-09-14 23:09:53 +00001590
Chris Lattner4b009652007-07-25 00:24:17 +00001591 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001592 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001593 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00001594 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001595 FD->setInvalidDecl();
1596 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001597 continue;
1598 }
Chris Lattner4b009652007-07-25 00:24:17 +00001599 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1600 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001601 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001602 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001603 FD->setInvalidDecl();
1604 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001605 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001606 }
Chris Lattner4b009652007-07-25 00:24:17 +00001607 if (i != NumFields-1 || // ... that the last member ...
1608 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001609 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001610 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001611 FD->setInvalidDecl();
1612 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001613 continue;
1614 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001615 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00001616 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1617 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001618 FD->setInvalidDecl();
1619 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001620 continue;
1621 }
Chris Lattner4b009652007-07-25 00:24:17 +00001622 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001623 if (Record)
1624 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001625 }
Chris Lattner4b009652007-07-25 00:24:17 +00001626 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1627 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001628 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001629 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1630 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001631 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner4b009652007-07-25 00:24:17 +00001632 Record->setHasFlexibleArrayMember(true);
1633 } else {
1634 // If this is a struct/class and this is not the last element, reject
1635 // it. Note that GCC supports variable sized arrays in the middle of
1636 // structures.
1637 if (i != NumFields-1) {
1638 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1639 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001640 FD->setInvalidDecl();
1641 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001642 continue;
1643 }
Chris Lattner4b009652007-07-25 00:24:17 +00001644 // We support flexible arrays at the end of structs in other structs
1645 // as an extension.
1646 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1647 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001648 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001649 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001650 }
1651 }
1652 }
Chris Lattner4b009652007-07-25 00:24:17 +00001653 // Keep track of the number of named members.
1654 if (IdentifierInfo *II = FD->getIdentifier()) {
1655 // Detect duplicate member names.
1656 if (!FieldIDs.insert(II)) {
1657 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1658 // Find the previous decl.
1659 SourceLocation PrevLoc;
1660 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1661 assert(i != e && "Didn't find previous def!");
1662 if (RecFields[i]->getIdentifier() == II) {
1663 PrevLoc = RecFields[i]->getLocation();
1664 break;
1665 }
1666 }
1667 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001668 FD->setInvalidDecl();
1669 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001670 continue;
1671 }
1672 ++NumNamedMembers;
1673 }
Chris Lattner4b009652007-07-25 00:24:17 +00001674 }
1675
Chris Lattner4b009652007-07-25 00:24:17 +00001676 // Okay, we successfully defined 'Record'.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001677 if (Record)
1678 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001679 else {
1680 ObjcIvarDecl **ClsFields =
1681 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001682 if (isa<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1683 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1684 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1685 else if (isa<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1686 ObjcImplementationDecl* IMPDecl =
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001687 cast<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl));
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001688 assert(IMPDecl && "ActOnFields - missing ObjcImplementationDecl");
1689 IMPDecl->ObjcAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Steve Naroff89529b12007-10-02 21:43:37 +00001690 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size());
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001691 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001692 }
Chris Lattner4b009652007-07-25 00:24:17 +00001693}
1694
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001695/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1696/// returns true, or false, accordingly.
1697/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1698bool Sema:: MatchTwoMethodDeclarations(const ObjcMethodDecl *Method,
1699 const ObjcMethodDecl *PrevMethod) {
1700 if (Method->getMethodType().getCanonicalType() !=
1701 PrevMethod->getMethodType().getCanonicalType())
1702 return false;
1703 for (int i = 0; i < Method->getNumParams(); i++) {
1704 ParmVarDecl *ParamDecl = Method->getParamDecl(i);
1705 ParmVarDecl *PrevParamDecl = PrevMethod->getParamDecl(i);
1706 if (ParamDecl->getCanonicalType() != PrevParamDecl->getCanonicalType())
1707 return false;
1708 }
1709 return true;
1710}
1711
Chris Lattner910435b2007-10-06 22:53:46 +00001712void Sema::ActOnAddMethodsToObjcDecl(Scope* S, DeclTy *classDecl,
Steve Naroff25aace82007-10-03 21:00:46 +00001713 DeclTy **allMethods, unsigned allNum) {
Chris Lattner910435b2007-10-06 22:53:46 +00001714 Decl *ClassDecl = static_cast<Decl *>(classDecl);
1715
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001716 // FIXME: Fix this when we can handle methods declared in protocols.
1717 // See Parser::ParseObjCAtProtocolDeclaration
1718 if (!ClassDecl)
1719 return;
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001720 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1721 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001722
1723 llvm::DenseMap<void *, const ObjcMethodDecl*> InsMap;
1724 llvm::DenseMap<void *, const ObjcMethodDecl*> ClsMap;
1725
1726 bool isClassDeclaration =
Chris Lattner910435b2007-10-06 22:53:46 +00001727 (isa<ObjcInterfaceDecl>(ClassDecl) || isa<ObjcCategoryDecl>(ClassDecl));
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001728
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001729 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001730 ObjcMethodDecl *Method =
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001731 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1732 if (!Method) continue; // Already issued a diagnostic.
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001733 if (Method->isInstance()) {
1734 if (isClassDeclaration) {
1735 /// Check for instance method of the same name with incompatible types
1736 const ObjcMethodDecl *&PrevMethod =
1737 InsMap[Method->getSelector().getAsOpaquePtr()];
1738 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001739 Diag(Method->getLocation(), diag::error_duplicate_method_decl,
Chris Lattner64610dd2007-10-07 01:33:16 +00001740 Method->getSelector().getName());
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001741 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
1742 }
1743 else {
1744 insMethods.push_back(Method);
1745 InsMap[Method->getSelector().getAsOpaquePtr()] = Method;
1746 }
1747 }
1748 else
1749 insMethods.push_back(Method);
1750 }
1751 else {
1752 if (isClassDeclaration) {
1753 /// Check for class method of the same name with incompatible types
1754 const ObjcMethodDecl *&PrevMethod =
1755 ClsMap[Method->getSelector().getAsOpaquePtr()];
1756 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001757 Diag(Method->getLocation(), diag::error_duplicate_method_decl,
Chris Lattner64610dd2007-10-07 01:33:16 +00001758 Method->getSelector().getName());
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001759 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
1760 }
1761 else {
1762 clsMethods.push_back(Method);
1763 ClsMap[Method->getSelector().getAsOpaquePtr()] = Method;
1764 }
1765 }
1766 else
1767 clsMethods.push_back(Method);
1768 }
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001769 }
Chris Lattner910435b2007-10-06 22:53:46 +00001770
1771 if (ObjcInterfaceDecl *I = dyn_cast<ObjcInterfaceDecl>(ClassDecl)) {
1772 I->ObjcAddMethods(&insMethods[0], insMethods.size(),
1773 &clsMethods[0], clsMethods.size());
1774 } else if (ObjcProtocolDecl *P = dyn_cast<ObjcProtocolDecl>(ClassDecl)) {
1775 P->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1776 &clsMethods[0], clsMethods.size());
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001777 }
Chris Lattner910435b2007-10-06 22:53:46 +00001778 else if (ObjcCategoryDecl *C = dyn_cast<ObjcCategoryDecl>(ClassDecl)) {
1779 C->ObjcAddCatMethods(&insMethods[0], insMethods.size(),
1780 &clsMethods[0], clsMethods.size());
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001781 }
Chris Lattner910435b2007-10-06 22:53:46 +00001782 else if (ObjcImplementationDecl *IC =
1783 dyn_cast<ObjcImplementationDecl>(ClassDecl)) {
1784 IC->ObjcAddImplMethods(&insMethods[0], insMethods.size(),
1785 &clsMethods[0], clsMethods.size());
1786 if (ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(IC->getIdentifier()))
1787 ImplMethodsVsClassMethods(IC, IDecl);
1788 } else {
1789 ObjcCategoryImplDecl* CatImplClass = cast<ObjcCategoryImplDecl>(ClassDecl);
1790 CatImplClass->ObjcAddCatImplMethods(&insMethods[0], insMethods.size(),
1791 &clsMethods[0], clsMethods.size());
1792 ObjcInterfaceDecl* IDecl = CatImplClass->getClassInterface();
1793 // Find category interface decl and then check that all methods declared
1794 // in this interface is implemented in the category @implementation.
1795 if (IDecl) {
1796 for (ObjcCategoryDecl *Categories = IDecl->getListCategories();
1797 Categories; Categories = Categories->getNextClassCategory()) {
Chris Lattner79b00842007-10-06 23:12:31 +00001798 if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
Chris Lattner910435b2007-10-06 22:53:46 +00001799 ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
1800 break;
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001801 }
1802 }
1803 }
1804 }
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001805}
1806
Steve Naroffb4dfe362007-10-02 22:39:18 +00001807Sema::DeclTy *Sema::ActOnMethodDeclaration(SourceLocation MethodLoc,
Steve Naroff6cb1d362007-09-28 22:22:11 +00001808 tok::TokenKind MethodType, TypeTy *ReturnType, Selector Sel,
Steve Naroff4ed9d662007-09-27 14:38:14 +00001809 // optional arguments. The number of types/arguments is obtained
1810 // from the Sel.getNumArgs().
1811 TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1812 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind) {
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001813 llvm::SmallVector<ParmVarDecl*, 16> Params;
1814
Steve Naroff6cb1d362007-09-28 22:22:11 +00001815 for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001816 // FIXME: arg->AttrList must be stored too!
Steve Naroff4ed9d662007-09-27 14:38:14 +00001817 ParmVarDecl* Param = new ParmVarDecl(SourceLocation(/*FIXME*/), ArgNames[i],
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001818 QualType::getFromOpaquePtr(ArgTypes[i]),
1819 VarDecl::None, 0);
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001820 Params.push_back(Param);
1821 }
1822 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Steve Naroff4ed9d662007-09-27 14:38:14 +00001823 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc, Sel,
1824 resultDeclType, 0, -1, AttrList,
Fariborz Jahaniana00e0742007-09-29 18:24:58 +00001825 MethodType == tok::minus,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001826 MethodDeclKind == tok::objc_optional ?
1827 ObjcMethodDecl::Optional :
1828 ObjcMethodDecl::Required);
Steve Naroff6cb1d362007-09-28 22:22:11 +00001829 ObjcMethod->setMethodParams(&Params[0], Sel.getNumArgs());
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001830 return ObjcMethod;
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001831}
1832
Steve Naroff0acc9c92007-09-15 18:49:24 +00001833Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001834 DeclTy *lastEnumConst,
1835 SourceLocation IdLoc, IdentifierInfo *Id,
1836 SourceLocation EqualLoc, ExprTy *val) {
1837 theEnumDecl = theEnumDecl; // silence unused warning.
1838 EnumConstantDecl *LastEnumConst =
1839 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1840 Expr *Val = static_cast<Expr*>(val);
1841
Chris Lattnera7549902007-08-26 06:24:45 +00001842 // The scope passed in may not be a decl scope. Zip up the scope tree until
1843 // we find one that is.
1844 while ((S->getFlags() & Scope::DeclScope) == 0)
1845 S = S->getParent();
1846
Chris Lattner4b009652007-07-25 00:24:17 +00001847 // Verify that there isn't already something declared with this name in this
1848 // scope.
Steve Naroffcb597472007-09-13 21:41:19 +00001849 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1850 IdLoc, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001851 if (S->isDeclScope(PrevDecl)) {
1852 if (isa<EnumConstantDecl>(PrevDecl))
1853 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1854 else
1855 Diag(IdLoc, diag::err_redefinition, Id->getName());
1856 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1857 // FIXME: Don't leak memory: delete Val;
1858 return 0;
1859 }
1860 }
1861
1862 llvm::APSInt EnumVal(32);
1863 QualType EltTy;
1864 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001865 // Make sure to promote the operand type to int.
1866 UsualUnaryConversions(Val);
1867
Chris Lattner4b009652007-07-25 00:24:17 +00001868 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1869 SourceLocation ExpLoc;
1870 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1871 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1872 Id->getName());
1873 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001874 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001875 } else {
1876 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001877 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001878 }
1879
1880 if (!Val) {
1881 if (LastEnumConst) {
1882 // Assign the last value + 1.
1883 EnumVal = LastEnumConst->getInitVal();
1884 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001885
1886 // Check for overflow on increment.
1887 if (EnumVal < LastEnumConst->getInitVal())
1888 Diag(IdLoc, diag::warn_enum_value_overflow);
1889
Chris Lattnere7f53a42007-08-27 17:37:24 +00001890 EltTy = LastEnumConst->getType();
1891 } else {
1892 // First value, set to zero.
1893 EltTy = Context.IntTy;
Chris Lattner3496d522007-09-04 02:45:27 +00001894 EnumVal.zextOrTrunc(
1895 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001896 }
Chris Lattner4b009652007-07-25 00:24:17 +00001897 }
1898
Chris Lattner4b009652007-07-25 00:24:17 +00001899 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1900 LastEnumConst);
1901
1902 // Register this decl in the current scope stack.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001903 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001904 Id->setFETokenInfo(New);
1905 S->AddDecl(New);
1906 return New;
1907}
1908
Steve Naroff0acc9c92007-09-15 18:49:24 +00001909void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00001910 DeclTy **Elements, unsigned NumElements) {
1911 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1912 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1913
Chris Lattner435c3fd2007-08-28 05:10:31 +00001914 // TODO: If the result value doesn't fit in an int, it must be a long or long
1915 // long value. ISO C does not support this, but GCC does as an extension,
1916 // emit a warning.
Chris Lattner206754a2007-08-28 06:15:15 +00001917 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner435c3fd2007-08-28 05:10:31 +00001918
1919
Chris Lattner206754a2007-08-28 06:15:15 +00001920 // Verify that all the values are okay, compute the size of the values, and
1921 // reverse the list.
1922 unsigned NumNegativeBits = 0;
1923 unsigned NumPositiveBits = 0;
1924
1925 // Keep track of whether all elements have type int.
1926 bool AllElementsInt = true;
1927
Chris Lattner4b009652007-07-25 00:24:17 +00001928 EnumConstantDecl *EltList = 0;
1929 for (unsigned i = 0; i != NumElements; ++i) {
1930 EnumConstantDecl *ECD =
1931 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1932 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001933
1934 // If the enum value doesn't fit in an int, emit an extension warning.
1935 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1936 "Should have promoted value to int");
1937 const llvm::APSInt &InitVal = ECD->getInitVal();
1938 if (InitVal.getBitWidth() > IntWidth) {
1939 llvm::APSInt V(InitVal);
1940 V.trunc(IntWidth);
1941 V.extend(InitVal.getBitWidth());
1942 if (V != InitVal)
1943 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1944 InitVal.toString());
1945 }
Chris Lattner206754a2007-08-28 06:15:15 +00001946
1947 // Keep track of the size of positive and negative values.
1948 if (InitVal.isUnsigned() || !InitVal.isNegative())
1949 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1950 else
1951 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001952
Chris Lattner206754a2007-08-28 06:15:15 +00001953 // Keep track of whether every enum element has type int (very commmon).
1954 if (AllElementsInt)
1955 AllElementsInt = ECD->getType() == Context.IntTy;
1956
Chris Lattner4b009652007-07-25 00:24:17 +00001957 ECD->setNextDeclarator(EltList);
1958 EltList = ECD;
1959 }
1960
Chris Lattner206754a2007-08-28 06:15:15 +00001961 // Figure out the type that should be used for this enum.
1962 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1963 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001964 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001965
1966 if (NumNegativeBits) {
1967 // If there is a negative value, figure out the smallest integer type (of
1968 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001969 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001970 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001971 BestWidth = IntWidth;
1972 } else {
1973 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1974 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001975 BestType = Context.LongTy;
1976 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001977 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1978 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001979 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1980 BestType = Context.LongLongTy;
1981 }
1982 }
1983 } else {
1984 // If there is no negative value, figure out which of uint, ulong, ulonglong
1985 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001986 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001987 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001988 BestWidth = IntWidth;
1989 } else if (NumPositiveBits <=
1990 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattner206754a2007-08-28 06:15:15 +00001991 BestType = Context.UnsignedLongTy;
1992 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001993 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1994 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001995 "How could an initializer get larger than ULL?");
1996 BestType = Context.UnsignedLongLongTy;
1997 }
1998 }
1999
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002000 // Loop over all of the enumerator constants, changing their types to match
2001 // the type of the enum if needed.
2002 for (unsigned i = 0; i != NumElements; ++i) {
2003 EnumConstantDecl *ECD =
2004 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2005 if (!ECD) continue; // Already issued a diagnostic.
2006
2007 // Standard C says the enumerators have int type, but we allow, as an
2008 // extension, the enumerators to be larger than int size. If each
2009 // enumerator value fits in an int, type it as an int, otherwise type it the
2010 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2011 // that X has type 'int', not 'unsigned'.
2012 if (ECD->getType() == Context.IntTy)
2013 continue; // Already int type.
2014
2015 // Determine whether the value fits into an int.
2016 llvm::APSInt InitVal = ECD->getInitVal();
2017 bool FitsInInt;
2018 if (InitVal.isUnsigned() || !InitVal.isNegative())
2019 FitsInInt = InitVal.getActiveBits() < IntWidth;
2020 else
2021 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2022
2023 // If it fits into an integer type, force it. Otherwise force it to match
2024 // the enum decl type.
2025 QualType NewTy;
2026 unsigned NewWidth;
2027 bool NewSign;
2028 if (FitsInInt) {
2029 NewTy = Context.IntTy;
2030 NewWidth = IntWidth;
2031 NewSign = true;
2032 } else if (ECD->getType() == BestType) {
2033 // Already the right type!
2034 continue;
2035 } else {
2036 NewTy = BestType;
2037 NewWidth = BestWidth;
2038 NewSign = BestType->isSignedIntegerType();
2039 }
2040
2041 // Adjust the APSInt value.
2042 InitVal.extOrTrunc(NewWidth);
2043 InitVal.setIsSigned(NewSign);
2044 ECD->setInitVal(InitVal);
2045
2046 // Adjust the Expr initializer and type.
2047 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2048 ECD->setType(NewTy);
2049 }
Chris Lattner206754a2007-08-28 06:15:15 +00002050
Chris Lattner90a018d2007-08-28 18:24:31 +00002051 Enum->defineElements(EltList, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00002052}
2053
2054void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
2055 if (!current) return;
2056
2057 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
2058 // remember this in the LastInGroupList list.
2059 if (last)
2060 LastInGroupList.push_back((Decl*)last);
2061}
2062
2063void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
2064 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
2065 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2066 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
2067 if (!newType.isNull()) // install the new vector type into the decl
2068 vDecl->setType(newType);
2069 }
2070 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2071 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
2072 rawAttr);
2073 if (!newType.isNull()) // install the new vector type into the decl
2074 tDecl->setUnderlyingType(newType);
2075 }
2076 }
2077 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroff82113e32007-07-29 16:33:31 +00002078 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
2079 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
2080 else
Chris Lattner4b009652007-07-25 00:24:17 +00002081 Diag(rawAttr->getAttributeLoc(),
2082 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner4b009652007-07-25 00:24:17 +00002083 }
2084 // FIXME: add other attributes...
2085}
2086
2087void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2088 AttributeList *declarator_postfix) {
2089 while (declspec_prefix) {
2090 HandleDeclAttribute(New, declspec_prefix);
2091 declspec_prefix = declspec_prefix->getNext();
2092 }
2093 while (declarator_postfix) {
2094 HandleDeclAttribute(New, declarator_postfix);
2095 declarator_postfix = declarator_postfix->getNext();
2096 }
2097}
2098
Steve Naroff82113e32007-07-29 16:33:31 +00002099void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2100 AttributeList *rawAttr) {
2101 QualType curType = tDecl->getUnderlyingType();
Chris Lattner4b009652007-07-25 00:24:17 +00002102 // check the attribute arugments.
2103 if (rawAttr->getNumArgs() != 1) {
2104 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2105 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00002106 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002107 }
2108 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2109 llvm::APSInt vecSize(32);
2110 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
2111 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2112 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00002113 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002114 }
2115 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2116 // in conjunction with complex types (pointers, arrays, functions, etc.).
2117 Type *canonType = curType.getCanonicalType().getTypePtr();
2118 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2119 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2120 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00002121 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002122 }
2123 // unlike gcc's vector_size attribute, the size is specified as the
2124 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00002125 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00002126
2127 if (vectorSize == 0) {
2128 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2129 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00002130 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002131 }
Steve Naroff82113e32007-07-29 16:33:31 +00002132 // Instantiate/Install the vector type, the number of elements is > 0.
2133 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2134 // Remember this typedef decl, we will need it later for diagnostics.
2135 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002136}
2137
2138QualType Sema::HandleVectorTypeAttribute(QualType curType,
2139 AttributeList *rawAttr) {
2140 // check the attribute arugments.
2141 if (rawAttr->getNumArgs() != 1) {
2142 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2143 std::string("1"));
2144 return QualType();
2145 }
2146 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2147 llvm::APSInt vecSize(32);
2148 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
2149 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2150 sizeExpr->getSourceRange());
2151 return QualType();
2152 }
2153 // navigate to the base type - we need to provide for vector pointers,
2154 // vector arrays, and functions returning vectors.
2155 Type *canonType = curType.getCanonicalType().getTypePtr();
2156
2157 if (canonType->isPointerType() || canonType->isArrayType() ||
2158 canonType->isFunctionType()) {
2159 assert(1 && "HandleVector(): Complex type construction unimplemented");
2160 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2161 do {
2162 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2163 canonType = PT->getPointeeType().getTypePtr();
2164 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2165 canonType = AT->getElementType().getTypePtr();
2166 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2167 canonType = FT->getResultType().getTypePtr();
2168 } while (canonType->isPointerType() || canonType->isArrayType() ||
2169 canonType->isFunctionType());
2170 */
2171 }
2172 // the base type must be integer or float.
2173 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2174 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2175 curType.getCanonicalType().getAsString());
2176 return QualType();
2177 }
Chris Lattner3496d522007-09-04 02:45:27 +00002178 unsigned typeSize = static_cast<unsigned>(
2179 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Chris Lattner4b009652007-07-25 00:24:17 +00002180 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00002181 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00002182
2183 // the vector size needs to be an integral multiple of the type size.
2184 if (vectorSize % typeSize) {
2185 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
2186 sizeExpr->getSourceRange());
2187 return QualType();
2188 }
2189 if (vectorSize == 0) {
2190 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2191 sizeExpr->getSourceRange());
2192 return QualType();
2193 }
2194 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
2195 // the number of elements to be a power of two (unlike GCC).
2196 // Instantiate the vector type, the number of elements is > 0.
2197 return Context.getVectorType(curType, vectorSize/typeSize);
2198}
2199