blob: 3b7d8f3467ee72bdde325ff4f965015594388eb9 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Builtins.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/Type.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Parse/Scope.h"
22#include "clang/Lex/IdentifierTable.h"
23#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
Hartmut Kaiserb61a8e42007-09-18 12:16:59 +000025#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026#include "llvm/ADT/SmallSet.h"
Hartmut Kaiserb61a8e42007-09-18 12:16:59 +000027#if !defined(LLVM_ON_WIN32)
Gabor Greifb3886be2007-09-18 11:01:25 +000028#include <alloca.h>
Hartmut Kaiserb61a8e42007-09-18 12:16:59 +000029#endif
Chris Lattner4b009652007-07-25 00:24:17 +000030using namespace clang;
31
Chris Lattner4b009652007-07-25 00:24:17 +000032Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Steve Naroff81f1bba2007-09-06 21:24:23 +000033 Decl *IIDecl = II.getFETokenInfo<Decl>();
34 if (dyn_cast_or_null<TypedefDecl>(IIDecl) ||
Fariborz Jahanianf25220e2007-09-18 20:26:58 +000035 dyn_cast_or_null<ObjcInterfaceDecl>(IIDecl))
Steve Naroff81f1bba2007-09-06 21:24:23 +000036 return IIDecl;
37 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000038}
39
40void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000041 if (S->decl_empty()) return;
42 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
43
Chris Lattner4b009652007-07-25 00:24:17 +000044 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
45 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +000046 Decl *TmpD = static_cast<Decl*>(*I);
47 assert(TmpD && "This decl didn't get pushed??");
48 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
49 assert(D && "This decl isn't a ScopedDecl?");
50
Chris Lattner4b009652007-07-25 00:24:17 +000051 IdentifierInfo *II = D->getIdentifier();
52 if (!II) continue;
53
54 // Unlink this decl from the identifier. Because the scope contains decls
55 // in an unordered collection, and because we have multiple identifier
56 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
57 if (II->getFETokenInfo<Decl>() == D) {
58 // Normal case, no multiple decls in different namespaces.
59 II->setFETokenInfo(D->getNext());
60 } else {
61 // Scan ahead. There are only three namespaces in C, so this loop can
62 // never execute more than 3 times.
Steve Naroffd21bc0d2007-09-13 18:10:37 +000063 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Chris Lattner4b009652007-07-25 00:24:17 +000064 while (SomeDecl->getNext() != D) {
65 SomeDecl = SomeDecl->getNext();
66 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
67 }
68 SomeDecl->setNext(D->getNext());
69 }
70
71 // This will have to be revisited for C++: there we want to nest stuff in
72 // namespace decls etc. Even for C, we might want a top-level translation
73 // unit decl or something.
74 if (!CurFunctionDecl)
75 continue;
76
77 // Chain this decl to the containing function, it now owns the memory for
78 // the decl.
79 D->setNext(CurFunctionDecl->getDeclChain());
80 CurFunctionDecl->setDeclChain(D);
81 }
82}
83
84/// LookupScopedDecl - Look up the inner-most declaration in the specified
85/// namespace.
Steve Naroffd21bc0d2007-09-13 18:10:37 +000086ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
87 SourceLocation IdLoc, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +000088 if (II == 0) return 0;
89 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
90
91 // Scan up the scope chain looking for a decl that matches this identifier
92 // that is in the appropriate namespace. This search should not take long, as
93 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffd21bc0d2007-09-13 18:10:37 +000094 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner4b009652007-07-25 00:24:17 +000095 if (D->getIdentifierNamespace() == NS)
96 return D;
97
98 // If we didn't find a use of this identifier, and if the identifier
99 // corresponds to a compiler builtin, create the decl object for the builtin
100 // now, injecting it into translation unit scope, and return it.
101 if (NS == Decl::IDNS_Ordinary) {
102 // If this is a builtin on some other target, or if this builtin varies
103 // across targets (e.g. in type), emit a diagnostic and mark the translation
104 // unit non-portable for using it.
105 if (II->isNonPortableBuiltin()) {
106 // Only emit this diagnostic once for this builtin.
107 II->setNonPortableBuiltin(false);
108 Context.Target.DiagnoseNonPortability(IdLoc,
109 diag::port_target_builtin_use);
110 }
111 // If this is a builtin on this (or all) targets, create the decl.
112 if (unsigned BuiltinID = II->getBuiltinID())
113 return LazilyCreateBuiltin(II, BuiltinID, S);
114 }
115 return 0;
116}
117
118/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
119/// lazily create a decl for it.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000120ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000121 Builtin::ID BID = (Builtin::ID)bid;
122
123 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
124 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner987058a2007-08-26 04:02:13 +0000125 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000126
127 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000128 if (Scope *FnS = S->getFnParent())
129 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000130 while (S->getParent())
131 S = S->getParent();
132 S->AddDecl(New);
133
134 // Add this decl to the end of the identifier info.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000135 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000136 // Scan until we find the last (outermost) decl in the id chain.
137 while (LastDecl->getNext())
138 LastDecl = LastDecl->getNext();
139 // Insert before (outside) it.
140 LastDecl->setNext(New);
141 } else {
142 II->setFETokenInfo(New);
143 }
144 // Make sure clients iterating over decls see this.
145 LastInGroupList.push_back(New);
146
147 return New;
148}
149
150/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
151/// and scope as a previous declaration 'Old'. Figure out how to resolve this
152/// situation, merging decls or emitting diagnostics as appropriate.
153///
Steve Naroffcb597472007-09-13 21:41:19 +0000154TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000155 // Verify the old decl was also a typedef.
156 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
157 if (!Old) {
158 Diag(New->getLocation(), diag::err_redefinition_different_kind,
159 New->getName());
160 Diag(OldD->getLocation(), diag::err_previous_definition);
161 return New;
162 }
163
164 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
165 // TODO: This is totally simplistic. It should handle merging functions
166 // together etc, merging extern int X; int X; ...
167 Diag(New->getLocation(), diag::err_redefinition, New->getName());
168 Diag(Old->getLocation(), diag::err_previous_definition);
169 return New;
170}
171
172/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
173/// and scope as a previous declaration 'Old'. Figure out how to resolve this
174/// situation, merging decls or emitting diagnostics as appropriate.
175///
Steve Naroffcb597472007-09-13 21:41:19 +0000176FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000177 // Verify the old decl was also a function.
178 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
179 if (!Old) {
180 Diag(New->getLocation(), diag::err_redefinition_different_kind,
181 New->getName());
182 Diag(OldD->getLocation(), diag::err_previous_definition);
183 return New;
184 }
185
186 // This is not right, but it's a start. If 'Old' is a function prototype with
187 // the same type as 'New', silently allow this. FIXME: We should link up decl
188 // objects here.
189 if (Old->getBody() == 0 &&
190 Old->getCanonicalType() == New->getCanonicalType()) {
191 return New;
192 }
193
194 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
195 // TODO: This is totally simplistic. It should handle merging functions
196 // together etc, merging extern int X; int X; ...
197 Diag(New->getLocation(), diag::err_redefinition, New->getName());
198 Diag(Old->getLocation(), diag::err_previous_definition);
199 return New;
200}
201
202/// MergeVarDecl - We just parsed a variable 'New' which has the same name
203/// and scope as a previous declaration 'Old'. Figure out how to resolve this
204/// situation, merging decls or emitting diagnostics as appropriate.
205///
206/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
207/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
208///
Steve Naroffcb597472007-09-13 21:41:19 +0000209VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000210 // Verify the old decl was also a variable.
211 VarDecl *Old = dyn_cast<VarDecl>(OldD);
212 if (!Old) {
213 Diag(New->getLocation(), diag::err_redefinition_different_kind,
214 New->getName());
215 Diag(OldD->getLocation(), diag::err_previous_definition);
216 return New;
217 }
Steve Naroff83c13012007-08-30 01:06:46 +0000218 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
219 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
220 bool OldIsTentative = false;
221
222 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
223 // Handle C "tentative" external object definitions. FIXME: finish!
224 if (!OldFSDecl->getInit() &&
225 (OldFSDecl->getStorageClass() == VarDecl::None ||
226 OldFSDecl->getStorageClass() == VarDecl::Static))
227 OldIsTentative = true;
228 }
Chris Lattner4b009652007-07-25 00:24:17 +0000229 // Verify the types match.
230 if (Old->getCanonicalType() != New->getCanonicalType()) {
231 Diag(New->getLocation(), diag::err_redefinition, New->getName());
232 Diag(Old->getLocation(), diag::err_previous_definition);
233 return New;
234 }
235 // We've verified the types match, now check if Old is "extern".
236 if (Old->getStorageClass() != VarDecl::Extern) {
237 Diag(New->getLocation(), diag::err_redefinition, New->getName());
238 Diag(Old->getLocation(), diag::err_previous_definition);
239 }
240 return New;
241}
242
243/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
244/// no declarator (e.g. "struct foo;") is parsed.
245Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
246 // TODO: emit error on 'int;' or 'const enum foo;'.
247 // TODO: emit error on 'typedef int;'
248 // if (!DS.isMissingDeclaratorOk()) Diag(...);
249
250 return 0;
251}
252
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000253bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000254 AssignmentCheckResult result;
255 SourceLocation loc = Init->getLocStart();
256 // Get the type before calling CheckSingleAssignmentConstraints(), since
257 // it can promote the expression.
258 QualType rhsType = Init->getType();
259
260 result = CheckSingleAssignmentConstraints(DeclType, Init);
261
262 // decode the result (notice that extensions still return a type).
263 switch (result) {
264 case Compatible:
265 break;
266 case Incompatible:
Steve Naroff9091f3f2007-09-02 15:34:30 +0000267 // FIXME: tighten up this check which should allow:
268 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
269 if (rhsType == Context.getPointerType(Context.CharTy))
270 break;
Steve Naroffe14e5542007-09-02 02:04:30 +0000271 Diag(loc, diag::err_typecheck_assign_incompatible,
272 DeclType.getAsString(), rhsType.getAsString(),
273 Init->getSourceRange());
274 return true;
275 case PointerFromInt:
276 // check for null pointer constant (C99 6.3.2.3p3)
277 if (!Init->isNullPointerConstant(Context)) {
278 Diag(loc, diag::ext_typecheck_assign_pointer_int,
279 DeclType.getAsString(), rhsType.getAsString(),
280 Init->getSourceRange());
281 return true;
282 }
283 break;
284 case IntFromPointer:
285 Diag(loc, diag::ext_typecheck_assign_pointer_int,
286 DeclType.getAsString(), rhsType.getAsString(),
287 Init->getSourceRange());
288 break;
289 case IncompatiblePointer:
290 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
291 DeclType.getAsString(), rhsType.getAsString(),
292 Init->getSourceRange());
293 break;
294 case CompatiblePointerDiscardsQualifiers:
295 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
296 DeclType.getAsString(), rhsType.getAsString(),
297 Init->getSourceRange());
298 break;
299 }
300 return false;
301}
302
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000303bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
304 bool isStatic, QualType ElementType) {
Steve Naroff509d0b52007-09-04 02:20:04 +0000305 SourceLocation loc;
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000306 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff509d0b52007-09-04 02:20:04 +0000307
308 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
309 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
310 return true;
311 } else if (CheckSingleInitializer(expr, ElementType)) {
312 return true; // types weren't compatible.
313 }
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000314 if (savExpr != expr) // The type was promoted, update initializer list.
315 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000316 return false;
317}
318
319void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
320 QualType ElementType, bool isStatic,
321 int &nInitializers, bool &hadError) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000322 for (unsigned i = 0; i < IList->getNumInits(); i++) {
323 Expr *expr = IList->getInit(i);
324
Steve Naroff509d0b52007-09-04 02:20:04 +0000325 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
326 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000327 int maxElements = CAT->getMaximumElements();
Steve Naroff509d0b52007-09-04 02:20:04 +0000328 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
329 maxElements, hadError);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000330 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000331 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000332 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000333 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000334 nInitializers++;
335 }
336 return;
337}
338
339// FIXME: Doesn't deal with arrays of structures yet.
340void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
341 QualType ElementType, bool isStatic,
342 int &totalInits, bool &hadError) {
343 int maxElementsAtThisLevel = 0;
344 int nInitsAtLevel = 0;
345
346 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
347 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff4f910992007-09-04 21:13:33 +0000348 maxElementsAtThisLevel = CAT->getMaximumElements();
349 // Set DeclType, used below to recurse (for multi-dimensional arrays).
350 DeclType = CAT->getElementType();
Steve Naroff509d0b52007-09-04 02:20:04 +0000351 } else if (DeclType->isScalarType()) {
352 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
353 IList->getSourceRange());
354 maxElementsAtThisLevel = 1;
355 }
356 // The empty init list "{ }" is treated specially below.
357 unsigned numInits = IList->getNumInits();
358 if (numInits) {
359 for (unsigned i = 0; i < numInits; i++) {
360 Expr *expr = IList->getInit(i);
361
362 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
363 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
364 totalInits, hadError);
365 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000366 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff509d0b52007-09-04 02:20:04 +0000367 nInitsAtLevel++; // increment the number of initializers at this level.
368 totalInits--; // decrement the total number of initializers.
369
370 // Check if we have space for another initializer.
371 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
372 Diag(expr->getLocStart(), diag::warn_excess_initializers,
373 expr->getSourceRange());
374 }
375 }
376 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
377 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
378 } else {
379 // we have an initializer list with no elements.
380 totalInits -= maxElementsAtThisLevel;
381 if (totalInits < 0)
382 Diag(IList->getLocStart(), diag::warn_excess_initializers,
383 IList->getSourceRange());
Steve Naroff9091f3f2007-09-02 15:34:30 +0000384 }
Steve Naroff1c9de712007-09-03 01:24:23 +0000385 return;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000386}
387
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000388bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000389 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroff1c9de712007-09-03 01:24:23 +0000390 if (!InitList)
391 return CheckSingleInitializer(Init, DeclType);
392
Steve Naroffe14e5542007-09-02 02:04:30 +0000393 // We have an InitListExpr, make sure we set the type.
394 Init->setType(DeclType);
Steve Naroff1c9de712007-09-03 01:24:23 +0000395
396 bool hadError = false;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000397
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000398 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
399 // of unknown size ("[]") or an object type that is not a variable array type.
400 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
401 Expr *expr = VAT->getSizeExpr();
Steve Naroff1c9de712007-09-03 01:24:23 +0000402 if (expr)
403 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
404 expr->getSourceRange());
405
Steve Naroff4f910992007-09-04 21:13:33 +0000406 // We have a VariableArrayType with unknown size. Note that only the first
407 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff509d0b52007-09-04 02:20:04 +0000408 int numInits = 0;
Steve Naroff4f910992007-09-04 21:13:33 +0000409 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
410 isStatic, numInits, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000411 if (!hadError) {
412 // Return a new array type from the number of initializers (C99 6.7.8p22).
413 llvm::APSInt ConstVal(32);
Steve Naroff509d0b52007-09-04 02:20:04 +0000414 ConstVal = numInits;
415 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroff1c9de712007-09-03 01:24:23 +0000416 ArrayType::Normal, 0);
417 }
418 return hadError;
419 }
420 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000421 int maxElements = CAT->getMaximumElements();
422 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
423 isStatic, maxElements, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000424 return hadError;
425 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000426 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
427 int maxElements = 1;
428 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
429 hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000430 return hadError;
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000431 }
432 // FIXME: Handle struct/union types.
Steve Naroff1c9de712007-09-03 01:24:23 +0000433 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +0000434}
435
Chris Lattner4b009652007-07-25 00:24:17 +0000436Sema::DeclTy *
Steve Naroff0acc9c92007-09-15 18:49:24 +0000437Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000438 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000439 IdentifierInfo *II = D.getIdentifier();
440
441 // All of these full declarators require an identifier. If it doesn't have
442 // one, the ParsedFreeStandingDeclSpec action should be used.
443 if (II == 0) {
Chris Lattner87492f42007-08-28 06:17:15 +0000444 Diag(D.getDeclSpec().getSourceRange().Begin(),
445 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000446 D.getDeclSpec().getSourceRange(), D.getSourceRange());
447 return 0;
448 }
449
Chris Lattnera7549902007-08-26 06:24:45 +0000450 // The scope passed in may not be a decl scope. Zip up the scope tree until
451 // we find one that is.
452 while ((S->getFlags() & Scope::DeclScope) == 0)
453 S = S->getParent();
454
Chris Lattner4b009652007-07-25 00:24:17 +0000455 // See if this is a redefinition of a variable in the same scope.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000456 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
457 D.getIdentifierLoc(), S);
Chris Lattner4b009652007-07-25 00:24:17 +0000458 if (PrevDecl && !S->isDeclScope(PrevDecl))
459 PrevDecl = 0; // If in outer scope, it isn't the same thing.
460
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000461 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000462 bool InvalidDecl = false;
463
Chris Lattner4b009652007-07-25 00:24:17 +0000464 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner4b009652007-07-25 00:24:17 +0000465 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
466 if (!NewTD) return 0;
467
468 // Handle attributes prior to checking for duplicates in MergeVarDecl
469 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
470 D.getAttributes());
471 // Merge the decl with the existing one if appropriate.
472 if (PrevDecl) {
473 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
474 if (NewTD == 0) return 0;
475 }
476 New = NewTD;
477 if (S->getParent() == 0) {
478 // C99 6.7.7p2: If a typedef name specifies a variably modified type
479 // then it shall have block scope.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000480 if (const VariableArrayType *VAT =
481 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
482 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
483 VAT->getSizeExpr()->getSourceRange());
484 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000485 }
486 }
487 } else if (D.isFunctionDeclarator()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000488 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000489 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000490
491 FunctionDecl::StorageClass SC;
492 switch (D.getDeclSpec().getStorageClassSpec()) {
493 default: assert(0 && "Unknown storage class!");
494 case DeclSpec::SCS_auto:
495 case DeclSpec::SCS_register:
496 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
497 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000498 InvalidDecl = true;
499 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000500 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
501 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
502 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
503 }
504
505 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000506 D.getDeclSpec().isInlineSpecified(),
Chris Lattner4b009652007-07-25 00:24:17 +0000507 LastDeclarator);
508
509 // Merge the decl with the existing one if appropriate.
510 if (PrevDecl) {
511 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
512 if (NewFD == 0) return 0;
513 }
514 New = NewFD;
515 } else {
516 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffcae537d2007-08-28 18:45:29 +0000517 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000518
519 VarDecl *NewVD;
520 VarDecl::StorageClass SC;
521 switch (D.getDeclSpec().getStorageClassSpec()) {
522 default: assert(0 && "Unknown storage class!");
523 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
524 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
525 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
526 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
527 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
528 }
529 if (S->getParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000530 // C99 6.9p2: The storage-class specifiers auto and register shall not
531 // appear in the declaration specifiers in an external declaration.
532 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
533 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
534 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000535 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000536 }
Chris Lattner4b009652007-07-25 00:24:17 +0000537 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000538 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000539 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000540 }
Chris Lattner4b009652007-07-25 00:24:17 +0000541 // Handle attributes prior to checking for duplicates in MergeVarDecl
542 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
543 D.getAttributes());
544
545 // Merge the decl with the existing one if appropriate.
546 if (PrevDecl) {
547 NewVD = MergeVarDecl(NewVD, PrevDecl);
548 if (NewVD == 0) return 0;
549 }
Chris Lattner4b009652007-07-25 00:24:17 +0000550 New = NewVD;
551 }
552
553 // If this has an identifier, add it to the scope stack.
554 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000555 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000556 II->setFETokenInfo(New);
557 S->AddDecl(New);
558 }
559
560 if (S->getParent() == 0)
561 AddTopLevelDecl(New, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000562
563 // If any semantic error occurred, mark the decl as invalid.
564 if (D.getInvalidType() || InvalidDecl)
565 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000566
567 return New;
568}
569
Steve Naroff6a0e2092007-09-12 14:07:44 +0000570void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000571 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000572 Expr *Init = static_cast<Expr *>(init);
573
Steve Naroff420d0f52007-09-12 20:13:48 +0000574 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +0000575
Steve Naroff420d0f52007-09-12 20:13:48 +0000576 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
577 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +0000578 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
579 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +0000580 RealDecl->setInvalidDecl();
581 return;
582 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000583 // Get the decls type and save a reference for later, since
584 // CheckInitializer may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +0000585 QualType DclT = VDecl->getType(), SavT = DclT;
586 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000587 VarDecl::StorageClass SC = BVD->getStorageClass();
588 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +0000589 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000590 BVD->setInvalidDecl();
591 } else if (!BVD->isInvalidDecl()) {
592 CheckInitializer(Init, DclT, SC == VarDecl::Static);
593 }
Steve Naroff420d0f52007-09-12 20:13:48 +0000594 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000595 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +0000596 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000597 if (!FVD->isInvalidDecl())
598 CheckInitializer(Init, DclT, true);
599 }
600 // If the type changed, it means we had an incomplete type that was
601 // completed by the initializer. For example:
602 // int ary[] = { 1, 3, 5 };
603 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff420d0f52007-09-12 20:13:48 +0000604 if (!VDecl->isInvalidDecl() && (DclT != SavT))
605 VDecl->setType(DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000606
607 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +0000608 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000609 return;
610}
611
Chris Lattner4b009652007-07-25 00:24:17 +0000612/// The declarators are chained together backwards, reverse the list.
613Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
614 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000615 Decl *GroupDecl = static_cast<Decl*>(group);
616 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +0000617 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +0000618
619 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
620 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000621 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000622 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000623 else { // reverse the list.
624 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000625 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +0000626 Group->setNextDeclarator(NewGroup);
627 NewGroup = Group;
628 Group = Next;
629 }
630 }
631 // Perform semantic analysis that depends on having fully processed both
632 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000633 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000634 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
635 if (!IDecl)
636 continue;
637 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
638 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
639 QualType T = IDecl->getType();
640
641 // C99 6.7.5.2p2: If an identifier is declared to be an object with
642 // static storage duration, it shall not have a variable length array.
643 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
644 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
645 if (VLA->getSizeExpr()) {
646 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
647 IDecl->setInvalidDecl();
648 }
649 }
650 }
651 // Block scope. C99 6.7p7: If an identifier for an object is declared with
652 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
653 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
654 if (T->isIncompleteType()) {
655 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
656 T.getAsString());
657 IDecl->setInvalidDecl();
658 }
659 }
660 // File scope. C99 6.9.2p2: A declaration of an identifier for and
661 // object that has file scope without an initializer, and without a
662 // storage-class specifier or with the storage-class specifier "static",
663 // constitutes a tentative definition. Note: A tentative definition with
664 // external linkage is valid (C99 6.2.2p5).
665 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
666 // C99 6.9.2p3: If the declaration of an identifier for an object is
667 // a tentative definition and has internal linkage (C99 6.2.2p3), the
668 // declared type shall not be an incomplete type.
669 if (T->isIncompleteType()) {
670 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
671 T.getAsString());
672 IDecl->setInvalidDecl();
673 }
674 }
Chris Lattner4b009652007-07-25 00:24:17 +0000675 }
676 return NewGroup;
677}
Steve Naroff91b03f72007-08-28 03:03:08 +0000678
679// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000680ParmVarDecl *
681Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
682 Scope *FnScope) {
683 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
684
685 IdentifierInfo *II = PI.Ident;
686 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
687 // Can this happen for params? We already checked that they don't conflict
688 // among each other. Here they can only shadow globals, which is ok.
689 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
690 PI.IdentLoc, FnScope)) {
691
692 }
693
694 // FIXME: Handle storage class (auto, register). No declarator?
695 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000696
697 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
698 // Doing the promotion here has a win and a loss. The win is the type for
699 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
700 // code generator). The loss is the orginal type isn't preserved. For example:
701 //
702 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
703 // int blockvardecl[5];
704 // sizeof(parmvardecl); // size == 4
705 // sizeof(blockvardecl); // size == 20
706 // }
707 //
708 // For expressions, all implicit conversions are captured using the
709 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
710 //
711 // FIXME: If a source translation tool needs to see the original type, then
712 // we need to consider storing both types (in ParmVarDecl)...
713 //
714 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
715 if (const ArrayType *AT = parmDeclType->getAsArrayType())
716 parmDeclType = Context.getPointerType(AT->getElementType());
717 else if (parmDeclType->isFunctionType())
718 parmDeclType = Context.getPointerType(parmDeclType);
719
720 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffcae537d2007-08-28 18:45:29 +0000721 VarDecl::None, 0);
722 if (PI.InvalidType)
723 New->setInvalidDecl();
724
Chris Lattner4b009652007-07-25 00:24:17 +0000725 // If this has an identifier, add it to the scope stack.
726 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000727 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000728 II->setFETokenInfo(New);
729 FnScope->AddDecl(New);
730 }
731
732 return New;
733}
734
735
736Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
737 assert(CurFunctionDecl == 0 && "Function parsing confused");
738 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
739 "Not a function declarator!");
740 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
741
742 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
743 // for a K&R function.
744 if (!FTI.hasPrototype) {
745 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
746 if (FTI.ArgInfo[i].TypeInfo == 0) {
747 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
748 FTI.ArgInfo[i].Ident->getName());
749 // Implicitly declare the argument as type 'int' for lack of a better
750 // type.
751 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
752 }
753 }
754
755 // Since this is a function definition, act as though we have information
756 // about the arguments.
757 FTI.hasPrototype = true;
758 } else {
759 // FIXME: Diagnose arguments without names in C.
760
761 }
762
763 Scope *GlobalScope = FnBodyScope->getParent();
764
765 FunctionDecl *FD =
Steve Naroff0acc9c92007-09-15 18:49:24 +0000766 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattner4b009652007-07-25 00:24:17 +0000767 CurFunctionDecl = FD;
768
769 // Create Decl objects for each parameter, adding them to the FunctionDecl.
770 llvm::SmallVector<ParmVarDecl*, 16> Params;
771
772 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
773 // no arguments, not a function that takes a single void argument.
774 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
775 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
776 // empty arg list, don't push any params.
777 } else {
778 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
779 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
780 }
781
782 FD->setParams(&Params[0], Params.size());
783
784 return FD;
785}
786
787Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
788 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
789 FD->setBody((Stmt*)Body);
790
791 assert(FD == CurFunctionDecl && "Function parsing confused");
792 CurFunctionDecl = 0;
793
794 // Verify and clean out per-function state.
795
796 // Check goto/label use.
797 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
798 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
799 // Verify that we have no forward references left. If so, there was a goto
800 // or address of a label taken, but no definition of it. Label fwd
801 // definitions are indicated with a null substmt.
802 if (I->second->getSubStmt() == 0) {
803 LabelStmt *L = I->second;
804 // Emit error.
805 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
806
807 // At this point, we have gotos that use the bogus label. Stitch it into
808 // the function body so that they aren't leaked and that the AST is well
809 // formed.
810 L->setSubStmt(new NullStmt(L->getIdentLoc()));
811 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
812 }
813 }
814 LabelMap.clear();
815
816 return FD;
817}
818
819
820/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
821/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +0000822ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
823 IdentifierInfo &II, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000824 if (getLangOptions().C99) // Extension in C99.
825 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
826 else // Legal in C90, but warn about it.
827 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
828
829 // FIXME: handle stuff like:
830 // void foo() { extern float X(); }
831 // void bar() { X(); } <-- implicit decl for X in another scope.
832
833 // Set a Declarator for the implicit definition: int foo();
834 const char *Dummy;
835 DeclSpec DS;
836 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
837 Error = Error; // Silence warning.
838 assert(!Error && "Error setting up implicit decl!");
839 Declarator D(DS, Declarator::BlockContext);
840 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
841 D.SetIdentifier(&II, Loc);
842
843 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000844 if (Scope *FnS = S->getFnParent())
845 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000846 while (S->getParent())
847 S = S->getParent();
848
Steve Narofff0c31dd2007-09-16 16:16:00 +0000849 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattner4b009652007-07-25 00:24:17 +0000850}
851
852
853TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
Steve Naroff2591e1b2007-09-13 23:52:58 +0000854 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +0000855 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
856
857 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000858 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000859
860 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000861 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
862 T, LastDeclarator);
863 if (D.getInvalidType())
864 NewTD->setInvalidDecl();
865 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +0000866}
867
Steve Naroff81f1bba2007-09-06 21:24:23 +0000868Sema::DeclTy *Sema::ObjcStartClassInterface(SourceLocation AtInterfaceLoc,
869 IdentifierInfo *ClassName, SourceLocation ClassLoc,
870 IdentifierInfo *SuperName, SourceLocation SuperLoc,
871 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
872 AttributeList *AttrList) {
873 assert(ClassName && "Missing class identifier");
874 ObjcInterfaceDecl *IDecl;
875
876 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, ClassName);
877
878 // Chain & install the interface decl into the identifier.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000879 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
Steve Naroff81f1bba2007-09-06 21:24:23 +0000880 ClassName->setFETokenInfo(IDecl);
881 return IDecl;
882}
883
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +0000884Sema::DeclTy *Sema::ObjcStartProtoInterface(SourceLocation AtProtoInterfaceLoc,
885 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
886 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
887 assert(ProtocolName && "Missing protocol identifier");
888 ObjcProtocolDecl *PDecl;
889
890 PDecl = new ObjcProtocolDecl(AtProtoInterfaceLoc, ProtocolName);
891
892 // Chain & install the protocol decl into the identifier.
893 PDecl->setNext(ProtocolName->getFETokenInfo<ScopedDecl>());
894 ProtocolName->setFETokenInfo(PDecl);
895 return PDecl;
896}
897
Fariborz Jahanianf25220e2007-09-18 20:26:58 +0000898Sema::DeclTy *Sema::ObjcStartCatInterface(SourceLocation AtInterfaceLoc,
899 IdentifierInfo *ClassName, SourceLocation ClassLoc,
900 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
901 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
902 ObjcCategoryDecl *CDecl;
903 CDecl = new ObjcCategoryDecl(AtInterfaceLoc, ClassName);
904 assert (ClassName->getFETokenInfo<ScopedDecl>() && "Missing @interface decl");
905 Decl *D = static_cast<Decl *>(ClassName->getFETokenInfo<ScopedDecl>());
906 assert(isa<ObjcInterfaceDecl>(D) && "Missing @interface decl");
907
908 // Chain & install the category decl into the identifier.
909 // Note that head of the chain is the @interface class type and follow up
910 // nodes in the chain are the protocol decl nodes.
911 cast<ObjcInterfaceDecl>(D)->setNext(CDecl);
912 return CDecl;
913}
Steve Naroff81f1bba2007-09-06 21:24:23 +0000914/// ObjcClassDeclaration -
915/// Scope will always be top level file scope.
916Action::DeclTy *
917Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
918 IdentifierInfo **IdentList, unsigned NumElts) {
919 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
920
921 for (unsigned i = 0; i != NumElts; ++i) {
922 ObjcInterfaceDecl *IDecl;
923
Steve Narofffaed3bf2007-09-10 20:51:04 +0000924 // FIXME: before we create one, look up the interface decl in a hash table.
Steve Naroff81f1bba2007-09-06 21:24:23 +0000925 IDecl = new ObjcInterfaceDecl(SourceLocation(), IdentList[i], true);
926 // Chain & install the interface decl into the identifier.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000927 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
Steve Naroff81f1bba2007-09-06 21:24:23 +0000928 IdentList[i]->setFETokenInfo(IDecl);
929
930 // Remember that this needs to be removed when the scope is popped.
931 S->AddDecl(IdentList[i]);
932
933 CDecl->setInterfaceDecl((int)i, IDecl);
934 }
935 return CDecl;
936}
937
Chris Lattner4b009652007-07-25 00:24:17 +0000938
Steve Naroff0acc9c92007-09-15 18:49:24 +0000939/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +0000940/// former case, Name will be non-null. In the later case, Name will be null.
941/// TagType indicates what kind of tag this is. TK indicates whether this is a
942/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000943Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +0000944 SourceLocation KWLoc, IdentifierInfo *Name,
945 SourceLocation NameLoc, AttributeList *Attr) {
946 // If this is a use of an existing tag, it must have a name.
947 assert((Name != 0 || TK == TK_Definition) &&
948 "Nameless record must be a definition!");
949
950 Decl::Kind Kind;
951 switch (TagType) {
952 default: assert(0 && "Unknown tag type!");
953 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
954 case DeclSpec::TST_union: Kind = Decl::Union; break;
955//case DeclSpec::TST_class: Kind = Decl::Class; break;
956 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
957 }
958
959 // If this is a named struct, check to see if there was a previous forward
960 // declaration or definition.
961 if (TagDecl *PrevDecl =
962 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
963 NameLoc, S))) {
964
965 // If this is a use of a previous tag, or if the tag is already declared in
966 // the same scope (so that the definition/declaration completes or
967 // rementions the tag), reuse the decl.
968 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
969 // Make sure that this wasn't declared as an enum and now used as a struct
970 // or something similar.
971 if (PrevDecl->getKind() != Kind) {
972 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
973 Diag(PrevDecl->getLocation(), diag::err_previous_use);
974 }
975
976 // If this is a use or a forward declaration, we're good.
977 if (TK != TK_Definition)
978 return PrevDecl;
979
980 // Diagnose attempts to redefine a tag.
981 if (PrevDecl->isDefinition()) {
982 Diag(NameLoc, diag::err_redefinition, Name->getName());
983 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
984 // If this is a redefinition, recover by making this struct be
985 // anonymous, which will make any later references get the previous
986 // definition.
987 Name = 0;
988 } else {
989 // Okay, this is definition of a previously declared or referenced tag.
990 // Move the location of the decl to be the definition site.
991 PrevDecl->setLocation(NameLoc);
992 return PrevDecl;
993 }
994 }
995 // If we get here, this is a definition of a new struct type in a nested
996 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
997 // type.
998 }
999
1000 // If there is an identifier, use the location of the identifier as the
1001 // location of the decl, otherwise use the location of the struct/union
1002 // keyword.
1003 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1004
1005 // Otherwise, if this is the first time we've seen this tag, create the decl.
1006 TagDecl *New;
1007 switch (Kind) {
1008 default: assert(0 && "Unknown tag kind!");
1009 case Decl::Enum:
1010 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1011 // enum X { A, B, C } D; D should chain to X.
1012 New = new EnumDecl(Loc, Name, 0);
1013 // If this is an undefined enum, warn.
1014 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1015 break;
1016 case Decl::Union:
1017 case Decl::Struct:
1018 case Decl::Class:
1019 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1020 // struct X { int A; } D; D should chain to X.
1021 New = new RecordDecl(Kind, Loc, Name, 0);
1022 break;
1023 }
1024
1025 // If this has an identifier, add it to the scope stack.
1026 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001027 // The scope passed in may not be a decl scope. Zip up the scope tree until
1028 // we find one that is.
1029 while ((S->getFlags() & Scope::DeclScope) == 0)
1030 S = S->getParent();
1031
1032 // Add it to the decl chain.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001033 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001034 Name->setFETokenInfo(New);
1035 S->AddDecl(New);
1036 }
1037
1038 return New;
1039}
1040
Steve Naroff0acc9c92007-09-15 18:49:24 +00001041/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001042/// to create a FieldDecl object for it.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001043Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001044 SourceLocation DeclStart,
1045 Declarator &D, ExprTy *BitfieldWidth) {
1046 IdentifierInfo *II = D.getIdentifier();
1047 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001048 SourceLocation Loc = DeclStart;
1049 if (II) Loc = D.getIdentifierLoc();
1050
1051 // FIXME: Unnamed fields can be handled in various different ways, for
1052 // example, unnamed unions inject all members into the struct namespace!
1053
1054
1055 if (BitWidth) {
1056 // TODO: Validate.
1057 //printf("WARNING: BITFIELDS IGNORED!\n");
1058
1059 // 6.7.2.1p3
1060 // 6.7.2.1p4
1061
1062 } else {
1063 // Not a bitfield.
1064
1065 // validate II.
1066
1067 }
1068
1069 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001070 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1071 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001072
Chris Lattner4b009652007-07-25 00:24:17 +00001073 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1074 // than a variably modified type.
Steve Naroff5eb879b2007-08-31 17:20:07 +00001075 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1076 Diag(Loc, diag::err_typecheck_illegal_vla,
1077 VAT->getSizeExpr()->getSourceRange());
1078 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001079 }
Chris Lattner4b009652007-07-25 00:24:17 +00001080 // FIXME: Chain fielddecls together.
Steve Naroff75494892007-09-11 21:17:26 +00001081 FieldDecl *NewFD;
1082
1083 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Naroffdc1ad762007-09-14 02:20:46 +00001084 NewFD = new FieldDecl(Loc, II, T);
Steve Naroff75494892007-09-11 21:17:26 +00001085 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl)))
Steve Naroffdc1ad762007-09-14 02:20:46 +00001086 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff75494892007-09-11 21:17:26 +00001087 else
Steve Naroff0acc9c92007-09-15 18:49:24 +00001088 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff75494892007-09-11 21:17:26 +00001089
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001090 if (D.getInvalidType() || InvalidDecl)
1091 NewFD->setInvalidDecl();
1092 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001093}
1094
Steve Naroffffeaa552007-09-14 23:09:53 +00001095static void ObjcSetIvarVisibility(ObjcIvarDecl *OIvar,
1096 tok::ObjCKeywordKind ivarVisibility) {
1097 assert(OIvar && "missing instance variable");
1098 switch (ivarVisibility) {
1099 case tok::objc_private:
1100 OIvar->setAccessControl(ObjcIvarDecl::Private);
1101 break;
1102 case tok::objc_public:
1103 OIvar->setAccessControl(ObjcIvarDecl::Public);
1104 break;
1105 case tok::objc_protected:
1106 OIvar->setAccessControl(ObjcIvarDecl::Protected);
1107 break;
1108 case tok::objc_package:
1109 OIvar->setAccessControl(ObjcIvarDecl::Package);
1110 break;
1111 default:
1112 OIvar->setAccessControl(ObjcIvarDecl::None);
1113 break;
1114 }
1115}
1116
Steve Naroff0acc9c92007-09-15 18:49:24 +00001117void Sema::ActOnFields(SourceLocation RecLoc, DeclTy *RecDecl,
1118 DeclTy **Fields, unsigned NumFields,
1119 tok::ObjCKeywordKind *visibility) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001120 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1121 assert(EnclosingDecl && "missing record or interface decl");
1122 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1123
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001124 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001125 // Diagnose code like:
1126 // struct S { struct S {} X; };
1127 // We discover this when we complete the outer S. Reject and ignore the
1128 // outer S.
1129 Diag(Record->getLocation(), diag::err_nested_redefinition,
1130 Record->getKindName());
1131 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001132 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001133 return;
1134 }
Chris Lattner4b009652007-07-25 00:24:17 +00001135 // Verify that all the fields are okay.
1136 unsigned NumNamedMembers = 0;
1137 llvm::SmallVector<FieldDecl*, 32> RecFields;
1138 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00001139
Chris Lattner4b009652007-07-25 00:24:17 +00001140 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001141
Steve Naroff9bb759f2007-09-14 22:20:54 +00001142 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1143 assert(FD && "missing field decl");
1144
1145 // Remember all fields.
1146 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00001147
1148 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001149 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +00001150
Steve Naroffffeaa552007-09-14 23:09:53 +00001151 // If we have visibility info, make sure the AST is set accordingly.
1152 if (visibility)
1153 ObjcSetIvarVisibility(dyn_cast<ObjcIvarDecl>(FD), visibility[i]);
1154
Chris Lattner4b009652007-07-25 00:24:17 +00001155 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001156 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001157 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00001158 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001159 FD->setInvalidDecl();
1160 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001161 continue;
1162 }
Chris Lattner4b009652007-07-25 00:24:17 +00001163 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1164 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001165 if (!Record) { // Incomplete ivar type is always an error.
1166 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001167 FD->setInvalidDecl();
1168 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001169 continue;
1170 }
Chris Lattner4b009652007-07-25 00:24:17 +00001171 if (i != NumFields-1 || // ... that the last member ...
1172 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001173 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001174 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001175 FD->setInvalidDecl();
1176 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001177 continue;
1178 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001179 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00001180 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1181 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001182 FD->setInvalidDecl();
1183 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001184 continue;
1185 }
Chris Lattner4b009652007-07-25 00:24:17 +00001186 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001187 if (Record)
1188 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001189 }
Chris Lattner4b009652007-07-25 00:24:17 +00001190 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1191 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001192 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001193 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1194 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001195 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner4b009652007-07-25 00:24:17 +00001196 Record->setHasFlexibleArrayMember(true);
1197 } else {
1198 // If this is a struct/class and this is not the last element, reject
1199 // it. Note that GCC supports variable sized arrays in the middle of
1200 // structures.
1201 if (i != NumFields-1) {
1202 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1203 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001204 FD->setInvalidDecl();
1205 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001206 continue;
1207 }
Chris Lattner4b009652007-07-25 00:24:17 +00001208 // We support flexible arrays at the end of structs in other structs
1209 // as an extension.
1210 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1211 FD->getName());
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001212 if (Record)
1213 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001214 }
1215 }
1216 }
Chris Lattner4b009652007-07-25 00:24:17 +00001217 // Keep track of the number of named members.
1218 if (IdentifierInfo *II = FD->getIdentifier()) {
1219 // Detect duplicate member names.
1220 if (!FieldIDs.insert(II)) {
1221 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1222 // Find the previous decl.
1223 SourceLocation PrevLoc;
1224 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1225 assert(i != e && "Didn't find previous def!");
1226 if (RecFields[i]->getIdentifier() == II) {
1227 PrevLoc = RecFields[i]->getLocation();
1228 break;
1229 }
1230 }
1231 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001232 FD->setInvalidDecl();
1233 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001234 continue;
1235 }
1236 ++NumNamedMembers;
1237 }
Chris Lattner4b009652007-07-25 00:24:17 +00001238 }
1239
Chris Lattner4b009652007-07-25 00:24:17 +00001240 // Okay, we successfully defined 'Record'.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001241 if (Record)
1242 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001243 else {
1244 ObjcIvarDecl **ClsFields =
1245 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
1246 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1247 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1248 }
Chris Lattner4b009652007-07-25 00:24:17 +00001249}
1250
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001251void Sema::ObjcAddMethodsToClass(DeclTy *ClassDecl,
1252 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001253 // FIXME: Fix this when we can handle methods declared in protocols.
1254 // See Parser::ParseObjCAtProtocolDeclaration
1255 if (!ClassDecl)
1256 return;
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001257 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1258 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1259
1260 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001261 ObjcMethodDecl *Method =
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001262 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1263 if (!Method) continue; // Already issued a diagnostic.
1264 if (Method->isInstance())
1265 insMethods.push_back(Method);
1266 else
1267 clsMethods.push_back(Method);
1268 }
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001269 if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(ClassDecl))) {
1270 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1271 static_cast<Decl*>(ClassDecl));
1272 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1273 &clsMethods[0], clsMethods.size());
1274 }
1275 else if (isa<ObjcProtocolDecl>(static_cast<Decl *>(ClassDecl))) {
1276 ObjcProtocolDecl *Protocol = cast<ObjcProtocolDecl>(
1277 static_cast<Decl*>(ClassDecl));
1278 Protocol->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1279 &clsMethods[0], clsMethods.size());
1280 }
Fariborz Jahanianf25220e2007-09-18 20:26:58 +00001281 else if (isa<ObjcCategoryDecl>(static_cast<Decl *>(ClassDecl))) {
1282 ObjcCategoryDecl *Category = cast<ObjcCategoryDecl>(
1283 static_cast<Decl*>(ClassDecl));
1284 Category->ObjcAddCatMethods(&insMethods[0], insMethods.size(),
1285 &clsMethods[0], clsMethods.size());
1286 }
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001287 else
1288 assert(0 && "Sema::ObjcAddMethodsToClass(): Unknown DeclTy");
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001289 return;
1290}
1291
Fariborz Jahanian8b5ab6f2007-09-18 00:25:23 +00001292Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
Steve Naroff253118b2007-09-17 20:25:27 +00001293 tok::TokenKind MethodType, TypeTy *ReturnType,
1294 ObjcKeywordDecl *Keywords, unsigned NumKeywords,
Fariborz Jahanian8b5ab6f2007-09-18 00:25:23 +00001295 AttributeList *AttrList,
1296 tok::ObjCKeywordKind MethodDeclKind) {
Steve Naroff253118b2007-09-17 20:25:27 +00001297 assert(NumKeywords && "Selector must be specified");
1298
1299 // Derive the selector name from the keyword declarations.
Steve Naroff948fd372007-09-17 14:16:13 +00001300 int len=0;
1301 char *methodName;
Steve Naroff253118b2007-09-17 20:25:27 +00001302 for (unsigned int i = 0; i < NumKeywords; i++) {
1303 if (Keywords[i].SelectorName)
1304 len += strlen(Keywords[i].SelectorName->getName());
Steve Naroff948fd372007-09-17 14:16:13 +00001305 len++;
1306 }
1307 methodName = (char *) alloca (len + 1);
1308 methodName[0] = '\0';
Steve Naroff253118b2007-09-17 20:25:27 +00001309 for (unsigned int i = 0; i < NumKeywords; i++) {
1310 if (Keywords[i].SelectorName)
1311 strcat(methodName, Keywords[i].SelectorName->getName());
Steve Naroff948fd372007-09-17 14:16:13 +00001312 strcat(methodName, ":");
1313 }
Steve Naroff253118b2007-09-17 20:25:27 +00001314 SelectorInfo &SelName = Context.getSelectorInfo(methodName, methodName+len);
Steve Naroff948fd372007-09-17 14:16:13 +00001315
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001316 llvm::SmallVector<ParmVarDecl*, 16> Params;
1317
1318 for (unsigned i = 0; i < NumKeywords; i++) {
Steve Naroff253118b2007-09-17 20:25:27 +00001319 ObjcKeywordDecl *arg = &Keywords[i];
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001320 // FIXME: arg->AttrList must be stored too!
1321 ParmVarDecl* Param = new ParmVarDecl(arg->ColonLoc, arg->ArgumentName,
1322 QualType::getFromOpaquePtr(arg->TypeInfo),
1323 VarDecl::None, 0);
1324 // FIXME: 'InvalidType' does not get set by caller yet.
1325 if (arg->InvalidType)
1326 Param->setInvalidDecl();
1327 Params.push_back(Param);
1328 }
1329 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Fariborz Jahanian4a2b0ac2007-09-17 22:36:42 +00001330 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc,
1331 SelName, resultDeclType,
1332 0, -1, AttrList, MethodType == tok::minus);
1333 ObjcMethod->setMethodParams(&Params[0], NumKeywords);
Fariborz Jahanian8b5ab6f2007-09-18 00:25:23 +00001334 if (MethodDeclKind == tok::objc_optional)
Fariborz Jahanian4a2b0ac2007-09-17 22:36:42 +00001335 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Optional);
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001336 else
Fariborz Jahanian4a2b0ac2007-09-17 22:36:42 +00001337 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Required);
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001338 return ObjcMethod;
1339}
1340
Fariborz Jahanian8b5ab6f2007-09-18 00:25:23 +00001341Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001342 tok::TokenKind MethodType, TypeTy *ReturnType,
Fariborz Jahanian8b5ab6f2007-09-18 00:25:23 +00001343 IdentifierInfo *SelectorName, AttributeList *AttrList,
1344 tok::ObjCKeywordKind MethodDeclKind) {
Steve Naroff948fd372007-09-17 14:16:13 +00001345 const char *methodName = SelectorName->getName();
1346 SelectorInfo &SelName = Context.getSelectorInfo(methodName,
1347 methodName+strlen(methodName));
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001348 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Fariborz Jahanian4a2b0ac2007-09-17 22:36:42 +00001349 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc,
1350 SelName, resultDeclType, 0, -1,
1351 AttrList, MethodType == tok::minus);
Fariborz Jahanian8b5ab6f2007-09-18 00:25:23 +00001352 if (MethodDeclKind == tok::objc_optional)
Fariborz Jahanian4a2b0ac2007-09-17 22:36:42 +00001353 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Optional);
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001354 else
Fariborz Jahanian4a2b0ac2007-09-17 22:36:42 +00001355 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Required);
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001356 return ObjcMethod;
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001357}
1358
Steve Naroff0acc9c92007-09-15 18:49:24 +00001359Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001360 DeclTy *lastEnumConst,
1361 SourceLocation IdLoc, IdentifierInfo *Id,
1362 SourceLocation EqualLoc, ExprTy *val) {
1363 theEnumDecl = theEnumDecl; // silence unused warning.
1364 EnumConstantDecl *LastEnumConst =
1365 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1366 Expr *Val = static_cast<Expr*>(val);
1367
Chris Lattnera7549902007-08-26 06:24:45 +00001368 // The scope passed in may not be a decl scope. Zip up the scope tree until
1369 // we find one that is.
1370 while ((S->getFlags() & Scope::DeclScope) == 0)
1371 S = S->getParent();
1372
Chris Lattner4b009652007-07-25 00:24:17 +00001373 // Verify that there isn't already something declared with this name in this
1374 // scope.
Steve Naroffcb597472007-09-13 21:41:19 +00001375 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1376 IdLoc, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001377 if (S->isDeclScope(PrevDecl)) {
1378 if (isa<EnumConstantDecl>(PrevDecl))
1379 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1380 else
1381 Diag(IdLoc, diag::err_redefinition, Id->getName());
1382 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1383 // FIXME: Don't leak memory: delete Val;
1384 return 0;
1385 }
1386 }
1387
1388 llvm::APSInt EnumVal(32);
1389 QualType EltTy;
1390 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001391 // Make sure to promote the operand type to int.
1392 UsualUnaryConversions(Val);
1393
Chris Lattner4b009652007-07-25 00:24:17 +00001394 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1395 SourceLocation ExpLoc;
1396 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1397 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1398 Id->getName());
1399 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001400 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001401 } else {
1402 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001403 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001404 }
1405
1406 if (!Val) {
1407 if (LastEnumConst) {
1408 // Assign the last value + 1.
1409 EnumVal = LastEnumConst->getInitVal();
1410 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001411
1412 // Check for overflow on increment.
1413 if (EnumVal < LastEnumConst->getInitVal())
1414 Diag(IdLoc, diag::warn_enum_value_overflow);
1415
Chris Lattnere7f53a42007-08-27 17:37:24 +00001416 EltTy = LastEnumConst->getType();
1417 } else {
1418 // First value, set to zero.
1419 EltTy = Context.IntTy;
Chris Lattner3496d522007-09-04 02:45:27 +00001420 EnumVal.zextOrTrunc(
1421 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001422 }
Chris Lattner4b009652007-07-25 00:24:17 +00001423 }
1424
Chris Lattner4b009652007-07-25 00:24:17 +00001425 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1426 LastEnumConst);
1427
1428 // Register this decl in the current scope stack.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001429 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001430 Id->setFETokenInfo(New);
1431 S->AddDecl(New);
1432 return New;
1433}
1434
Steve Naroff0acc9c92007-09-15 18:49:24 +00001435void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00001436 DeclTy **Elements, unsigned NumElements) {
1437 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1438 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1439
Chris Lattner435c3fd2007-08-28 05:10:31 +00001440 // TODO: If the result value doesn't fit in an int, it must be a long or long
1441 // long value. ISO C does not support this, but GCC does as an extension,
1442 // emit a warning.
Chris Lattner206754a2007-08-28 06:15:15 +00001443 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner435c3fd2007-08-28 05:10:31 +00001444
1445
Chris Lattner206754a2007-08-28 06:15:15 +00001446 // Verify that all the values are okay, compute the size of the values, and
1447 // reverse the list.
1448 unsigned NumNegativeBits = 0;
1449 unsigned NumPositiveBits = 0;
1450
1451 // Keep track of whether all elements have type int.
1452 bool AllElementsInt = true;
1453
Chris Lattner4b009652007-07-25 00:24:17 +00001454 EnumConstantDecl *EltList = 0;
1455 for (unsigned i = 0; i != NumElements; ++i) {
1456 EnumConstantDecl *ECD =
1457 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1458 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001459
1460 // If the enum value doesn't fit in an int, emit an extension warning.
1461 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1462 "Should have promoted value to int");
1463 const llvm::APSInt &InitVal = ECD->getInitVal();
1464 if (InitVal.getBitWidth() > IntWidth) {
1465 llvm::APSInt V(InitVal);
1466 V.trunc(IntWidth);
1467 V.extend(InitVal.getBitWidth());
1468 if (V != InitVal)
1469 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1470 InitVal.toString());
1471 }
Chris Lattner206754a2007-08-28 06:15:15 +00001472
1473 // Keep track of the size of positive and negative values.
1474 if (InitVal.isUnsigned() || !InitVal.isNegative())
1475 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1476 else
1477 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001478
Chris Lattner206754a2007-08-28 06:15:15 +00001479 // Keep track of whether every enum element has type int (very commmon).
1480 if (AllElementsInt)
1481 AllElementsInt = ECD->getType() == Context.IntTy;
1482
Chris Lattner4b009652007-07-25 00:24:17 +00001483 ECD->setNextDeclarator(EltList);
1484 EltList = ECD;
1485 }
1486
Chris Lattner206754a2007-08-28 06:15:15 +00001487 // Figure out the type that should be used for this enum.
1488 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1489 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001490 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001491
1492 if (NumNegativeBits) {
1493 // If there is a negative value, figure out the smallest integer type (of
1494 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001495 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001496 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001497 BestWidth = IntWidth;
1498 } else {
1499 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1500 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001501 BestType = Context.LongTy;
1502 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001503 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1504 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001505 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1506 BestType = Context.LongLongTy;
1507 }
1508 }
1509 } else {
1510 // If there is no negative value, figure out which of uint, ulong, ulonglong
1511 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001512 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001513 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001514 BestWidth = IntWidth;
1515 } else if (NumPositiveBits <=
1516 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattner206754a2007-08-28 06:15:15 +00001517 BestType = Context.UnsignedLongTy;
1518 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001519 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1520 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001521 "How could an initializer get larger than ULL?");
1522 BestType = Context.UnsignedLongLongTy;
1523 }
1524 }
1525
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001526 // Loop over all of the enumerator constants, changing their types to match
1527 // the type of the enum if needed.
1528 for (unsigned i = 0; i != NumElements; ++i) {
1529 EnumConstantDecl *ECD =
1530 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1531 if (!ECD) continue; // Already issued a diagnostic.
1532
1533 // Standard C says the enumerators have int type, but we allow, as an
1534 // extension, the enumerators to be larger than int size. If each
1535 // enumerator value fits in an int, type it as an int, otherwise type it the
1536 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1537 // that X has type 'int', not 'unsigned'.
1538 if (ECD->getType() == Context.IntTy)
1539 continue; // Already int type.
1540
1541 // Determine whether the value fits into an int.
1542 llvm::APSInt InitVal = ECD->getInitVal();
1543 bool FitsInInt;
1544 if (InitVal.isUnsigned() || !InitVal.isNegative())
1545 FitsInInt = InitVal.getActiveBits() < IntWidth;
1546 else
1547 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1548
1549 // If it fits into an integer type, force it. Otherwise force it to match
1550 // the enum decl type.
1551 QualType NewTy;
1552 unsigned NewWidth;
1553 bool NewSign;
1554 if (FitsInInt) {
1555 NewTy = Context.IntTy;
1556 NewWidth = IntWidth;
1557 NewSign = true;
1558 } else if (ECD->getType() == BestType) {
1559 // Already the right type!
1560 continue;
1561 } else {
1562 NewTy = BestType;
1563 NewWidth = BestWidth;
1564 NewSign = BestType->isSignedIntegerType();
1565 }
1566
1567 // Adjust the APSInt value.
1568 InitVal.extOrTrunc(NewWidth);
1569 InitVal.setIsSigned(NewSign);
1570 ECD->setInitVal(InitVal);
1571
1572 // Adjust the Expr initializer and type.
1573 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1574 ECD->setType(NewTy);
1575 }
Chris Lattner206754a2007-08-28 06:15:15 +00001576
Chris Lattner90a018d2007-08-28 18:24:31 +00001577 Enum->defineElements(EltList, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00001578}
1579
1580void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1581 if (!current) return;
1582
1583 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1584 // remember this in the LastInGroupList list.
1585 if (last)
1586 LastInGroupList.push_back((Decl*)last);
1587}
1588
1589void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1590 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1591 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1592 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1593 if (!newType.isNull()) // install the new vector type into the decl
1594 vDecl->setType(newType);
1595 }
1596 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1597 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1598 rawAttr);
1599 if (!newType.isNull()) // install the new vector type into the decl
1600 tDecl->setUnderlyingType(newType);
1601 }
1602 }
1603 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroff82113e32007-07-29 16:33:31 +00001604 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1605 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1606 else
Chris Lattner4b009652007-07-25 00:24:17 +00001607 Diag(rawAttr->getAttributeLoc(),
1608 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner4b009652007-07-25 00:24:17 +00001609 }
1610 // FIXME: add other attributes...
1611}
1612
1613void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1614 AttributeList *declarator_postfix) {
1615 while (declspec_prefix) {
1616 HandleDeclAttribute(New, declspec_prefix);
1617 declspec_prefix = declspec_prefix->getNext();
1618 }
1619 while (declarator_postfix) {
1620 HandleDeclAttribute(New, declarator_postfix);
1621 declarator_postfix = declarator_postfix->getNext();
1622 }
1623}
1624
Steve Naroff82113e32007-07-29 16:33:31 +00001625void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1626 AttributeList *rawAttr) {
1627 QualType curType = tDecl->getUnderlyingType();
Chris Lattner4b009652007-07-25 00:24:17 +00001628 // check the attribute arugments.
1629 if (rawAttr->getNumArgs() != 1) {
1630 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1631 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001632 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001633 }
1634 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1635 llvm::APSInt vecSize(32);
1636 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1637 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1638 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001639 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001640 }
1641 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1642 // in conjunction with complex types (pointers, arrays, functions, etc.).
1643 Type *canonType = curType.getCanonicalType().getTypePtr();
1644 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1645 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1646 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001647 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001648 }
1649 // unlike gcc's vector_size attribute, the size is specified as the
1650 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00001651 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00001652
1653 if (vectorSize == 0) {
1654 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1655 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001656 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001657 }
Steve Naroff82113e32007-07-29 16:33:31 +00001658 // Instantiate/Install the vector type, the number of elements is > 0.
1659 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1660 // Remember this typedef decl, we will need it later for diagnostics.
1661 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001662}
1663
1664QualType Sema::HandleVectorTypeAttribute(QualType curType,
1665 AttributeList *rawAttr) {
1666 // check the attribute arugments.
1667 if (rawAttr->getNumArgs() != 1) {
1668 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1669 std::string("1"));
1670 return QualType();
1671 }
1672 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1673 llvm::APSInt vecSize(32);
1674 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1675 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1676 sizeExpr->getSourceRange());
1677 return QualType();
1678 }
1679 // navigate to the base type - we need to provide for vector pointers,
1680 // vector arrays, and functions returning vectors.
1681 Type *canonType = curType.getCanonicalType().getTypePtr();
1682
1683 if (canonType->isPointerType() || canonType->isArrayType() ||
1684 canonType->isFunctionType()) {
1685 assert(1 && "HandleVector(): Complex type construction unimplemented");
1686 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1687 do {
1688 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1689 canonType = PT->getPointeeType().getTypePtr();
1690 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1691 canonType = AT->getElementType().getTypePtr();
1692 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1693 canonType = FT->getResultType().getTypePtr();
1694 } while (canonType->isPointerType() || canonType->isArrayType() ||
1695 canonType->isFunctionType());
1696 */
1697 }
1698 // the base type must be integer or float.
1699 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1700 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1701 curType.getCanonicalType().getAsString());
1702 return QualType();
1703 }
Chris Lattner3496d522007-09-04 02:45:27 +00001704 unsigned typeSize = static_cast<unsigned>(
1705 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Chris Lattner4b009652007-07-25 00:24:17 +00001706 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00001707 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00001708
1709 // the vector size needs to be an integral multiple of the type size.
1710 if (vectorSize % typeSize) {
1711 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1712 sizeExpr->getSourceRange());
1713 return QualType();
1714 }
1715 if (vectorSize == 0) {
1716 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1717 sizeExpr->getSourceRange());
1718 return QualType();
1719 }
1720 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1721 // the number of elements to be a power of two (unlike GCC).
1722 // Instantiate the vector type, the number of elements is > 0.
1723 return Context.getVectorType(curType, vectorSize/typeSize);
1724}
1725