blob: ae9c719471b451786c2730d5a7001decf88a7351 [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +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
Chris Lattnere168f762006-11-10 05:29:30 +000014#include "Sema.h"
Chris Lattner5c5fbcc2006-12-03 08:41:30 +000015#include "clang/AST/ASTContext.h"
Chris Lattner9561a0b2007-01-28 08:20:04 +000016#include "clang/AST/Builtins.h"
Chris Lattnere168f762006-11-10 05:29:30 +000017#include "clang/AST/Decl.h"
Chris Lattner1300fb92007-01-23 23:42:53 +000018#include "clang/AST/Expr.h"
Chris Lattnerf84a79c2006-11-11 22:59:23 +000019#include "clang/AST/Type.h"
Chris Lattner591a6752006-11-19 23:16:18 +000020#include "clang/Parse/DeclSpec.h"
Chris Lattnere168f762006-11-10 05:29:30 +000021#include "clang/Parse/Scope.h"
22#include "clang/Lex/IdentifierTable.h"
Chris Lattnerac18be92006-11-20 06:49:47 +000023#include "clang/Basic/LangOptions.h"
Chris Lattner9561a0b2007-01-28 08:20:04 +000024#include "clang/Basic/TargetInfo.h"
Steve Naroffd54978b2007-09-18 23:55:05 +000025#include "llvm/ADT/SmallString.h"
Chris Lattner38047f92007-01-27 06:24:01 +000026#include "llvm/ADT/SmallSet.h"
Chris Lattner697e5d62006-11-09 06:32:27 +000027using namespace clang;
28
Chris Lattner2ebe4bb2006-11-20 01:29:42 +000029Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Steve Naroff09bf8152007-09-06 21:24:23 +000030 Decl *IIDecl = II.getFETokenInfo<Decl>();
31 if (dyn_cast_or_null<TypedefDecl>(IIDecl) ||
Fariborz Jahanian867a7eb2007-09-18 20:26:58 +000032 dyn_cast_or_null<ObjcInterfaceDecl>(IIDecl))
Steve Naroff09bf8152007-09-06 21:24:23 +000033 return IIDecl;
34 return 0;
Chris Lattnere168f762006-11-10 05:29:30 +000035}
36
Chris Lattner302b4be2006-11-19 02:31:38 +000037void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +000038 if (S->decl_empty()) return;
39 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
40
Chris Lattner302b4be2006-11-19 02:31:38 +000041 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
42 I != E; ++I) {
Steve Naroff9324db12007-09-13 18:10:37 +000043 Decl *TmpD = static_cast<Decl*>(*I);
44 assert(TmpD && "This decl didn't get pushed??");
45 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
46 assert(D && "This decl isn't a ScopedDecl?");
47
Chris Lattnerff65b6b2007-01-23 01:33:16 +000048 IdentifierInfo *II = D->getIdentifier();
49 if (!II) continue;
Chris Lattner302b4be2006-11-19 02:31:38 +000050
Chris Lattnerff65b6b2007-01-23 01:33:16 +000051 // Unlink this decl from the identifier. Because the scope contains decls
52 // in an unordered collection, and because we have multiple identifier
53 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
54 if (II->getFETokenInfo<Decl>() == D) {
55 // Normal case, no multiple decls in different namespaces.
56 II->setFETokenInfo(D->getNext());
57 } else {
58 // Scan ahead. There are only three namespaces in C, so this loop can
59 // never execute more than 3 times.
Steve Naroff9324db12007-09-13 18:10:37 +000060 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Chris Lattnerff65b6b2007-01-23 01:33:16 +000061 while (SomeDecl->getNext() != D) {
62 SomeDecl = SomeDecl->getNext();
63 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
64 }
65 SomeDecl->setNext(D->getNext());
66 }
Chris Lattner302b4be2006-11-19 02:31:38 +000067
Chris Lattner740b2f32006-11-21 01:32:20 +000068 // This will have to be revisited for C++: there we want to nest stuff in
69 // namespace decls etc. Even for C, we might want a top-level translation
70 // unit decl or something.
71 if (!CurFunctionDecl)
72 continue;
73
74 // Chain this decl to the containing function, it now owns the memory for
75 // the decl.
76 D->setNext(CurFunctionDecl->getDeclChain());
77 CurFunctionDecl->setDeclChain(D);
Chris Lattner302b4be2006-11-19 02:31:38 +000078 }
79}
80
Chris Lattner18b19622007-01-22 07:39:13 +000081/// LookupScopedDecl - Look up the inner-most declaration in the specified
82/// namespace.
Steve Naroff9324db12007-09-13 18:10:37 +000083ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
84 SourceLocation IdLoc, Scope *S) {
Chris Lattner18b19622007-01-22 07:39:13 +000085 if (II == 0) return 0;
Chris Lattnerb6738ec2007-01-28 00:38:24 +000086 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
Chris Lattner18b19622007-01-22 07:39:13 +000087
88 // Scan up the scope chain looking for a decl that matches this identifier
89 // that is in the appropriate namespace. This search should not take long, as
90 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroff9324db12007-09-13 18:10:37 +000091 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner18b19622007-01-22 07:39:13 +000092 if (D->getIdentifierNamespace() == NS)
93 return D;
Chris Lattnerb6738ec2007-01-28 00:38:24 +000094
Chris Lattner9561a0b2007-01-28 08:20:04 +000095 // If we didn't find a use of this identifier, and if the identifier
96 // corresponds to a compiler builtin, create the decl object for the builtin
97 // now, injecting it into translation unit scope, and return it.
98 if (NS == Decl::IDNS_Ordinary) {
99 // If this is a builtin on some other target, or if this builtin varies
100 // across targets (e.g. in type), emit a diagnostic and mark the translation
101 // unit non-portable for using it.
102 if (II->isNonPortableBuiltin()) {
103 // Only emit this diagnostic once for this builtin.
104 II->setNonPortableBuiltin(false);
105 Context.Target.DiagnoseNonPortability(IdLoc,
106 diag::port_target_builtin_use);
107 }
Chris Lattner9561a0b2007-01-28 08:20:04 +0000108 // If this is a builtin on this (or all) targets, create the decl.
109 if (unsigned BuiltinID = II->getBuiltinID())
110 return LazilyCreateBuiltin(II, BuiltinID, S);
111 }
Chris Lattner18b19622007-01-22 07:39:13 +0000112 return 0;
113}
114
Chris Lattner9561a0b2007-01-28 08:20:04 +0000115/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
116/// lazily create a decl for it.
Steve Naroff9324db12007-09-13 18:10:37 +0000117ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000118 Builtin::ID BID = (Builtin::ID)bid;
119
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000120 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner776fac82007-06-09 00:53:06 +0000121 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattnerb677a932007-08-26 04:02:13 +0000122 FunctionDecl::Extern, false, 0);
Chris Lattner9561a0b2007-01-28 08:20:04 +0000123
124 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000125 if (Scope *FnS = S->getFnParent())
126 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner9561a0b2007-01-28 08:20:04 +0000127 while (S->getParent())
128 S = S->getParent();
129 S->AddDecl(New);
130
131 // Add this decl to the end of the identifier info.
Steve Naroff9324db12007-09-13 18:10:37 +0000132 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000133 // Scan until we find the last (outermost) decl in the id chain.
134 while (LastDecl->getNext())
135 LastDecl = LastDecl->getNext();
136 // Insert before (outside) it.
137 LastDecl->setNext(New);
138 } else {
139 II->setFETokenInfo(New);
140 }
141 // Make sure clients iterating over decls see this.
142 LastInGroupList.push_back(New);
143
144 return New;
145}
146
Chris Lattner01564d92007-01-27 19:27:06 +0000147/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
148/// and scope as a previous declaration 'Old'. Figure out how to resolve this
149/// situation, merging decls or emitting diagnostics as appropriate.
150///
Steve Naroff9def2b12007-09-13 21:41:19 +0000151TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000152 // Verify the old decl was also a typedef.
153 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
154 if (!Old) {
155 Diag(New->getLocation(), diag::err_redefinition_different_kind,
156 New->getName());
157 Diag(OldD->getLocation(), diag::err_previous_definition);
158 return New;
159 }
160
Chris Lattner01564d92007-01-27 19:27:06 +0000161 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
162 // TODO: This is totally simplistic. It should handle merging functions
163 // together etc, merging extern int X; int X; ...
164 Diag(New->getLocation(), diag::err_redefinition, New->getName());
165 Diag(Old->getLocation(), diag::err_previous_definition);
166 return New;
167}
168
169/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
170/// and scope as a previous declaration 'Old'. Figure out how to resolve this
171/// situation, merging decls or emitting diagnostics as appropriate.
172///
Steve Naroff9def2b12007-09-13 21:41:19 +0000173FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000174 // Verify the old decl was also a function.
175 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
176 if (!Old) {
177 Diag(New->getLocation(), diag::err_redefinition_different_kind,
178 New->getName());
179 Diag(OldD->getLocation(), diag::err_previous_definition);
180 return New;
181 }
182
Chris Lattnerefe4aea2007-01-27 19:35:39 +0000183 // This is not right, but it's a start. If 'Old' is a function prototype with
184 // the same type as 'New', silently allow this. FIXME: We should link up decl
185 // objects here.
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000186 if (Old->getBody() == 0 &&
187 Old->getCanonicalType() == New->getCanonicalType()) {
Chris Lattnerefe4aea2007-01-27 19:35:39 +0000188 return New;
189 }
Chris Lattnerc511efb2007-01-27 19:32:14 +0000190
Chris Lattner01564d92007-01-27 19:27:06 +0000191 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
192 // TODO: This is totally simplistic. It should handle merging functions
193 // together etc, merging extern int X; int X; ...
194 Diag(New->getLocation(), diag::err_redefinition, New->getName());
195 Diag(Old->getLocation(), diag::err_previous_definition);
196 return New;
197}
198
199/// MergeVarDecl - We just parsed a variable 'New' which has the same name
200/// and scope as a previous declaration 'Old'. Figure out how to resolve this
201/// situation, merging decls or emitting diagnostics as appropriate.
202///
Steve Narofffc49d672007-04-01 21:27:45 +0000203/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
204/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
205///
Steve Naroff9def2b12007-09-13 21:41:19 +0000206VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000207 // Verify the old decl was also a variable.
208 VarDecl *Old = dyn_cast<VarDecl>(OldD);
209 if (!Old) {
210 Diag(New->getLocation(), diag::err_redefinition_different_kind,
211 New->getName());
212 Diag(OldD->getLocation(), diag::err_previous_definition);
213 return New;
214 }
Steve Naroff5c131802007-08-30 01:06:46 +0000215 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
216 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
217 bool OldIsTentative = false;
218
219 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
220 // Handle C "tentative" external object definitions. FIXME: finish!
221 if (!OldFSDecl->getInit() &&
222 (OldFSDecl->getStorageClass() == VarDecl::None ||
223 OldFSDecl->getStorageClass() == VarDecl::Static))
224 OldIsTentative = true;
225 }
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000226 // Verify the types match.
227 if (Old->getCanonicalType() != New->getCanonicalType()) {
228 Diag(New->getLocation(), diag::err_redefinition, New->getName());
229 Diag(Old->getLocation(), diag::err_previous_definition);
230 return New;
231 }
232 // We've verified the types match, now check if Old is "extern".
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000233 if (Old->getStorageClass() != VarDecl::Extern) {
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000234 Diag(New->getLocation(), diag::err_redefinition, New->getName());
235 Diag(Old->getLocation(), diag::err_previous_definition);
236 }
Chris Lattner01564d92007-01-27 19:27:06 +0000237 return New;
238}
239
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000240/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
241/// no declarator (e.g. "struct foo;") is parsed.
242Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
243 // TODO: emit error on 'int;' or 'const enum foo;'.
244 // TODO: emit error on 'typedef int;'
245 // if (!DS.isMissingDeclaratorOk()) Diag(...);
246
247 return 0;
248}
249
Steve Naroff77b97002007-09-04 14:36:54 +0000250bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroff2fea1392007-09-02 02:04:30 +0000251 AssignmentCheckResult result;
252 SourceLocation loc = Init->getLocStart();
253 // Get the type before calling CheckSingleAssignmentConstraints(), since
254 // it can promote the expression.
255 QualType rhsType = Init->getType();
256
257 result = CheckSingleAssignmentConstraints(DeclType, Init);
258
259 // decode the result (notice that extensions still return a type).
260 switch (result) {
261 case Compatible:
262 break;
263 case Incompatible:
Steve Narofff33527a2007-09-02 15:34:30 +0000264 // FIXME: tighten up this check which should allow:
265 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
266 if (rhsType == Context.getPointerType(Context.CharTy))
267 break;
Steve Naroff2fea1392007-09-02 02:04:30 +0000268 Diag(loc, diag::err_typecheck_assign_incompatible,
269 DeclType.getAsString(), rhsType.getAsString(),
270 Init->getSourceRange());
271 return true;
272 case PointerFromInt:
273 // check for null pointer constant (C99 6.3.2.3p3)
274 if (!Init->isNullPointerConstant(Context)) {
275 Diag(loc, diag::ext_typecheck_assign_pointer_int,
276 DeclType.getAsString(), rhsType.getAsString(),
277 Init->getSourceRange());
278 return true;
279 }
280 break;
281 case IntFromPointer:
282 Diag(loc, diag::ext_typecheck_assign_pointer_int,
283 DeclType.getAsString(), rhsType.getAsString(),
284 Init->getSourceRange());
285 break;
286 case IncompatiblePointer:
287 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
288 DeclType.getAsString(), rhsType.getAsString(),
289 Init->getSourceRange());
290 break;
291 case CompatiblePointerDiscardsQualifiers:
292 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
293 DeclType.getAsString(), rhsType.getAsString(),
294 Init->getSourceRange());
295 break;
296 }
297 return false;
298}
299
Steve Naroff77b97002007-09-04 14:36:54 +0000300bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
301 bool isStatic, QualType ElementType) {
Steve Naroffac074b42007-09-04 02:20:04 +0000302 SourceLocation loc;
Steve Naroff77b97002007-09-04 14:36:54 +0000303 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffac074b42007-09-04 02:20:04 +0000304
305 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
306 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
307 return true;
308 } else if (CheckSingleInitializer(expr, ElementType)) {
309 return true; // types weren't compatible.
310 }
Steve Naroff77b97002007-09-04 14:36:54 +0000311 if (savExpr != expr) // The type was promoted, update initializer list.
312 IList->setInit(slot, expr);
Steve Naroffac074b42007-09-04 02:20:04 +0000313 return false;
314}
315
316void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
317 QualType ElementType, bool isStatic,
318 int &nInitializers, bool &hadError) {
Steve Narofff33527a2007-09-02 15:34:30 +0000319 for (unsigned i = 0; i < IList->getNumInits(); i++) {
320 Expr *expr = IList->getInit(i);
321
Steve Naroffac074b42007-09-04 02:20:04 +0000322 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
323 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff67ae4432007-09-04 21:13:33 +0000324 int maxElements = CAT->getMaximumElements();
Steve Naroffac074b42007-09-04 02:20:04 +0000325 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
326 maxElements, hadError);
Steve Narofff33527a2007-09-02 15:34:30 +0000327 }
Steve Naroffac074b42007-09-04 02:20:04 +0000328 } else {
Steve Naroff77b97002007-09-04 14:36:54 +0000329 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Narofff33527a2007-09-02 15:34:30 +0000330 }
Steve Naroffac074b42007-09-04 02:20:04 +0000331 nInitializers++;
332 }
333 return;
334}
335
336// FIXME: Doesn't deal with arrays of structures yet.
337void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
338 QualType ElementType, bool isStatic,
339 int &totalInits, bool &hadError) {
340 int maxElementsAtThisLevel = 0;
341 int nInitsAtLevel = 0;
342
343 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
344 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff67ae4432007-09-04 21:13:33 +0000345 maxElementsAtThisLevel = CAT->getMaximumElements();
346 // Set DeclType, used below to recurse (for multi-dimensional arrays).
347 DeclType = CAT->getElementType();
Steve Naroffac074b42007-09-04 02:20:04 +0000348 } else if (DeclType->isScalarType()) {
349 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
350 IList->getSourceRange());
351 maxElementsAtThisLevel = 1;
352 }
353 // The empty init list "{ }" is treated specially below.
354 unsigned numInits = IList->getNumInits();
355 if (numInits) {
356 for (unsigned i = 0; i < numInits; i++) {
357 Expr *expr = IList->getInit(i);
358
359 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
360 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
361 totalInits, hadError);
362 } else {
Steve Naroff77b97002007-09-04 14:36:54 +0000363 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroffac074b42007-09-04 02:20:04 +0000364 nInitsAtLevel++; // increment the number of initializers at this level.
365 totalInits--; // decrement the total number of initializers.
366
367 // Check if we have space for another initializer.
368 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
369 Diag(expr->getLocStart(), diag::warn_excess_initializers,
370 expr->getSourceRange());
371 }
372 }
373 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
374 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
375 } else {
376 // we have an initializer list with no elements.
377 totalInits -= maxElementsAtThisLevel;
378 if (totalInits < 0)
379 Diag(IList->getLocStart(), diag::warn_excess_initializers,
380 IList->getSourceRange());
Steve Narofff33527a2007-09-02 15:34:30 +0000381 }
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000382 return;
Steve Narofff33527a2007-09-02 15:34:30 +0000383}
384
Steve Naroff77b97002007-09-04 14:36:54 +0000385bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Naroff2fea1392007-09-02 02:04:30 +0000386 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000387 if (!InitList)
388 return CheckSingleInitializer(Init, DeclType);
389
Steve Naroff2fea1392007-09-02 02:04:30 +0000390 // We have an InitListExpr, make sure we set the type.
391 Init->setType(DeclType);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000392
393 bool hadError = false;
Steve Narofff33527a2007-09-02 15:34:30 +0000394
Steve Naroffb03f5942007-09-02 20:30:18 +0000395 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
396 // of unknown size ("[]") or an object type that is not a variable array type.
397 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
398 Expr *expr = VAT->getSizeExpr();
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000399 if (expr)
400 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
401 expr->getSourceRange());
402
Steve Naroff67ae4432007-09-04 21:13:33 +0000403 // We have a VariableArrayType with unknown size. Note that only the first
404 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroffac074b42007-09-04 02:20:04 +0000405 int numInits = 0;
Steve Naroff67ae4432007-09-04 21:13:33 +0000406 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
407 isStatic, numInits, hadError);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000408 if (!hadError) {
409 // Return a new array type from the number of initializers (C99 6.7.8p22).
410 llvm::APSInt ConstVal(32);
Steve Naroffac074b42007-09-04 02:20:04 +0000411 ConstVal = numInits;
412 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000413 ArrayType::Normal, 0);
414 }
415 return hadError;
416 }
417 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff67ae4432007-09-04 21:13:33 +0000418 int maxElements = CAT->getMaximumElements();
419 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
420 isStatic, maxElements, hadError);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000421 return hadError;
422 }
Steve Naroffac074b42007-09-04 02:20:04 +0000423 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
424 int maxElements = 1;
425 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
426 hadError);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000427 return hadError;
Steve Naroffb03f5942007-09-02 20:30:18 +0000428 }
429 // FIXME: Handle struct/union types.
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000430 return hadError;
Steve Naroff2fea1392007-09-02 02:04:30 +0000431}
432
Chris Lattner776fac82007-06-09 00:53:06 +0000433Sema::DeclTy *
Steve Naroff30d242c2007-09-15 18:49:24 +0000434Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroffa23cc792007-09-13 23:52:58 +0000435 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattnere168f762006-11-10 05:29:30 +0000436 IdentifierInfo *II = D.getIdentifier();
Chris Lattner302b4be2006-11-19 02:31:38 +0000437
Chris Lattner02c04392007-07-25 00:24:17 +0000438 // All of these full declarators require an identifier. If it doesn't have
439 // one, the ParsedFreeStandingDeclSpec action should be used.
440 if (II == 0) {
Chris Lattnerc4f6d0c2007-08-28 06:17:15 +0000441 Diag(D.getDeclSpec().getSourceRange().Begin(),
442 diag::err_declarator_need_ident,
Chris Lattner02c04392007-07-25 00:24:17 +0000443 D.getDeclSpec().getSourceRange(), D.getSourceRange());
444 return 0;
445 }
446
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000447 // The scope passed in may not be a decl scope. Zip up the scope tree until
448 // we find one that is.
449 while ((S->getFlags() & Scope::DeclScope) == 0)
450 S = S->getParent();
451
Chris Lattner01564d92007-01-27 19:27:06 +0000452 // See if this is a redefinition of a variable in the same scope.
Steve Naroff9324db12007-09-13 18:10:37 +0000453 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
454 D.getIdentifierLoc(), S);
Chris Lattner776fac82007-06-09 00:53:06 +0000455 if (PrevDecl && !S->isDeclScope(PrevDecl))
Chris Lattner01564d92007-01-27 19:27:06 +0000456 PrevDecl = 0; // If in outer scope, it isn't the same thing.
457
Steve Naroff9324db12007-09-13 18:10:37 +0000458 ScopedDecl *New;
Steve Narofff93b6722007-08-28 20:14:24 +0000459 bool InvalidDecl = false;
460
Chris Lattner01a7c532007-01-25 23:09:03 +0000461 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner776fac82007-06-09 00:53:06 +0000462 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
Chris Lattner01564d92007-01-27 19:27:06 +0000463 if (!NewTD) return 0;
Steve Naroffa8fd9732007-06-11 00:35:03 +0000464
465 // Handle attributes prior to checking for duplicates in MergeVarDecl
466 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
467 D.getAttributes());
Chris Lattner01564d92007-01-27 19:27:06 +0000468 // Merge the decl with the existing one if appropriate.
469 if (PrevDecl) {
470 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
471 if (NewTD == 0) return 0;
472 }
473 New = NewTD;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000474 if (S->getParent() == 0) {
475 // C99 6.7.7p2: If a typedef name specifies a variably modified type
476 // then it shall have block scope.
Steve Naroff096dd942007-08-31 17:20:07 +0000477 if (const VariableArrayType *VAT =
478 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
479 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
480 VAT->getSizeExpr()->getSourceRange());
481 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000482 }
483 }
Chris Lattner01a7c532007-01-25 23:09:03 +0000484 } else if (D.isFunctionDeclarator()) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000485 QualType R = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +0000486 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff7a5af782007-07-13 16:58:59 +0000487
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000488 FunctionDecl::StorageClass SC;
489 switch (D.getDeclSpec().getStorageClassSpec()) {
490 default: assert(0 && "Unknown storage class!");
491 case DeclSpec::SCS_auto:
492 case DeclSpec::SCS_register:
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000493 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
494 R.getAsString());
Steve Narofff93b6722007-08-28 20:14:24 +0000495 InvalidDecl = true;
496 break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000497 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
498 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
499 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
500 }
501
Chris Lattner776fac82007-06-09 00:53:06 +0000502 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattnerb677a932007-08-26 04:02:13 +0000503 D.getDeclSpec().isInlineSpecified(),
Chris Lattner776fac82007-06-09 00:53:06 +0000504 LastDeclarator);
Chris Lattner01564d92007-01-27 19:27:06 +0000505
506 // Merge the decl with the existing one if appropriate.
507 if (PrevDecl) {
508 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
509 if (NewFD == 0) return 0;
510 }
511 New = NewFD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000512 } else {
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000513 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffcf871f52007-08-28 18:45:29 +0000514 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner01564d92007-01-27 19:27:06 +0000515
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000516 VarDecl *NewVD;
517 VarDecl::StorageClass SC;
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000518 switch (D.getDeclSpec().getStorageClassSpec()) {
519 default: assert(0 && "Unknown storage class!");
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000520 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
521 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
522 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
523 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
524 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
525 }
Steve Narofffc49d672007-04-01 21:27:45 +0000526 if (S->getParent() == 0) {
Bill Wendlingd6de6572007-06-02 09:40:07 +0000527 // C99 6.9p2: The storage-class specifiers auto and register shall not
528 // appear in the declaration specifiers in an external declaration.
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000529 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000530 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
531 R.getAsString());
Steve Naroffcf871f52007-08-28 18:45:29 +0000532 InvalidDecl = true;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000533 }
Chris Lattner776fac82007-06-09 00:53:06 +0000534 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff2fea1392007-09-02 02:04:30 +0000535 } else {
Chris Lattner776fac82007-06-09 00:53:06 +0000536 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcf871f52007-08-28 18:45:29 +0000537 }
Steve Naroffa8fd9732007-06-11 00:35:03 +0000538 // Handle attributes prior to checking for duplicates in MergeVarDecl
539 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
540 D.getAttributes());
541
Chris Lattner01564d92007-01-27 19:27:06 +0000542 // Merge the decl with the existing one if appropriate.
543 if (PrevDecl) {
544 NewVD = MergeVarDecl(NewVD, PrevDecl);
545 if (NewVD == 0) return 0;
546 }
547 New = NewVD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000548 }
Chris Lattner302b4be2006-11-19 02:31:38 +0000549
Chris Lattnere168f762006-11-10 05:29:30 +0000550 // If this has an identifier, add it to the scope stack.
551 if (II) {
Steve Naroff9324db12007-09-13 18:10:37 +0000552 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattnere168f762006-11-10 05:29:30 +0000553 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000554 S->AddDecl(New);
Chris Lattnere168f762006-11-10 05:29:30 +0000555 }
556
Steve Naroff26c8ea52007-03-21 21:08:52 +0000557 if (S->getParent() == 0)
Chris Lattner776fac82007-06-09 00:53:06 +0000558 AddTopLevelDecl(New, LastDeclarator);
Steve Narofff93b6722007-08-28 20:14:24 +0000559
560 // If any semantic error occurred, mark the decl as invalid.
561 if (D.getInvalidType() || InvalidDecl)
562 New->setInvalidDecl();
Chris Lattnere168f762006-11-10 05:29:30 +0000563
564 return New;
565}
566
Steve Naroff61091402007-09-12 14:07:44 +0000567void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff437b4d82007-09-12 20:13:48 +0000568 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff61091402007-09-12 14:07:44 +0000569 Expr *Init = static_cast<Expr *>(init);
570
Steve Naroff437b4d82007-09-12 20:13:48 +0000571 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroff61091402007-09-12 14:07:44 +0000572
Steve Naroff437b4d82007-09-12 20:13:48 +0000573 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
574 if (!VDecl) {
Steve Naroff9def2b12007-09-13 21:41:19 +0000575 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
576 diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +0000577 RealDecl->setInvalidDecl();
578 return;
579 }
Steve Naroff61091402007-09-12 14:07:44 +0000580 // Get the decls type and save a reference for later, since
581 // CheckInitializer may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +0000582 QualType DclT = VDecl->getType(), SavT = DclT;
583 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff61091402007-09-12 14:07:44 +0000584 VarDecl::StorageClass SC = BVD->getStorageClass();
585 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +0000586 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff61091402007-09-12 14:07:44 +0000587 BVD->setInvalidDecl();
588 } else if (!BVD->isInvalidDecl()) {
589 CheckInitializer(Init, DclT, SC == VarDecl::Static);
590 }
Steve Naroff437b4d82007-09-12 20:13:48 +0000591 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff61091402007-09-12 14:07:44 +0000592 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff437b4d82007-09-12 20:13:48 +0000593 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff61091402007-09-12 14:07:44 +0000594 if (!FVD->isInvalidDecl())
595 CheckInitializer(Init, DclT, true);
596 }
597 // If the type changed, it means we had an incomplete type that was
598 // completed by the initializer. For example:
599 // int ary[] = { 1, 3, 5 };
600 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff437b4d82007-09-12 20:13:48 +0000601 if (!VDecl->isInvalidDecl() && (DclT != SavT))
602 VDecl->setType(DclT);
Steve Naroff61091402007-09-12 14:07:44 +0000603
604 // Attach the initializer to the decl.
Steve Naroff437b4d82007-09-12 20:13:48 +0000605 VDecl->setInit(Init);
Steve Naroff61091402007-09-12 14:07:44 +0000606 return;
607}
608
Chris Lattner776fac82007-06-09 00:53:06 +0000609/// The declarators are chained together backwards, reverse the list.
610Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
611 // Often we have single declarators, handle them quickly.
Steve Naroffa23cc792007-09-13 23:52:58 +0000612 Decl *GroupDecl = static_cast<Decl*>(group);
613 if (GroupDecl == 0)
Steve Naroff61091402007-09-12 14:07:44 +0000614 return 0;
Steve Naroffa23cc792007-09-13 23:52:58 +0000615
616 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
617 ScopedDecl *NewGroup = 0;
Steve Naroff61091402007-09-12 14:07:44 +0000618 if (Group->getNextDeclarator() == 0)
Chris Lattner776fac82007-06-09 00:53:06 +0000619 NewGroup = Group;
Steve Naroff61091402007-09-12 14:07:44 +0000620 else { // reverse the list.
621 while (Group) {
Steve Naroffa23cc792007-09-13 23:52:58 +0000622 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff61091402007-09-12 14:07:44 +0000623 Group->setNextDeclarator(NewGroup);
624 NewGroup = Group;
625 Group = Next;
626 }
627 }
628 // Perform semantic analysis that depends on having fully processed both
629 // the declarator and initializer.
Steve Naroffa23cc792007-09-13 23:52:58 +0000630 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff61091402007-09-12 14:07:44 +0000631 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
632 if (!IDecl)
633 continue;
634 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
635 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
636 QualType T = IDecl->getType();
637
638 // C99 6.7.5.2p2: If an identifier is declared to be an object with
639 // static storage duration, it shall not have a variable length array.
640 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
641 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
642 if (VLA->getSizeExpr()) {
643 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
644 IDecl->setInvalidDecl();
645 }
646 }
647 }
648 // Block scope. C99 6.7p7: If an identifier for an object is declared with
649 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
650 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
651 if (T->isIncompleteType()) {
652 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
653 T.getAsString());
654 IDecl->setInvalidDecl();
655 }
656 }
657 // File scope. C99 6.9.2p2: A declaration of an identifier for and
658 // object that has file scope without an initializer, and without a
659 // storage-class specifier or with the storage-class specifier "static",
660 // constitutes a tentative definition. Note: A tentative definition with
661 // external linkage is valid (C99 6.2.2p5).
662 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
663 // C99 6.9.2p3: If the declaration of an identifier for an object is
664 // a tentative definition and has internal linkage (C99 6.2.2p3), the
665 // declared type shall not be an incomplete type.
666 if (T->isIncompleteType()) {
667 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
668 T.getAsString());
669 IDecl->setInvalidDecl();
670 }
671 }
Chris Lattner776fac82007-06-09 00:53:06 +0000672 }
673 return NewGroup;
674}
Steve Naroff7e6f7c22007-08-28 03:03:08 +0000675
676// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner53621a52007-06-13 20:44:40 +0000677ParmVarDecl *
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000678Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
679 Scope *FnScope) {
680 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
Chris Lattner200bdc32006-11-19 02:43:37 +0000681
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000682 IdentifierInfo *II = PI.Ident;
Chris Lattnerc284e9b2007-01-23 05:14:32 +0000683 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
684 // Can this happen for params? We already checked that they don't conflict
685 // among each other. Here they can only shadow globals, which is ok.
Chris Lattnerd2b88ab2007-07-13 03:05:23 +0000686 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Chris Lattner9561a0b2007-01-28 08:20:04 +0000687 PI.IdentLoc, FnScope)) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000688
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000689 }
690
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000691 // FIXME: Handle storage class (auto, register). No declarator?
Chris Lattner776fac82007-06-09 00:53:06 +0000692 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff773df5c2007-08-07 22:44:21 +0000693
694 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
695 // Doing the promotion here has a win and a loss. The win is the type for
696 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
697 // code generator). The loss is the orginal type isn't preserved. For example:
698 //
699 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
700 // int blockvardecl[5];
701 // sizeof(parmvardecl); // size == 4
702 // sizeof(blockvardecl); // size == 20
703 // }
704 //
705 // For expressions, all implicit conversions are captured using the
706 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
707 //
708 // FIXME: If a source translation tool needs to see the original type, then
709 // we need to consider storing both types (in ParmVarDecl)...
710 //
711 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
712 if (const ArrayType *AT = parmDeclType->getAsArrayType())
713 parmDeclType = Context.getPointerType(AT->getElementType());
714 else if (parmDeclType->isFunctionType())
715 parmDeclType = Context.getPointerType(parmDeclType);
716
717 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffcf871f52007-08-28 18:45:29 +0000718 VarDecl::None, 0);
719 if (PI.InvalidType)
720 New->setInvalidDecl();
721
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000722 // If this has an identifier, add it to the scope stack.
723 if (II) {
Steve Naroff9324db12007-09-13 18:10:37 +0000724 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000725 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000726 FnScope->AddDecl(New);
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000727 }
Chris Lattner229ce602006-11-21 01:21:07 +0000728
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000729 return New;
730}
731
732
733Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner229ce602006-11-21 01:21:07 +0000734 assert(CurFunctionDecl == 0 && "Function parsing confused");
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000735 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
736 "Not a function declarator!");
737 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
738
739 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
740 // for a K&R function.
741 if (!FTI.hasPrototype) {
742 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
743 if (FTI.ArgInfo[i].TypeInfo == 0) {
Chris Lattner843c5922007-06-10 23:40:34 +0000744 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000745 FTI.ArgInfo[i].Ident->getName());
746 // Implicitly declare the argument as type 'int' for lack of a better
747 // type.
748 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
749 }
750 }
751
752 // Since this is a function definition, act as though we have information
753 // about the arguments.
754 FTI.hasPrototype = true;
Chris Lattner2114d5e2006-12-04 07:40:24 +0000755 } else {
756 // FIXME: Diagnose arguments without names in C.
757
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000758 }
759
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000760 Scope *GlobalScope = FnBodyScope->getParent();
761
762 FunctionDecl *FD =
Steve Naroff30d242c2007-09-15 18:49:24 +0000763 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattner229ce602006-11-21 01:21:07 +0000764 CurFunctionDecl = FD;
Chris Lattner2114d5e2006-12-04 07:40:24 +0000765
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000766 // Create Decl objects for each parameter, adding them to the FunctionDecl.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000767 llvm::SmallVector<ParmVarDecl*, 16> Params;
Chris Lattnerf61c8a82007-01-21 19:04:43 +0000768
769 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
770 // no arguments, not a function that takes a single void argument.
771 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
772 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
Chris Lattner99d31772007-01-21 22:37:37 +0000773 // empty arg list, don't push any params.
Chris Lattnerf61c8a82007-01-21 19:04:43 +0000774 } else {
775 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
776 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
777 }
Chris Lattner2114d5e2006-12-04 07:40:24 +0000778
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000779 FD->setParams(&Params[0], Params.size());
Chris Lattner2114d5e2006-12-04 07:40:24 +0000780
Chris Lattnere168f762006-11-10 05:29:30 +0000781 return FD;
782}
783
Chris Lattner229ce602006-11-21 01:21:07 +0000784Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
785 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
786 FD->setBody((Stmt*)Body);
787
788 assert(FD == CurFunctionDecl && "Function parsing confused");
789 CurFunctionDecl = 0;
Chris Lattnere2473062007-05-28 06:28:18 +0000790
791 // Verify and clean out per-function state.
792
793 // Check goto/label use.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000794 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
795 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
Chris Lattnere2473062007-05-28 06:28:18 +0000796 // Verify that we have no forward references left. If so, there was a goto
797 // or address of a label taken, but no definition of it. Label fwd
798 // definitions are indicated with a null substmt.
799 if (I->second->getSubStmt() == 0) {
800 LabelStmt *L = I->second;
801 // Emit error.
Chris Lattnereefa10e2007-05-28 06:56:27 +0000802 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
Chris Lattnere2473062007-05-28 06:28:18 +0000803
804 // At this point, we have gotos that use the bogus label. Stitch it into
805 // the function body so that they aren't leaked and that the AST is well
806 // formed.
807 L->setSubStmt(new NullStmt(L->getIdentLoc()));
808 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
809 }
810 }
811 LabelMap.clear();
812
Chris Lattner229ce602006-11-21 01:21:07 +0000813 return FD;
814}
815
816
Chris Lattnerac18be92006-11-20 06:49:47 +0000817/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
818/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff2f742082007-09-16 16:16:00 +0000819ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
820 IdentifierInfo &II, Scope *S) {
Chris Lattnerac18be92006-11-20 06:49:47 +0000821 if (getLangOptions().C99) // Extension in C99.
822 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
823 else // Legal in C90, but warn about it.
824 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
825
826 // FIXME: handle stuff like:
827 // void foo() { extern float X(); }
828 // void bar() { X(); } <-- implicit decl for X in another scope.
829
830 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +0000831 const char *Dummy;
Chris Lattnerac18be92006-11-20 06:49:47 +0000832 DeclSpec DS;
Chris Lattnerb20e8942006-11-28 05:30:29 +0000833 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
Chris Lattnerb055f2d2007-02-11 08:19:57 +0000834 Error = Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +0000835 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +0000836 Declarator D(DS, Declarator::BlockContext);
Chris Lattnercbc426d2006-12-02 06:43:02 +0000837 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
Chris Lattnerac18be92006-11-20 06:49:47 +0000838 D.SetIdentifier(&II, Loc);
839
Chris Lattner62d2e662007-01-28 00:21:37 +0000840 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000841 if (Scope *FnS = S->getFnParent())
842 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner62d2e662007-01-28 00:21:37 +0000843 while (S->getParent())
844 S = S->getParent();
Chris Lattnerac18be92006-11-20 06:49:47 +0000845
Steve Naroff2f742082007-09-16 16:16:00 +0000846 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattnerac18be92006-11-20 06:49:47 +0000847}
848
Chris Lattner302b4be2006-11-19 02:31:38 +0000849
Chris Lattner776fac82007-06-09 00:53:06 +0000850TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
Steve Naroffa23cc792007-09-13 23:52:58 +0000851 ScopedDecl *LastDeclarator) {
Chris Lattner776fac82007-06-09 00:53:06 +0000852 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Chris Lattner302b4be2006-11-19 02:31:38 +0000853
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000854 QualType T = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +0000855 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner0d8b1a12006-11-20 04:34:45 +0000856
Chris Lattner18b19622007-01-22 07:39:13 +0000857 // Scope manipulation handled by caller.
Steve Narofff93b6722007-08-28 20:14:24 +0000858 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
859 T, LastDeclarator);
860 if (D.getInvalidType())
861 NewTD->setInvalidDecl();
862 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +0000863}
864
Fariborz Jahanianbfe13c52007-09-25 18:38:09 +0000865Sema::DeclTy *Sema::ObjcStartClassInterface(Scope* S,
866 SourceLocation AtInterfaceLoc,
Steve Naroff09bf8152007-09-06 21:24:23 +0000867 IdentifierInfo *ClassName, SourceLocation ClassLoc,
868 IdentifierInfo *SuperName, SourceLocation SuperLoc,
869 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
870 AttributeList *AttrList) {
871 assert(ClassName && "Missing class identifier");
Fariborz Jahanianbfe13c52007-09-25 18:38:09 +0000872
873 // Check for another declaration kind with the same name.
874 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
875 ClassLoc, S);
876 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
877 && !isa<ObjcProtocolDecl>(PrevDecl)) {
878 Diag(ClassLoc, diag::err_redefinition_different_kind,
879 ClassName->getName());
880 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
881 }
882
Fariborz Jahanian397d8de2007-09-20 20:26:44 +0000883 ObjcInterfaceDecl* IDecl = Context.getObjCInterfaceDecl(ClassName);
Fariborz Jahaniana8bbc632007-09-20 17:54:07 +0000884
Fariborz Jahanian397d8de2007-09-20 20:26:44 +0000885 if (IDecl) {
886 // Class already seen. Is it a forward declaration?
887 if (!IDecl->getIsForwardDecl())
888 Diag(AtInterfaceLoc, diag::err_duplicate_class_def, ClassName->getName());
Fariborz Jahanian7e5d5332007-09-22 00:01:35 +0000889 else {
Fariborz Jahanian397d8de2007-09-20 20:26:44 +0000890 IDecl->setIsForwardDecl(false);
Fariborz Jahanian7e5d5332007-09-22 00:01:35 +0000891 IDecl->AllocIntfRefProtocols(NumProtocols);
892 }
Fariborz Jahanian397d8de2007-09-20 20:26:44 +0000893 }
894 else {
Fariborz Jahanian7e5d5332007-09-22 00:01:35 +0000895 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, NumProtocols, ClassName);
Fariborz Jahaniana8bbc632007-09-20 17:54:07 +0000896
Fariborz Jahanian397d8de2007-09-20 20:26:44 +0000897 // Chain & install the interface decl into the identifier.
898 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
899 ClassName->setFETokenInfo(IDecl);
900 }
Fariborz Jahaniana8bbc632007-09-20 17:54:07 +0000901
902 if (SuperName) {
Fariborz Jahanianbfe13c52007-09-25 18:38:09 +0000903 ObjcInterfaceDecl* SuperClassEntry = 0;
904 // Check if a different kind of symbol declared in this scope.
905 PrevDecl = LookupScopedDecl(SuperName, Decl::IDNS_Ordinary,
906 SuperLoc, S);
907 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
908 && !isa<ObjcProtocolDecl>(PrevDecl)) {
909 Diag(SuperLoc, diag::err_redefinition_different_kind,
910 SuperName->getName());
911 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Fariborz Jahaniana8bbc632007-09-20 17:54:07 +0000912 }
Fariborz Jahanianbfe13c52007-09-25 18:38:09 +0000913 else {
914 // Check that super class is previously defined
915 SuperClassEntry = Context.getObjCInterfaceDecl(SuperName);
916
917 if (!SuperClassEntry || SuperClassEntry->getIsForwardDecl()) {
918 Diag(AtInterfaceLoc, diag::err_undef_superclass, SuperName->getName(),
919 ClassName->getName());
920 }
921 }
922 IDecl->setSuperClass(SuperClassEntry);
Fariborz Jahaniana8bbc632007-09-20 17:54:07 +0000923 }
924
Fariborz Jahanian7e5d5332007-09-22 00:01:35 +0000925 /// Check then save referenced protocols
926 for (unsigned int i = 0; i != NumProtocols; i++) {
927 ObjcProtocolDecl* RefPDecl = Context.getObjCProtocolDecl(ProtocolNames[i]);
928 if (!RefPDecl || RefPDecl->getIsForwardProtoDecl())
929 Diag(ClassLoc, diag::err_undef_protocolref,
930 ProtocolNames[i]->getName(),
931 ClassName->getName());
932 IDecl->setIntfRefProtocols((int)i, RefPDecl);
933 }
934
935
Fariborz Jahaniana8bbc632007-09-20 17:54:07 +0000936 Context.setObjCInterfaceDecl(ClassName, IDecl);
937
Steve Naroff09bf8152007-09-06 21:24:23 +0000938 return IDecl;
939}
940
Fariborz Jahanianbfe13c52007-09-25 18:38:09 +0000941Sema::DeclTy *Sema::ObjcStartProtoInterface(Scope* S,
942 SourceLocation AtProtoInterfaceLoc,
Fariborz Jahanian39d641f2007-09-17 21:07:36 +0000943 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
944 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
945 assert(ProtocolName && "Missing protocol identifier");
Fariborz Jahanian876e27d2007-09-21 15:40:54 +0000946 ObjcProtocolDecl *PDecl = Context.getObjCProtocolDecl(ProtocolName);
947 if (PDecl) {
948 // Protocol already seen. Better be a forward protocol declaration
949 if (!PDecl->getIsForwardProtoDecl())
950 Diag(ProtocolLoc, diag::err_duplicate_protocol_def,
951 ProtocolName->getName());
952 else {
953 PDecl->setIsForwardProtoDecl(false);
954 PDecl->AllocReferencedProtocols(NumProtoRefs);
955 }
956 }
957 else {
958 PDecl = new ObjcProtocolDecl(AtProtoInterfaceLoc, NumProtoRefs,
959 ProtocolName);
960 PDecl->setIsForwardProtoDecl(false);
961 // Chain & install the protocol decl into the identifier.
962 PDecl->setNext(ProtocolName->getFETokenInfo<ScopedDecl>());
963 ProtocolName->setFETokenInfo(PDecl);
964 Context.setObjCProtocolDecl(ProtocolName, PDecl);
965 }
966
967 /// Check then save referenced protocols
968 for (unsigned int i = 0; i != NumProtoRefs; i++) {
969 ObjcProtocolDecl* RefPDecl = Context.getObjCProtocolDecl(ProtoRefNames[i]);
970 if (!RefPDecl || RefPDecl->getIsForwardProtoDecl())
971 Diag(ProtocolLoc, diag::err_undef_protocolref,
972 ProtoRefNames[i]->getName(),
973 ProtocolName->getName());
974 PDecl->setReferencedProtocols((int)i, RefPDecl);
975 }
Fariborz Jahanian39d641f2007-09-17 21:07:36 +0000976
Fariborz Jahanian39d641f2007-09-17 21:07:36 +0000977 return PDecl;
978}
979
Fariborz Jahanian876e27d2007-09-21 15:40:54 +0000980/// ObjcForwardProtocolDeclaration -
981/// Scope will always be top level file scope.
982Action::DeclTy *
983Sema::ObjcForwardProtocolDeclaration(Scope *S, SourceLocation AtProtocolLoc,
984 IdentifierInfo **IdentList, unsigned NumElts) {
985 ObjcForwardProtocolDecl *FDecl = new ObjcForwardProtocolDecl(AtProtocolLoc,
986 NumElts);
987
988 for (unsigned i = 0; i != NumElts; ++i) {
989 ObjcProtocolDecl *PDecl;
990 PDecl = Context.getObjCProtocolDecl(IdentList[i]);
991 if (!PDecl) {// Already seen?
992 PDecl = new ObjcProtocolDecl(SourceLocation(), 0, IdentList[i], true);
993 // Chain & install the protocol decl into the identifier.
994 PDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
995 IdentList[i]->setFETokenInfo(PDecl);
996 Context.setObjCProtocolDecl(IdentList[i], PDecl);
997 }
998 // Remember that this needs to be removed when the scope is popped.
999 S->AddDecl(IdentList[i]);
1000
1001 FDecl->setForwardProtocolDecl((int)i, PDecl);
1002 }
1003 return FDecl;
1004}
1005
Fariborz Jahanian867a7eb2007-09-18 20:26:58 +00001006Sema::DeclTy *Sema::ObjcStartCatInterface(SourceLocation AtInterfaceLoc,
1007 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1008 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1009 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
1010 ObjcCategoryDecl *CDecl;
Fariborz Jahanian7e5d5332007-09-22 00:01:35 +00001011 ObjcInterfaceDecl* IDecl = Context.getObjCInterfaceDecl(ClassName);
1012 CDecl = new ObjcCategoryDecl(AtInterfaceLoc, NumProtoRefs, ClassName);
1013 if (IDecl) {
1014 assert (ClassName->getFETokenInfo<ScopedDecl>() && "Missing @interface decl");
1015 Decl *D = static_cast<Decl *>(ClassName->getFETokenInfo<ScopedDecl>());
1016 assert(isa<ObjcInterfaceDecl>(D) && "Missing @interface decl");
Fariborz Jahanian867a7eb2007-09-18 20:26:58 +00001017
Fariborz Jahanian7e5d5332007-09-22 00:01:35 +00001018 // Chain & install the category decl into the identifier.
1019 // Note that head of the chain is the @interface class type and follow up
1020 // nodes in the chain are the protocol decl nodes.
1021 cast<ObjcInterfaceDecl>(D)->setNext(CDecl);
1022 }
1023
1024 CDecl->setClassInterface(IDecl);
1025 /// Check that class of this category is already completely declared.
1026 if (!IDecl || IDecl->getIsForwardDecl())
1027 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
1028 else {
1029 /// Check for duplicate interface declaration for this category
1030 ObjcCategoryDecl *CDeclChain;
1031 for (CDeclChain = IDecl->getListCategories(); CDeclChain;
1032 CDeclChain = CDeclChain->getNextClassCategory()) {
1033 if (CDeclChain->getCatName() == CategoryName) {
1034 Diag(CategoryLoc, diag::err_dup_category_def, ClassName->getName(),
1035 CategoryName->getName());
1036 break;
1037 }
1038 }
1039 if (!CDeclChain) {
1040 CDecl->setCatName(CategoryName);
1041 CDecl->insertNextClassCategory();
1042 }
1043 }
1044
1045 /// Check then save referenced protocols
1046 for (unsigned int i = 0; i != NumProtoRefs; i++) {
1047 ObjcProtocolDecl* RefPDecl = Context.getObjCProtocolDecl(ProtoRefNames[i]);
1048 if (!RefPDecl || RefPDecl->getIsForwardProtoDecl())
1049 Diag(CategoryLoc, diag::err_undef_protocolref,
1050 ProtoRefNames[i]->getName(),
1051 CategoryName->getName());
1052 CDecl->setCatReferencedProtocols((int)i, RefPDecl);
1053 }
1054
Fariborz Jahanian867a7eb2007-09-18 20:26:58 +00001055 return CDecl;
1056}
Fariborz Jahanian397d8de2007-09-20 20:26:44 +00001057
Fariborz Jahanianbfe13c52007-09-25 18:38:09 +00001058Sema::DeclTy *Sema::ObjcStartClassImplementation(Scope *S,
1059 SourceLocation AtClassImplLoc,
1060 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1061 IdentifierInfo *SuperClassname,
1062 SourceLocation SuperClassLoc) {
1063 ObjcInterfaceDecl* IDecl = 0;
1064 // Check for another declaration kind with the same name.
1065 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
1066 ClassLoc, S);
1067 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
1068 Diag(ClassLoc, diag::err_redefinition_different_kind,
1069 ClassName->getName());
1070 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1071 }
1072 else {
1073 // Is there an interface declaration of this class; if not, warn!
1074 IDecl = Context.getObjCInterfaceDecl(ClassName);
1075 if (!IDecl)
1076 Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
1077 }
1078
1079 // Check that super class name is valid class name
1080 ObjcInterfaceDecl* SDecl = 0;
1081 if (SuperClassname) {
1082 // Check if a different kind of symbol declared in this scope.
1083 PrevDecl = LookupScopedDecl(SuperClassname, Decl::IDNS_Ordinary,
1084 SuperClassLoc, S);
1085 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
1086 && !isa<ObjcProtocolDecl>(PrevDecl)) {
1087 Diag(SuperClassLoc, diag::err_redefinition_different_kind,
1088 SuperClassname->getName());
1089 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1090 }
1091 else {
1092 SDecl = Context.getObjCInterfaceDecl(SuperClassname);
1093 if (!SDecl)
1094 Diag(SuperClassLoc, diag::err_undef_superclass,
1095 SuperClassname->getName(), ClassName->getName());
1096 else if (IDecl && IDecl->getSuperClass() != SDecl) {
1097 // This implementation and its interface do not have the same
1098 // super class.
1099 Diag(SuperClassLoc, diag::err_conflicting_super_class,
1100 SuperClassname->getName());
1101 Diag(SDecl->getLocation(), diag::err_previous_definition);
1102 }
1103 }
1104 }
1105
1106 ObjcImplementationDecl* IMPDecl =
1107 new ObjcImplementationDecl(AtClassImplLoc, ClassName, SDecl);
Fariborz Jahaniane2017c12007-09-25 21:00:20 +00001108 if (!IDecl) {
1109 // Legacy case of @implementation with no corresponding @interface.
1110 // Build, chain & install the interface decl into the identifier.
1111 IDecl = new ObjcInterfaceDecl(AtClassImplLoc, 0, ClassName);
1112 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
1113 ClassName->setFETokenInfo(IDecl);
1114
1115 }
Fariborz Jahanianbfe13c52007-09-25 18:38:09 +00001116
1117 // Check that there is no duplicate implementation of this class.
1118 bool err = false;
1119 for (unsigned i = 0; i != Context.sizeObjcImplementationClass(); i++) {
1120 if (Context.getObjcImplementationClass(i)->getIdentifier() == ClassName) {
1121 Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
1122 err = true;
1123 break;
1124 }
1125 }
1126 if (!err)
1127 Context.setObjcImplementationClass(IMPDecl);
1128
1129 return IMPDecl;
1130}
1131
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00001132void Sema::ActOnImpleIvarVsClassIvars(DeclTy *ClassDecl,
1133 DeclTy **Fields, unsigned numIvars) {
1134 ObjcInterfaceDecl* IDecl =
1135 cast<ObjcInterfaceDecl>(static_cast<Decl*>(ClassDecl));
1136 assert(IDecl && "missing named interface class decl");
1137 ObjcIvarDecl** ivars = reinterpret_cast<ObjcIvarDecl**>(Fields);
1138 assert(ivars && "missing @implementation ivars");
1139
1140 // Check interface's Ivar list against those in the implementation.
1141 // names and types must match.
1142 //
1143 ObjcIvarDecl** IntfIvars = IDecl->getIntfDeclIvars();
1144 int IntfNumIvars = IDecl->getIntfDeclNumIvars();
1145 unsigned j = 0;
1146 bool err = false;
1147 while (numIvars > 0 && IntfNumIvars > 0) {
1148 ObjcIvarDecl* ImplIvar = ivars[j];
1149 ObjcIvarDecl* ClsIvar = IntfIvars[j++];
1150 assert (ImplIvar && "missing implementation ivar");
1151 assert (ClsIvar && "missing class ivar");
1152 if (ImplIvar->getCanonicalType() != ClsIvar->getCanonicalType()) {
1153 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
1154 ImplIvar->getIdentifier()->getName());
1155 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1156 ClsIvar->getIdentifier()->getName());
1157 }
1158 // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
1159 // as error.
1160 else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1161 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
1162 ImplIvar->getIdentifier()->getName());
1163 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1164 ClsIvar->getIdentifier()->getName());
1165 err = true;
1166 break;
1167 }
1168 --numIvars;
1169 --IntfNumIvars;
1170 }
1171 if (!err && (numIvars > 0 || IntfNumIvars > 0))
1172 Diag(numIvars > 0 ? ivars[j]->getLocation() : IntfIvars[j]->getLocation(),
1173 diag::err_inconsistant_ivar);
1174
1175}
1176
Steve Naroff09bf8152007-09-06 21:24:23 +00001177/// ObjcClassDeclaration -
1178/// Scope will always be top level file scope.
1179Action::DeclTy *
1180Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
1181 IdentifierInfo **IdentList, unsigned NumElts) {
1182 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
1183
1184 for (unsigned i = 0; i != NumElts; ++i) {
1185 ObjcInterfaceDecl *IDecl;
Fariborz Jahanian397d8de2007-09-20 20:26:44 +00001186 IDecl = Context.getObjCInterfaceDecl(IdentList[i]);
1187 if (!IDecl) {// Already seen?
Fariborz Jahanian7e5d5332007-09-22 00:01:35 +00001188 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, IdentList[i], true);
Fariborz Jahanian397d8de2007-09-20 20:26:44 +00001189 // Chain & install the interface decl into the identifier.
1190 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1191 IdentList[i]->setFETokenInfo(IDecl);
1192 Context.setObjCInterfaceDecl(IdentList[i], IDecl);
1193 }
Steve Naroff09bf8152007-09-06 21:24:23 +00001194 // Remember that this needs to be removed when the scope is popped.
1195 S->AddDecl(IdentList[i]);
1196
1197 CDecl->setInterfaceDecl((int)i, IDecl);
1198 }
1199 return CDecl;
1200}
1201
Chris Lattner18b19622007-01-22 07:39:13 +00001202
Steve Naroff30d242c2007-09-15 18:49:24 +00001203/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00001204/// former case, Name will be non-null. In the later case, Name will be null.
1205/// TagType indicates what kind of tag this is. TK indicates whether this is a
1206/// reference/declaration/definition of a tag.
Steve Naroff30d242c2007-09-15 18:49:24 +00001207Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001208 SourceLocation KWLoc, IdentifierInfo *Name,
Steve Naroffb3096442007-06-09 03:47:53 +00001209 SourceLocation NameLoc, AttributeList *Attr) {
Chris Lattner8799cf22007-01-23 01:57:16 +00001210 // If this is a use of an existing tag, it must have a name.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001211 assert((Name != 0 || TK == TK_Definition) &&
1212 "Nameless record must be a definition!");
Chris Lattner8799cf22007-01-23 01:57:16 +00001213
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001214 Decl::Kind Kind;
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001215 switch (TagType) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001216 default: assert(0 && "Unknown tag type!");
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001217 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1218 case DeclSpec::TST_union: Kind = Decl::Union; break;
1219//case DeclSpec::TST_class: Kind = Decl::Class; break;
1220 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001221 }
Chris Lattner7e783a12007-01-23 02:05:42 +00001222
Chris Lattner18b19622007-01-22 07:39:13 +00001223 // If this is a named struct, check to see if there was a previous forward
1224 // declaration or definition.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001225 if (TagDecl *PrevDecl =
Chris Lattner9561a0b2007-01-28 08:20:04 +00001226 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1227 NameLoc, S))) {
Chris Lattner8799cf22007-01-23 01:57:16 +00001228
1229 // If this is a use of a previous tag, or if the tag is already declared in
1230 // the same scope (so that the definition/declaration completes or
1231 // rementions the tag), reuse the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001232 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
Chris Lattner7e783a12007-01-23 02:05:42 +00001233 // Make sure that this wasn't declared as an enum and now used as a struct
1234 // or something similar.
1235 if (PrevDecl->getKind() != Kind) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001236 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
Chris Lattner7e783a12007-01-23 02:05:42 +00001237 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1238 }
Chris Lattner7b9ace62007-01-23 20:11:08 +00001239
1240 // If this is a use or a forward declaration, we're good.
1241 if (TK != TK_Definition)
1242 return PrevDecl;
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001243
Chris Lattner7b9ace62007-01-23 20:11:08 +00001244 // Diagnose attempts to redefine a tag.
1245 if (PrevDecl->isDefinition()) {
1246 Diag(NameLoc, diag::err_redefinition, Name->getName());
1247 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1248 // If this is a redefinition, recover by making this struct be
1249 // anonymous, which will make any later references get the previous
1250 // definition.
1251 Name = 0;
1252 } else {
1253 // Okay, this is definition of a previously declared or referenced tag.
1254 // Move the location of the decl to be the definition site.
1255 PrevDecl->setLocation(NameLoc);
Chris Lattner7b9ace62007-01-23 20:11:08 +00001256 return PrevDecl;
1257 }
Chris Lattner8799cf22007-01-23 01:57:16 +00001258 }
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001259 // If we get here, this is a definition of a new struct type in a nested
1260 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1261 // type.
Chris Lattner18b19622007-01-22 07:39:13 +00001262 }
1263
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001264 // If there is an identifier, use the location of the identifier as the
1265 // location of the decl, otherwise use the location of the struct/union
1266 // keyword.
1267 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1268
Chris Lattner18b19622007-01-22 07:39:13 +00001269 // Otherwise, if this is the first time we've seen this tag, create the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001270 TagDecl *New;
Chris Lattner720a0542007-01-25 00:44:24 +00001271 switch (Kind) {
1272 default: assert(0 && "Unknown tag kind!");
Chris Lattner5f521502007-01-25 06:27:24 +00001273 case Decl::Enum:
Chris Lattner776fac82007-06-09 00:53:06 +00001274 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1275 // enum X { A, B, C } D; D should chain to X.
1276 New = new EnumDecl(Loc, Name, 0);
Chris Lattner5f521502007-01-25 06:27:24 +00001277 // If this is an undefined enum, warn.
Chris Lattnerc1915e22007-01-25 07:29:02 +00001278 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Chris Lattner5f521502007-01-25 06:27:24 +00001279 break;
Chris Lattner720a0542007-01-25 00:44:24 +00001280 case Decl::Union:
1281 case Decl::Struct:
1282 case Decl::Class:
Chris Lattner776fac82007-06-09 00:53:06 +00001283 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1284 // struct X { int A; } D; D should chain to X.
1285 New = new RecordDecl(Kind, Loc, Name, 0);
Chris Lattner720a0542007-01-25 00:44:24 +00001286 break;
1287 }
Chris Lattner18b19622007-01-22 07:39:13 +00001288
1289 // If this has an identifier, add it to the scope stack.
1290 if (Name) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001291 // The scope passed in may not be a decl scope. Zip up the scope tree until
1292 // we find one that is.
1293 while ((S->getFlags() & Scope::DeclScope) == 0)
1294 S = S->getParent();
1295
1296 // Add it to the decl chain.
Steve Naroff9324db12007-09-13 18:10:37 +00001297 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner18b19622007-01-22 07:39:13 +00001298 Name->setFETokenInfo(New);
1299 S->AddDecl(New);
1300 }
1301
1302 return New;
1303}
Chris Lattner1300fb92007-01-23 23:42:53 +00001304
Steve Naroff30d242c2007-09-15 18:49:24 +00001305/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00001306/// to create a FieldDecl object for it.
Steve Naroff30d242c2007-09-15 18:49:24 +00001307Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Chris Lattner1300fb92007-01-23 23:42:53 +00001308 SourceLocation DeclStart,
1309 Declarator &D, ExprTy *BitfieldWidth) {
1310 IdentifierInfo *II = D.getIdentifier();
1311 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner1300fb92007-01-23 23:42:53 +00001312 SourceLocation Loc = DeclStart;
1313 if (II) Loc = D.getIdentifierLoc();
1314
Chris Lattner62d2e662007-01-28 00:21:37 +00001315 // FIXME: Unnamed fields can be handled in various different ways, for
1316 // example, unnamed unions inject all members into the struct namespace!
1317
1318
Chris Lattner1300fb92007-01-23 23:42:53 +00001319 if (BitWidth) {
1320 // TODO: Validate.
Steve Narofff84d11f2007-05-23 21:48:04 +00001321 //printf("WARNING: BITFIELDS IGNORED!\n");
Chris Lattner1300fb92007-01-23 23:42:53 +00001322
1323 // 6.7.2.1p3
1324 // 6.7.2.1p4
1325
1326 } else {
1327 // Not a bitfield.
1328
1329 // validate II.
1330
1331 }
1332
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001333 QualType T = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +00001334 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1335 bool InvalidDecl = false;
Steve Naroff096dd942007-08-31 17:20:07 +00001336
Steve Naroff8eeeb132007-05-08 21:09:37 +00001337 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1338 // than a variably modified type.
Steve Naroff096dd942007-08-31 17:20:07 +00001339 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1340 Diag(Loc, diag::err_typecheck_illegal_vla,
1341 VAT->getSizeExpr()->getSourceRange());
1342 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +00001343 }
Chris Lattner776fac82007-06-09 00:53:06 +00001344 // FIXME: Chain fielddecls together.
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001345 FieldDecl *NewFD;
1346
1347 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Naroff1d4b5eae2007-09-14 02:20:46 +00001348 NewFD = new FieldDecl(Loc, II, T);
Fariborz Jahanianbfe13c52007-09-25 18:38:09 +00001349 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl))
1350 || isa<ObjcImplementationDecl>(static_cast<Decl *>(TagDecl)))
Steve Naroff1d4b5eae2007-09-14 02:20:46 +00001351 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001352 else
Steve Naroff30d242c2007-09-15 18:49:24 +00001353 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001354
Steve Narofff93b6722007-08-28 20:14:24 +00001355 if (D.getInvalidType() || InvalidDecl)
1356 NewFD->setInvalidDecl();
1357 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00001358}
1359
Steve Naroff2e688fd2007-09-14 23:09:53 +00001360static void ObjcSetIvarVisibility(ObjcIvarDecl *OIvar,
1361 tok::ObjCKeywordKind ivarVisibility) {
1362 assert(OIvar && "missing instance variable");
1363 switch (ivarVisibility) {
1364 case tok::objc_private:
1365 OIvar->setAccessControl(ObjcIvarDecl::Private);
1366 break;
1367 case tok::objc_public:
1368 OIvar->setAccessControl(ObjcIvarDecl::Public);
1369 break;
1370 case tok::objc_protected:
1371 OIvar->setAccessControl(ObjcIvarDecl::Protected);
1372 break;
1373 case tok::objc_package:
1374 OIvar->setAccessControl(ObjcIvarDecl::Package);
1375 break;
1376 default:
1377 OIvar->setAccessControl(ObjcIvarDecl::None);
1378 break;
1379 }
1380}
1381
Steve Naroff30d242c2007-09-15 18:49:24 +00001382void Sema::ActOnFields(SourceLocation RecLoc, DeclTy *RecDecl,
1383 DeclTy **Fields, unsigned NumFields,
1384 tok::ObjCKeywordKind *visibility) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00001385 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1386 assert(EnclosingDecl && "missing record or interface decl");
1387 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1388
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001389 if (Record && Record->isDefinition()) {
Chris Lattner1300fb92007-01-23 23:42:53 +00001390 // Diagnose code like:
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001391 // struct S { struct S {} X; };
Chris Lattner1300fb92007-01-23 23:42:53 +00001392 // We discover this when we complete the outer S. Reject and ignore the
1393 // outer S.
1394 Diag(Record->getLocation(), diag::err_nested_redefinition,
1395 Record->getKindName());
1396 Diag(RecLoc, diag::err_previous_definition);
Steve Naroffdb47ee22007-09-14 22:20:54 +00001397 Record->setInvalidDecl();
Chris Lattner1300fb92007-01-23 23:42:53 +00001398 return;
1399 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001400 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00001401 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +00001402 llvm::SmallVector<FieldDecl*, 32> RecFields;
1403 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroffdb47ee22007-09-14 22:20:54 +00001404
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001405 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001406
Steve Naroffdb47ee22007-09-14 22:20:54 +00001407 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1408 assert(FD && "missing field decl");
1409
1410 // Remember all fields.
1411 RecFields.push_back(FD);
Chris Lattner720a0542007-01-25 00:44:24 +00001412
1413 // Get the type for the field.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001414 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner720a0542007-01-25 00:44:24 +00001415
Steve Naroff2e688fd2007-09-14 23:09:53 +00001416 // If we have visibility info, make sure the AST is set accordingly.
1417 if (visibility)
1418 ObjcSetIvarVisibility(dyn_cast<ObjcIvarDecl>(FD), visibility[i]);
1419
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001420 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001421 if (FDTy->isFunctionType()) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00001422 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001423 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001424 FD->setInvalidDecl();
1425 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001426 continue;
1427 }
Chris Lattner82625602007-01-24 02:26:21 +00001428 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
Chris Lattner720a0542007-01-25 00:44:24 +00001429 if (FDTy->isIncompleteType()) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001430 if (!Record) { // Incomplete ivar type is always an error.
1431 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001432 FD->setInvalidDecl();
1433 EnclosingDecl->setInvalidDecl();
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001434 continue;
1435 }
Chris Lattner82625602007-01-24 02:26:21 +00001436 if (i != NumFields-1 || // ... that the last member ...
1437 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner0fd893e2007-07-31 21:33:24 +00001438 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner82625602007-01-24 02:26:21 +00001439 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001440 FD->setInvalidDecl();
1441 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00001442 continue;
1443 }
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001444 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner82625602007-01-24 02:26:21 +00001445 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1446 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001447 FD->setInvalidDecl();
1448 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00001449 continue;
1450 }
Chris Lattner720a0542007-01-25 00:44:24 +00001451 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001452 if (Record)
1453 Record->setHasFlexibleArrayMember(true);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001454 }
Chris Lattner720a0542007-01-25 00:44:24 +00001455 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1456 /// field of another structure or the element of an array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001457 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner720a0542007-01-25 00:44:24 +00001458 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1459 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001460 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner41943152007-01-25 04:52:46 +00001461 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00001462 } else {
1463 // If this is a struct/class and this is not the last element, reject
1464 // it. Note that GCC supports variable sized arrays in the middle of
1465 // structures.
1466 if (i != NumFields-1) {
1467 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1468 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001469 FD->setInvalidDecl();
1470 EnclosingDecl->setInvalidDecl();
Chris Lattner720a0542007-01-25 00:44:24 +00001471 continue;
1472 }
Chris Lattner720a0542007-01-25 00:44:24 +00001473 // We support flexible arrays at the end of structs in other structs
1474 // as an extension.
1475 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1476 FD->getName());
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001477 if (Record)
1478 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00001479 }
1480 }
1481 }
Chris Lattner82625602007-01-24 02:26:21 +00001482 // Keep track of the number of named members.
Chris Lattnere5a66562007-01-25 22:48:42 +00001483 if (IdentifierInfo *II = FD->getIdentifier()) {
1484 // Detect duplicate member names.
Chris Lattnerbaf33662007-01-27 02:14:08 +00001485 if (!FieldIDs.insert(II)) {
Chris Lattnere5a66562007-01-25 22:48:42 +00001486 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1487 // Find the previous decl.
1488 SourceLocation PrevLoc;
1489 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1490 assert(i != e && "Didn't find previous def!");
1491 if (RecFields[i]->getIdentifier() == II) {
1492 PrevLoc = RecFields[i]->getLocation();
1493 break;
1494 }
1495 }
1496 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroffdb47ee22007-09-14 22:20:54 +00001497 FD->setInvalidDecl();
1498 EnclosingDecl->setInvalidDecl();
Chris Lattnere5a66562007-01-25 22:48:42 +00001499 continue;
1500 }
Chris Lattner82625602007-01-24 02:26:21 +00001501 ++NumNamedMembers;
Chris Lattnere5a66562007-01-25 22:48:42 +00001502 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001503 }
Chris Lattner82625602007-01-24 02:26:21 +00001504
Chris Lattner82625602007-01-24 02:26:21 +00001505 // Okay, we successfully defined 'Record'.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001506 if (Record)
1507 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00001508 else {
1509 ObjcIvarDecl **ClsFields =
1510 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00001511 if (isa<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1512 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1513 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1514 else if (isa<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1515 ObjcImplementationDecl* IMPDecl =
1516 cast<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl));
1517 assert(IMPDecl && "ActOnFields - missing ObjcImplementationDecl");
1518 IMPDecl->ObjcAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
1519 ObjcInterfaceDecl* IDecl =
1520 Context.getObjCInterfaceDecl(IMPDecl->getIdentifier());
1521 if (IDecl)
1522 ActOnImpleIvarVsClassIvars(static_cast<DeclTy*>(IDecl),
1523 reinterpret_cast<DeclTy**>(&RecFields[0]), RecFields.size());
1524 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00001525 }
Chris Lattner1300fb92007-01-23 23:42:53 +00001526}
1527
Fariborz Jahanian39d641f2007-09-17 21:07:36 +00001528void Sema::ObjcAddMethodsToClass(DeclTy *ClassDecl,
1529 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahaniancfb31fa2007-09-12 18:23:47 +00001530 // FIXME: Fix this when we can handle methods declared in protocols.
1531 // See Parser::ParseObjCAtProtocolDeclaration
1532 if (!ClassDecl)
1533 return;
Fariborz Jahanian33d03742007-09-10 20:33:04 +00001534 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1535 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1536
1537 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian39d641f2007-09-17 21:07:36 +00001538 ObjcMethodDecl *Method =
Fariborz Jahanian33d03742007-09-10 20:33:04 +00001539 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1540 if (!Method) continue; // Already issued a diagnostic.
1541 if (Method->isInstance())
1542 insMethods.push_back(Method);
1543 else
1544 clsMethods.push_back(Method);
1545 }
Fariborz Jahanian39d641f2007-09-17 21:07:36 +00001546 if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(ClassDecl))) {
1547 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1548 static_cast<Decl*>(ClassDecl));
1549 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1550 &clsMethods[0], clsMethods.size());
1551 }
1552 else if (isa<ObjcProtocolDecl>(static_cast<Decl *>(ClassDecl))) {
1553 ObjcProtocolDecl *Protocol = cast<ObjcProtocolDecl>(
1554 static_cast<Decl*>(ClassDecl));
1555 Protocol->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1556 &clsMethods[0], clsMethods.size());
1557 }
Fariborz Jahanian867a7eb2007-09-18 20:26:58 +00001558 else if (isa<ObjcCategoryDecl>(static_cast<Decl *>(ClassDecl))) {
1559 ObjcCategoryDecl *Category = cast<ObjcCategoryDecl>(
1560 static_cast<Decl*>(ClassDecl));
1561 Category->ObjcAddCatMethods(&insMethods[0], insMethods.size(),
1562 &clsMethods[0], clsMethods.size());
1563 }
Fariborz Jahanian39d641f2007-09-17 21:07:36 +00001564 else
1565 assert(0 && "Sema::ObjcAddMethodsToClass(): Unknown DeclTy");
Fariborz Jahanian33d03742007-09-10 20:33:04 +00001566 return;
1567}
1568
Fariborz Jahanian0c74e9d2007-09-18 00:25:23 +00001569Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
Steve Narofff73590d2007-09-27 14:38:14 +00001570 tok::TokenKind MethodType, TypeTy *ReturnType, SelectorInfo *Sel,
1571 // optional arguments. The number of types/arguments is obtained
1572 // from the Sel.getNumArgs().
1573 TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1574 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind) {
Fariborz Jahaniancfb31fa2007-09-12 18:23:47 +00001575 llvm::SmallVector<ParmVarDecl*, 16> Params;
1576
Steve Narofff73590d2007-09-27 14:38:14 +00001577 for (unsigned i = 0; i < Sel->getNumArgs(); i++) {
Fariborz Jahaniancfb31fa2007-09-12 18:23:47 +00001578 // FIXME: arg->AttrList must be stored too!
Steve Narofff73590d2007-09-27 14:38:14 +00001579 ParmVarDecl* Param = new ParmVarDecl(SourceLocation(/*FIXME*/), ArgNames[i],
1580 QualType::getFromOpaquePtr(ArgTypes[i]),
Fariborz Jahaniancfb31fa2007-09-12 18:23:47 +00001581 VarDecl::None, 0);
Fariborz Jahaniancfb31fa2007-09-12 18:23:47 +00001582 Params.push_back(Param);
1583 }
1584 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Steve Narofff73590d2007-09-27 14:38:14 +00001585 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc, Sel,
1586 resultDeclType, 0, -1, AttrList,
1587 MethodType == tok::minus);
1588 ObjcMethod->setMethodParams(&Params[0], Sel->getNumArgs());
Fariborz Jahanian0c74e9d2007-09-18 00:25:23 +00001589 if (MethodDeclKind == tok::objc_optional)
Steve Naroffd54978b2007-09-18 23:55:05 +00001590 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Optional);
Fariborz Jahanian39d641f2007-09-17 21:07:36 +00001591 else
Steve Naroffd54978b2007-09-18 23:55:05 +00001592 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Required);
Fariborz Jahanian39d641f2007-09-17 21:07:36 +00001593 return ObjcMethod;
Fariborz Jahaniancfb31fa2007-09-12 18:23:47 +00001594}
1595
Steve Naroff30d242c2007-09-15 18:49:24 +00001596Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4ef40012007-06-11 01:28:17 +00001597 DeclTy *lastEnumConst,
Chris Lattnerc1915e22007-01-25 07:29:02 +00001598 SourceLocation IdLoc, IdentifierInfo *Id,
Chris Lattner4ef40012007-06-11 01:28:17 +00001599 SourceLocation EqualLoc, ExprTy *val) {
1600 theEnumDecl = theEnumDecl; // silence unused warning.
1601 EnumConstantDecl *LastEnumConst =
1602 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1603 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00001604
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001605 // The scope passed in may not be a decl scope. Zip up the scope tree until
1606 // we find one that is.
1607 while ((S->getFlags() & Scope::DeclScope) == 0)
1608 S = S->getParent();
1609
Chris Lattner8116d1b2007-01-25 22:38:29 +00001610 // Verify that there isn't already something declared with this name in this
1611 // scope.
Steve Naroff9def2b12007-09-13 21:41:19 +00001612 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1613 IdLoc, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00001614 if (S->isDeclScope(PrevDecl)) {
1615 if (isa<EnumConstantDecl>(PrevDecl))
1616 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1617 else
1618 Diag(IdLoc, diag::err_redefinition, Id->getName());
1619 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner4ef40012007-06-11 01:28:17 +00001620 // FIXME: Don't leak memory: delete Val;
Chris Lattner8116d1b2007-01-25 22:38:29 +00001621 return 0;
1622 }
1623 }
Chris Lattner4ef40012007-06-11 01:28:17 +00001624
Chris Lattner23b7eb62007-06-15 23:05:46 +00001625 llvm::APSInt EnumVal(32);
Chris Lattner4ef40012007-06-11 01:28:17 +00001626 QualType EltTy;
1627 if (Val) {
Chris Lattner0515e4b2007-08-27 21:16:18 +00001628 // Make sure to promote the operand type to int.
1629 UsualUnaryConversions(Val);
1630
Chris Lattner4ef40012007-06-11 01:28:17 +00001631 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1632 SourceLocation ExpLoc;
Chris Lattner0e9d6222007-07-15 23:26:56 +00001633 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Chris Lattner4ef40012007-06-11 01:28:17 +00001634 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1635 Id->getName());
1636 // FIXME: Don't leak memory: delete Val;
Chris Lattnerf283a372007-08-27 17:37:24 +00001637 Val = 0; // Just forget about it.
Chris Lattnerc92bc4c2007-08-29 16:03:41 +00001638 } else {
1639 EltTy = Val->getType();
Chris Lattner4ef40012007-06-11 01:28:17 +00001640 }
Chris Lattnerf283a372007-08-27 17:37:24 +00001641 }
1642
1643 if (!Val) {
1644 if (LastEnumConst) {
1645 // Assign the last value + 1.
1646 EnumVal = LastEnumConst->getInitVal();
1647 ++EnumVal;
Chris Lattner0515e4b2007-08-27 21:16:18 +00001648
1649 // Check for overflow on increment.
1650 if (EnumVal < LastEnumConst->getInitVal())
1651 Diag(IdLoc, diag::warn_enum_value_overflow);
1652
Chris Lattnerf283a372007-08-27 17:37:24 +00001653 EltTy = LastEnumConst->getType();
1654 } else {
1655 // First value, set to zero.
1656 EltTy = Context.IntTy;
Chris Lattner9cf21c52007-09-04 02:45:27 +00001657 EnumVal.zextOrTrunc(
1658 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerf283a372007-08-27 17:37:24 +00001659 }
Steve Naroff63969212007-05-07 21:22:42 +00001660 }
Chris Lattner4ef40012007-06-11 01:28:17 +00001661
Chris Lattner4ef40012007-06-11 01:28:17 +00001662 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1663 LastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +00001664
1665 // Register this decl in the current scope stack.
Steve Naroff9324db12007-09-13 18:10:37 +00001666 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner8116d1b2007-01-25 22:38:29 +00001667 Id->setFETokenInfo(New);
1668 S->AddDecl(New);
1669 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001670}
1671
Steve Naroff30d242c2007-09-15 18:49:24 +00001672void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattnerc1915e22007-01-25 07:29:02 +00001673 DeclTy **Elements, unsigned NumElements) {
1674 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1675 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1676
Chris Lattner67933c02007-08-28 05:10:31 +00001677 // TODO: If the result value doesn't fit in an int, it must be a long or long
1678 // long value. ISO C does not support this, but GCC does as an extension,
1679 // emit a warning.
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001680 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner67933c02007-08-28 05:10:31 +00001681
1682
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001683 // Verify that all the values are okay, compute the size of the values, and
1684 // reverse the list.
1685 unsigned NumNegativeBits = 0;
1686 unsigned NumPositiveBits = 0;
1687
1688 // Keep track of whether all elements have type int.
1689 bool AllElementsInt = true;
1690
Chris Lattner4ef40012007-06-11 01:28:17 +00001691 EnumConstantDecl *EltList = 0;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001692 for (unsigned i = 0; i != NumElements; ++i) {
1693 EnumConstantDecl *ECD =
1694 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1695 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnerbf478cb2007-08-28 05:27:00 +00001696
1697 // If the enum value doesn't fit in an int, emit an extension warning.
1698 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1699 "Should have promoted value to int");
1700 const llvm::APSInt &InitVal = ECD->getInitVal();
1701 if (InitVal.getBitWidth() > IntWidth) {
1702 llvm::APSInt V(InitVal);
1703 V.trunc(IntWidth);
1704 V.extend(InitVal.getBitWidth());
1705 if (V != InitVal)
1706 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1707 InitVal.toString());
1708 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001709
1710 // Keep track of the size of positive and negative values.
1711 if (InitVal.isUnsigned() || !InitVal.isNegative())
1712 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1713 else
1714 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00001715
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001716 // Keep track of whether every enum element has type int (very commmon).
1717 if (AllElementsInt)
1718 AllElementsInt = ECD->getType() == Context.IntTy;
1719
Chris Lattner4ef40012007-06-11 01:28:17 +00001720 ECD->setNextDeclarator(EltList);
1721 EltList = ECD;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001722 }
1723
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001724 // Figure out the type that should be used for this enum.
1725 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1726 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001727 unsigned BestWidth;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001728
1729 if (NumNegativeBits) {
1730 // If there is a negative value, figure out the smallest integer type (of
1731 // int/long/longlong) that fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001732 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001733 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001734 BestWidth = IntWidth;
1735 } else {
1736 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1737 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001738 BestType = Context.LongTy;
1739 else {
Chris Lattner3a370bf2007-08-29 17:31:48 +00001740 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1741 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001742 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1743 BestType = Context.LongLongTy;
1744 }
1745 }
1746 } else {
1747 // If there is no negative value, figure out which of uint, ulong, ulonglong
1748 // fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001749 if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001750 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001751 BestWidth = IntWidth;
1752 } else if (NumPositiveBits <=
1753 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001754 BestType = Context.UnsignedLongTy;
1755 else {
Chris Lattner3a370bf2007-08-29 17:31:48 +00001756 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1757 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001758 "How could an initializer get larger than ULL?");
1759 BestType = Context.UnsignedLongLongTy;
1760 }
1761 }
1762
Chris Lattner3a370bf2007-08-29 17:31:48 +00001763 // Loop over all of the enumerator constants, changing their types to match
1764 // the type of the enum if needed.
1765 for (unsigned i = 0; i != NumElements; ++i) {
1766 EnumConstantDecl *ECD =
1767 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1768 if (!ECD) continue; // Already issued a diagnostic.
1769
1770 // Standard C says the enumerators have int type, but we allow, as an
1771 // extension, the enumerators to be larger than int size. If each
1772 // enumerator value fits in an int, type it as an int, otherwise type it the
1773 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1774 // that X has type 'int', not 'unsigned'.
1775 if (ECD->getType() == Context.IntTy)
1776 continue; // Already int type.
1777
1778 // Determine whether the value fits into an int.
1779 llvm::APSInt InitVal = ECD->getInitVal();
1780 bool FitsInInt;
1781 if (InitVal.isUnsigned() || !InitVal.isNegative())
1782 FitsInInt = InitVal.getActiveBits() < IntWidth;
1783 else
1784 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1785
1786 // If it fits into an integer type, force it. Otherwise force it to match
1787 // the enum decl type.
1788 QualType NewTy;
1789 unsigned NewWidth;
1790 bool NewSign;
1791 if (FitsInInt) {
1792 NewTy = Context.IntTy;
1793 NewWidth = IntWidth;
1794 NewSign = true;
1795 } else if (ECD->getType() == BestType) {
1796 // Already the right type!
1797 continue;
1798 } else {
1799 NewTy = BestType;
1800 NewWidth = BestWidth;
1801 NewSign = BestType->isSignedIntegerType();
1802 }
1803
1804 // Adjust the APSInt value.
1805 InitVal.extOrTrunc(NewWidth);
1806 InitVal.setIsSigned(NewSign);
1807 ECD->setInitVal(InitVal);
1808
1809 // Adjust the Expr initializer and type.
1810 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1811 ECD->setType(NewTy);
1812 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001813
Chris Lattner1c1f9322007-08-28 18:24:31 +00001814 Enum->defineElements(EltList, BestType);
Chris Lattnerc1915e22007-01-25 07:29:02 +00001815}
Chris Lattner1300fb92007-01-23 23:42:53 +00001816
Steve Naroff26c8ea52007-03-21 21:08:52 +00001817void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1818 if (!current) return;
1819
1820 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1821 // remember this in the LastInGroupList list.
Chris Lattner776fac82007-06-09 00:53:06 +00001822 if (last)
Steve Naroff26c8ea52007-03-21 21:08:52 +00001823 LastInGroupList.push_back((Decl*)last);
Steve Naroff26c8ea52007-03-21 21:08:52 +00001824}
Steve Naroffa8fd9732007-06-11 00:35:03 +00001825
1826void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1827 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1828 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001829 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001830 if (!newType.isNull()) // install the new vector type into the decl
1831 vDecl->setType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001832 }
1833 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001834 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1835 rawAttr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001836 if (!newType.isNull()) // install the new vector type into the decl
1837 tDecl->setUnderlyingType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001838 }
1839 }
Steve Naroff91fcddb2007-07-18 18:00:27 +00001840 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001841 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1842 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1843 else
Steve Naroff91fcddb2007-07-18 18:00:27 +00001844 Diag(rawAttr->getAttributeLoc(),
1845 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001846 }
Steve Naroffa8fd9732007-06-11 00:35:03 +00001847 // FIXME: add other attributes...
1848}
1849
1850void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1851 AttributeList *declarator_postfix) {
1852 while (declspec_prefix) {
1853 HandleDeclAttribute(New, declspec_prefix);
1854 declspec_prefix = declspec_prefix->getNext();
1855 }
1856 while (declarator_postfix) {
1857 HandleDeclAttribute(New, declarator_postfix);
1858 declarator_postfix = declarator_postfix->getNext();
1859 }
1860}
1861
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001862void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1863 AttributeList *rawAttr) {
1864 QualType curType = tDecl->getUnderlyingType();
Steve Naroff91fcddb2007-07-18 18:00:27 +00001865 // check the attribute arugments.
1866 if (rawAttr->getNumArgs() != 1) {
1867 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1868 std::string("1"));
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001869 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001870 }
1871 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1872 llvm::APSInt vecSize(32);
1873 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1874 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1875 sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001876 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001877 }
1878 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1879 // in conjunction with complex types (pointers, arrays, functions, etc.).
1880 Type *canonType = curType.getCanonicalType().getTypePtr();
1881 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1882 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1883 curType.getCanonicalType().getAsString());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001884 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001885 }
1886 // unlike gcc's vector_size attribute, the size is specified as the
1887 // number of elements, not the number of bytes.
Chris Lattner9cf21c52007-09-04 02:45:27 +00001888 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001889
1890 if (vectorSize == 0) {
1891 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1892 sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001893 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001894 }
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001895 // Instantiate/Install the vector type, the number of elements is > 0.
1896 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1897 // Remember this typedef decl, we will need it later for diagnostics.
1898 OCUVectorDecls.push_back(tDecl);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001899}
1900
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001901QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattner983a8bb2007-07-13 22:13:22 +00001902 AttributeList *rawAttr) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001903 // check the attribute arugments.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001904 if (rawAttr->getNumArgs() != 1) {
1905 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1906 std::string("1"));
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001907 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001908 }
1909 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
Chris Lattner23b7eb62007-06-15 23:05:46 +00001910 llvm::APSInt vecSize(32);
Chris Lattner0e9d6222007-07-15 23:26:56 +00001911 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Steve Naroffa8fd9732007-06-11 00:35:03 +00001912 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1913 sizeExpr->getSourceRange());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001914 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001915 }
1916 // navigate to the base type - we need to provide for vector pointers,
1917 // vector arrays, and functions returning vectors.
1918 Type *canonType = curType.getCanonicalType().getTypePtr();
1919
Steve Naroff91fcddb2007-07-18 18:00:27 +00001920 if (canonType->isPointerType() || canonType->isArrayType() ||
1921 canonType->isFunctionType()) {
1922 assert(1 && "HandleVector(): Complex type construction unimplemented");
1923 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1924 do {
1925 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1926 canonType = PT->getPointeeType().getTypePtr();
1927 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1928 canonType = AT->getElementType().getTypePtr();
1929 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1930 canonType = FT->getResultType().getTypePtr();
1931 } while (canonType->isPointerType() || canonType->isArrayType() ||
1932 canonType->isFunctionType());
1933 */
Steve Naroffa8fd9732007-06-11 00:35:03 +00001934 }
1935 // the base type must be integer or float.
1936 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1937 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1938 curType.getCanonicalType().getAsString());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001939 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001940 }
Chris Lattner9cf21c52007-09-04 02:45:27 +00001941 unsigned typeSize = static_cast<unsigned>(
1942 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001943 // vecSize is specified in bytes - convert to bits.
Chris Lattner9cf21c52007-09-04 02:45:27 +00001944 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001945
1946 // the vector size needs to be an integral multiple of the type size.
1947 if (vectorSize % typeSize) {
1948 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1949 sizeExpr->getSourceRange());
1950 return QualType();
1951 }
1952 if (vectorSize == 0) {
1953 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1954 sizeExpr->getSourceRange());
1955 return QualType();
1956 }
1957 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1958 // the number of elements to be a power of two (unlike GCC).
1959 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff91fcddb2007-07-18 18:00:27 +00001960 return Context.getVectorType(curType, vectorSize/typeSize);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001961}
1962