blob: d5ca7969349df68b2b7aa78594c262dadda26693 [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"
Steve Naroffc39ca262007-09-18 23:55:05 +000026#include "llvm/ADT/SmallString.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallSet.h"
Hartmut Kaiserb61a8e42007-09-18 12:16:59 +000028#if !defined(LLVM_ON_WIN32)
Gabor Greifb3886be2007-09-18 11:01:25 +000029#include <alloca.h>
Hartmut Kaiserb61a8e42007-09-18 12:16:59 +000030#endif
Chris Lattner4b009652007-07-25 00:24:17 +000031using namespace clang;
32
Chris Lattner4b009652007-07-25 00:24:17 +000033Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Steve Naroff81f1bba2007-09-06 21:24:23 +000034 Decl *IIDecl = II.getFETokenInfo<Decl>();
35 if (dyn_cast_or_null<TypedefDecl>(IIDecl) ||
Fariborz Jahanianf25220e2007-09-18 20:26:58 +000036 dyn_cast_or_null<ObjcInterfaceDecl>(IIDecl))
Steve Naroff81f1bba2007-09-06 21:24:23 +000037 return IIDecl;
38 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000039}
40
41void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000042 if (S->decl_empty()) return;
43 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
44
Chris Lattner4b009652007-07-25 00:24:17 +000045 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
46 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +000047 Decl *TmpD = static_cast<Decl*>(*I);
48 assert(TmpD && "This decl didn't get pushed??");
49 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
50 assert(D && "This decl isn't a ScopedDecl?");
51
Chris Lattner4b009652007-07-25 00:24:17 +000052 IdentifierInfo *II = D->getIdentifier();
53 if (!II) continue;
54
55 // Unlink this decl from the identifier. Because the scope contains decls
56 // in an unordered collection, and because we have multiple identifier
57 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
58 if (II->getFETokenInfo<Decl>() == D) {
59 // Normal case, no multiple decls in different namespaces.
60 II->setFETokenInfo(D->getNext());
61 } else {
62 // Scan ahead. There are only three namespaces in C, so this loop can
63 // never execute more than 3 times.
Steve Naroffd21bc0d2007-09-13 18:10:37 +000064 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Chris Lattner4b009652007-07-25 00:24:17 +000065 while (SomeDecl->getNext() != D) {
66 SomeDecl = SomeDecl->getNext();
67 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
68 }
69 SomeDecl->setNext(D->getNext());
70 }
71
72 // This will have to be revisited for C++: there we want to nest stuff in
73 // namespace decls etc. Even for C, we might want a top-level translation
74 // unit decl or something.
75 if (!CurFunctionDecl)
76 continue;
77
78 // Chain this decl to the containing function, it now owns the memory for
79 // the decl.
80 D->setNext(CurFunctionDecl->getDeclChain());
81 CurFunctionDecl->setDeclChain(D);
82 }
83}
84
85/// LookupScopedDecl - Look up the inner-most declaration in the specified
86/// namespace.
Steve Naroffd21bc0d2007-09-13 18:10:37 +000087ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
88 SourceLocation IdLoc, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +000089 if (II == 0) return 0;
90 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
91
92 // Scan up the scope chain looking for a decl that matches this identifier
93 // that is in the appropriate namespace. This search should not take long, as
94 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffd21bc0d2007-09-13 18:10:37 +000095 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner4b009652007-07-25 00:24:17 +000096 if (D->getIdentifierNamespace() == NS)
97 return D;
98
99 // If we didn't find a use of this identifier, and if the identifier
100 // corresponds to a compiler builtin, create the decl object for the builtin
101 // now, injecting it into translation unit scope, and return it.
102 if (NS == Decl::IDNS_Ordinary) {
103 // If this is a builtin on some other target, or if this builtin varies
104 // across targets (e.g. in type), emit a diagnostic and mark the translation
105 // unit non-portable for using it.
106 if (II->isNonPortableBuiltin()) {
107 // Only emit this diagnostic once for this builtin.
108 II->setNonPortableBuiltin(false);
109 Context.Target.DiagnoseNonPortability(IdLoc,
110 diag::port_target_builtin_use);
111 }
112 // If this is a builtin on this (or all) targets, create the decl.
113 if (unsigned BuiltinID = II->getBuiltinID())
114 return LazilyCreateBuiltin(II, BuiltinID, S);
115 }
116 return 0;
117}
118
119/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
120/// lazily create a decl for it.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000121ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000122 Builtin::ID BID = (Builtin::ID)bid;
123
124 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
125 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner987058a2007-08-26 04:02:13 +0000126 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000127
128 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000129 if (Scope *FnS = S->getFnParent())
130 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000131 while (S->getParent())
132 S = S->getParent();
133 S->AddDecl(New);
134
135 // Add this decl to the end of the identifier info.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000136 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000137 // Scan until we find the last (outermost) decl in the id chain.
138 while (LastDecl->getNext())
139 LastDecl = LastDecl->getNext();
140 // Insert before (outside) it.
141 LastDecl->setNext(New);
142 } else {
143 II->setFETokenInfo(New);
144 }
145 // Make sure clients iterating over decls see this.
146 LastInGroupList.push_back(New);
147
148 return New;
149}
150
151/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
152/// and scope as a previous declaration 'Old'. Figure out how to resolve this
153/// situation, merging decls or emitting diagnostics as appropriate.
154///
Steve Naroffcb597472007-09-13 21:41:19 +0000155TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000156 // Verify the old decl was also a typedef.
157 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
158 if (!Old) {
159 Diag(New->getLocation(), diag::err_redefinition_different_kind,
160 New->getName());
161 Diag(OldD->getLocation(), diag::err_previous_definition);
162 return New;
163 }
164
165 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
166 // TODO: This is totally simplistic. It should handle merging functions
167 // together etc, merging extern int X; int X; ...
168 Diag(New->getLocation(), diag::err_redefinition, New->getName());
169 Diag(Old->getLocation(), diag::err_previous_definition);
170 return New;
171}
172
173/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
174/// and scope as a previous declaration 'Old'. Figure out how to resolve this
175/// situation, merging decls or emitting diagnostics as appropriate.
176///
Steve Naroffcb597472007-09-13 21:41:19 +0000177FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000178 // Verify the old decl was also a function.
179 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
180 if (!Old) {
181 Diag(New->getLocation(), diag::err_redefinition_different_kind,
182 New->getName());
183 Diag(OldD->getLocation(), diag::err_previous_definition);
184 return New;
185 }
186
187 // This is not right, but it's a start. If 'Old' is a function prototype with
188 // the same type as 'New', silently allow this. FIXME: We should link up decl
189 // objects here.
190 if (Old->getBody() == 0 &&
191 Old->getCanonicalType() == New->getCanonicalType()) {
192 return New;
193 }
194
195 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
196 // TODO: This is totally simplistic. It should handle merging functions
197 // together etc, merging extern int X; int X; ...
198 Diag(New->getLocation(), diag::err_redefinition, New->getName());
199 Diag(Old->getLocation(), diag::err_previous_definition);
200 return New;
201}
202
203/// MergeVarDecl - We just parsed a variable 'New' which has the same name
204/// and scope as a previous declaration 'Old'. Figure out how to resolve this
205/// situation, merging decls or emitting diagnostics as appropriate.
206///
207/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
208/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
209///
Steve Naroffcb597472007-09-13 21:41:19 +0000210VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000211 // Verify the old decl was also a variable.
212 VarDecl *Old = dyn_cast<VarDecl>(OldD);
213 if (!Old) {
214 Diag(New->getLocation(), diag::err_redefinition_different_kind,
215 New->getName());
216 Diag(OldD->getLocation(), diag::err_previous_definition);
217 return New;
218 }
Steve Naroff83c13012007-08-30 01:06:46 +0000219 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
220 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
221 bool OldIsTentative = false;
222
223 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
224 // Handle C "tentative" external object definitions. FIXME: finish!
225 if (!OldFSDecl->getInit() &&
226 (OldFSDecl->getStorageClass() == VarDecl::None ||
227 OldFSDecl->getStorageClass() == VarDecl::Static))
228 OldIsTentative = true;
229 }
Chris Lattner4b009652007-07-25 00:24:17 +0000230 // Verify the types match.
231 if (Old->getCanonicalType() != New->getCanonicalType()) {
232 Diag(New->getLocation(), diag::err_redefinition, New->getName());
233 Diag(Old->getLocation(), diag::err_previous_definition);
234 return New;
235 }
236 // We've verified the types match, now check if Old is "extern".
237 if (Old->getStorageClass() != VarDecl::Extern) {
238 Diag(New->getLocation(), diag::err_redefinition, New->getName());
239 Diag(Old->getLocation(), diag::err_previous_definition);
240 }
241 return New;
242}
243
244/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
245/// no declarator (e.g. "struct foo;") is parsed.
246Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
247 // TODO: emit error on 'int;' or 'const enum foo;'.
248 // TODO: emit error on 'typedef int;'
249 // if (!DS.isMissingDeclaratorOk()) Diag(...);
250
251 return 0;
252}
253
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000254bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000255 AssignmentCheckResult result;
256 SourceLocation loc = Init->getLocStart();
257 // Get the type before calling CheckSingleAssignmentConstraints(), since
258 // it can promote the expression.
259 QualType rhsType = Init->getType();
260
261 result = CheckSingleAssignmentConstraints(DeclType, Init);
262
263 // decode the result (notice that extensions still return a type).
264 switch (result) {
265 case Compatible:
266 break;
267 case Incompatible:
Steve Naroff9091f3f2007-09-02 15:34:30 +0000268 // FIXME: tighten up this check which should allow:
269 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
270 if (rhsType == Context.getPointerType(Context.CharTy))
271 break;
Steve Naroffe14e5542007-09-02 02:04:30 +0000272 Diag(loc, diag::err_typecheck_assign_incompatible,
273 DeclType.getAsString(), rhsType.getAsString(),
274 Init->getSourceRange());
275 return true;
276 case PointerFromInt:
277 // check for null pointer constant (C99 6.3.2.3p3)
278 if (!Init->isNullPointerConstant(Context)) {
279 Diag(loc, diag::ext_typecheck_assign_pointer_int,
280 DeclType.getAsString(), rhsType.getAsString(),
281 Init->getSourceRange());
282 return true;
283 }
284 break;
285 case IntFromPointer:
286 Diag(loc, diag::ext_typecheck_assign_pointer_int,
287 DeclType.getAsString(), rhsType.getAsString(),
288 Init->getSourceRange());
289 break;
290 case IncompatiblePointer:
291 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
292 DeclType.getAsString(), rhsType.getAsString(),
293 Init->getSourceRange());
294 break;
295 case CompatiblePointerDiscardsQualifiers:
296 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
297 DeclType.getAsString(), rhsType.getAsString(),
298 Init->getSourceRange());
299 break;
300 }
301 return false;
302}
303
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000304bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
305 bool isStatic, QualType ElementType) {
Steve Naroff509d0b52007-09-04 02:20:04 +0000306 SourceLocation loc;
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000307 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff509d0b52007-09-04 02:20:04 +0000308
309 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
310 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
311 return true;
312 } else if (CheckSingleInitializer(expr, ElementType)) {
313 return true; // types weren't compatible.
314 }
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000315 if (savExpr != expr) // The type was promoted, update initializer list.
316 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000317 return false;
318}
319
320void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
321 QualType ElementType, bool isStatic,
322 int &nInitializers, bool &hadError) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000323 for (unsigned i = 0; i < IList->getNumInits(); i++) {
324 Expr *expr = IList->getInit(i);
325
Steve Naroff509d0b52007-09-04 02:20:04 +0000326 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
327 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000328 int maxElements = CAT->getMaximumElements();
Steve Naroff509d0b52007-09-04 02:20:04 +0000329 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
330 maxElements, hadError);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000331 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000332 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000333 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000334 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000335 nInitializers++;
336 }
337 return;
338}
339
340// FIXME: Doesn't deal with arrays of structures yet.
341void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
342 QualType ElementType, bool isStatic,
343 int &totalInits, bool &hadError) {
344 int maxElementsAtThisLevel = 0;
345 int nInitsAtLevel = 0;
346
347 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
348 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff4f910992007-09-04 21:13:33 +0000349 maxElementsAtThisLevel = CAT->getMaximumElements();
350 // Set DeclType, used below to recurse (for multi-dimensional arrays).
351 DeclType = CAT->getElementType();
Steve Naroff509d0b52007-09-04 02:20:04 +0000352 } else if (DeclType->isScalarType()) {
353 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
354 IList->getSourceRange());
355 maxElementsAtThisLevel = 1;
356 }
357 // The empty init list "{ }" is treated specially below.
358 unsigned numInits = IList->getNumInits();
359 if (numInits) {
360 for (unsigned i = 0; i < numInits; i++) {
361 Expr *expr = IList->getInit(i);
362
363 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
364 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
365 totalInits, hadError);
366 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000367 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff509d0b52007-09-04 02:20:04 +0000368 nInitsAtLevel++; // increment the number of initializers at this level.
369 totalInits--; // decrement the total number of initializers.
370
371 // Check if we have space for another initializer.
372 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
373 Diag(expr->getLocStart(), diag::warn_excess_initializers,
374 expr->getSourceRange());
375 }
376 }
377 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
378 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
379 } else {
380 // we have an initializer list with no elements.
381 totalInits -= maxElementsAtThisLevel;
382 if (totalInits < 0)
383 Diag(IList->getLocStart(), diag::warn_excess_initializers,
384 IList->getSourceRange());
Steve Naroff9091f3f2007-09-02 15:34:30 +0000385 }
Steve Naroff1c9de712007-09-03 01:24:23 +0000386 return;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000387}
388
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000389bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000390 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroff1c9de712007-09-03 01:24:23 +0000391 if (!InitList)
392 return CheckSingleInitializer(Init, DeclType);
393
Steve Naroffe14e5542007-09-02 02:04:30 +0000394 // We have an InitListExpr, make sure we set the type.
395 Init->setType(DeclType);
Steve Naroff1c9de712007-09-03 01:24:23 +0000396
397 bool hadError = false;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000398
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000399 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
400 // of unknown size ("[]") or an object type that is not a variable array type.
401 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
402 Expr *expr = VAT->getSizeExpr();
Steve Naroff1c9de712007-09-03 01:24:23 +0000403 if (expr)
404 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
405 expr->getSourceRange());
406
Steve Naroff4f910992007-09-04 21:13:33 +0000407 // We have a VariableArrayType with unknown size. Note that only the first
408 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff509d0b52007-09-04 02:20:04 +0000409 int numInits = 0;
Steve Naroff4f910992007-09-04 21:13:33 +0000410 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
411 isStatic, numInits, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000412 if (!hadError) {
413 // Return a new array type from the number of initializers (C99 6.7.8p22).
414 llvm::APSInt ConstVal(32);
Steve Naroff509d0b52007-09-04 02:20:04 +0000415 ConstVal = numInits;
416 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroff1c9de712007-09-03 01:24:23 +0000417 ArrayType::Normal, 0);
418 }
419 return hadError;
420 }
421 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000422 int maxElements = CAT->getMaximumElements();
423 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
424 isStatic, maxElements, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000425 return hadError;
426 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000427 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
428 int maxElements = 1;
429 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
430 hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000431 return hadError;
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000432 }
433 // FIXME: Handle struct/union types.
Steve Naroff1c9de712007-09-03 01:24:23 +0000434 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +0000435}
436
Chris Lattner4b009652007-07-25 00:24:17 +0000437Sema::DeclTy *
Steve Naroff0acc9c92007-09-15 18:49:24 +0000438Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000439 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000440 IdentifierInfo *II = D.getIdentifier();
441
442 // All of these full declarators require an identifier. If it doesn't have
443 // one, the ParsedFreeStandingDeclSpec action should be used.
444 if (II == 0) {
Chris Lattner87492f42007-08-28 06:17:15 +0000445 Diag(D.getDeclSpec().getSourceRange().Begin(),
446 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000447 D.getDeclSpec().getSourceRange(), D.getSourceRange());
448 return 0;
449 }
450
Chris Lattnera7549902007-08-26 06:24:45 +0000451 // The scope passed in may not be a decl scope. Zip up the scope tree until
452 // we find one that is.
453 while ((S->getFlags() & Scope::DeclScope) == 0)
454 S = S->getParent();
455
Chris Lattner4b009652007-07-25 00:24:17 +0000456 // See if this is a redefinition of a variable in the same scope.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000457 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
458 D.getIdentifierLoc(), S);
Chris Lattner4b009652007-07-25 00:24:17 +0000459 if (PrevDecl && !S->isDeclScope(PrevDecl))
460 PrevDecl = 0; // If in outer scope, it isn't the same thing.
461
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000462 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000463 bool InvalidDecl = false;
464
Chris Lattner4b009652007-07-25 00:24:17 +0000465 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner4b009652007-07-25 00:24:17 +0000466 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
467 if (!NewTD) return 0;
468
469 // Handle attributes prior to checking for duplicates in MergeVarDecl
470 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
471 D.getAttributes());
472 // Merge the decl with the existing one if appropriate.
473 if (PrevDecl) {
474 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
475 if (NewTD == 0) return 0;
476 }
477 New = NewTD;
478 if (S->getParent() == 0) {
479 // C99 6.7.7p2: If a typedef name specifies a variably modified type
480 // then it shall have block scope.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000481 if (const VariableArrayType *VAT =
482 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
483 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
484 VAT->getSizeExpr()->getSourceRange());
485 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000486 }
487 }
488 } else if (D.isFunctionDeclarator()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000489 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000490 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000491
492 FunctionDecl::StorageClass SC;
493 switch (D.getDeclSpec().getStorageClassSpec()) {
494 default: assert(0 && "Unknown storage class!");
495 case DeclSpec::SCS_auto:
496 case DeclSpec::SCS_register:
497 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
498 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000499 InvalidDecl = true;
500 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000501 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
502 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
503 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
504 }
505
506 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000507 D.getDeclSpec().isInlineSpecified(),
Chris Lattner4b009652007-07-25 00:24:17 +0000508 LastDeclarator);
509
510 // Merge the decl with the existing one if appropriate.
511 if (PrevDecl) {
512 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
513 if (NewFD == 0) return 0;
514 }
515 New = NewFD;
516 } else {
517 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffcae537d2007-08-28 18:45:29 +0000518 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000519
520 VarDecl *NewVD;
521 VarDecl::StorageClass SC;
522 switch (D.getDeclSpec().getStorageClassSpec()) {
523 default: assert(0 && "Unknown storage class!");
524 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
525 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
526 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
527 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
528 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
529 }
530 if (S->getParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000531 // C99 6.9p2: The storage-class specifiers auto and register shall not
532 // appear in the declaration specifiers in an external declaration.
533 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
534 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
535 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000536 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000537 }
Chris Lattner4b009652007-07-25 00:24:17 +0000538 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000539 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000540 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000541 }
Chris Lattner4b009652007-07-25 00:24:17 +0000542 // Handle attributes prior to checking for duplicates in MergeVarDecl
543 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
544 D.getAttributes());
545
546 // Merge the decl with the existing one if appropriate.
547 if (PrevDecl) {
548 NewVD = MergeVarDecl(NewVD, PrevDecl);
549 if (NewVD == 0) return 0;
550 }
Chris Lattner4b009652007-07-25 00:24:17 +0000551 New = NewVD;
552 }
553
554 // If this has an identifier, add it to the scope stack.
555 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000556 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000557 II->setFETokenInfo(New);
558 S->AddDecl(New);
559 }
560
561 if (S->getParent() == 0)
562 AddTopLevelDecl(New, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000563
564 // If any semantic error occurred, mark the decl as invalid.
565 if (D.getInvalidType() || InvalidDecl)
566 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000567
568 return New;
569}
570
Steve Naroff6a0e2092007-09-12 14:07:44 +0000571void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000572 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000573 Expr *Init = static_cast<Expr *>(init);
574
Steve Naroff420d0f52007-09-12 20:13:48 +0000575 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +0000576
Steve Naroff420d0f52007-09-12 20:13:48 +0000577 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
578 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +0000579 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
580 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +0000581 RealDecl->setInvalidDecl();
582 return;
583 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000584 // Get the decls type and save a reference for later, since
585 // CheckInitializer may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +0000586 QualType DclT = VDecl->getType(), SavT = DclT;
587 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000588 VarDecl::StorageClass SC = BVD->getStorageClass();
589 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +0000590 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000591 BVD->setInvalidDecl();
592 } else if (!BVD->isInvalidDecl()) {
593 CheckInitializer(Init, DclT, SC == VarDecl::Static);
594 }
Steve Naroff420d0f52007-09-12 20:13:48 +0000595 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000596 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +0000597 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000598 if (!FVD->isInvalidDecl())
599 CheckInitializer(Init, DclT, true);
600 }
601 // If the type changed, it means we had an incomplete type that was
602 // completed by the initializer. For example:
603 // int ary[] = { 1, 3, 5 };
604 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff420d0f52007-09-12 20:13:48 +0000605 if (!VDecl->isInvalidDecl() && (DclT != SavT))
606 VDecl->setType(DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000607
608 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +0000609 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000610 return;
611}
612
Chris Lattner4b009652007-07-25 00:24:17 +0000613/// The declarators are chained together backwards, reverse the list.
614Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
615 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000616 Decl *GroupDecl = static_cast<Decl*>(group);
617 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +0000618 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +0000619
620 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
621 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000622 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000623 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000624 else { // reverse the list.
625 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000626 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +0000627 Group->setNextDeclarator(NewGroup);
628 NewGroup = Group;
629 Group = Next;
630 }
631 }
632 // Perform semantic analysis that depends on having fully processed both
633 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000634 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000635 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
636 if (!IDecl)
637 continue;
638 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
639 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
640 QualType T = IDecl->getType();
641
642 // C99 6.7.5.2p2: If an identifier is declared to be an object with
643 // static storage duration, it shall not have a variable length array.
644 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
645 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
646 if (VLA->getSizeExpr()) {
647 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
648 IDecl->setInvalidDecl();
649 }
650 }
651 }
652 // Block scope. C99 6.7p7: If an identifier for an object is declared with
653 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
654 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
655 if (T->isIncompleteType()) {
656 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
657 T.getAsString());
658 IDecl->setInvalidDecl();
659 }
660 }
661 // File scope. C99 6.9.2p2: A declaration of an identifier for and
662 // object that has file scope without an initializer, and without a
663 // storage-class specifier or with the storage-class specifier "static",
664 // constitutes a tentative definition. Note: A tentative definition with
665 // external linkage is valid (C99 6.2.2p5).
666 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
667 // C99 6.9.2p3: If the declaration of an identifier for an object is
668 // a tentative definition and has internal linkage (C99 6.2.2p3), the
669 // declared type shall not be an incomplete type.
670 if (T->isIncompleteType()) {
671 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
672 T.getAsString());
673 IDecl->setInvalidDecl();
674 }
675 }
Chris Lattner4b009652007-07-25 00:24:17 +0000676 }
677 return NewGroup;
678}
Steve Naroff91b03f72007-08-28 03:03:08 +0000679
680// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000681ParmVarDecl *
682Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
683 Scope *FnScope) {
684 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
685
686 IdentifierInfo *II = PI.Ident;
687 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
688 // Can this happen for params? We already checked that they don't conflict
689 // among each other. Here they can only shadow globals, which is ok.
690 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
691 PI.IdentLoc, FnScope)) {
692
693 }
694
695 // FIXME: Handle storage class (auto, register). No declarator?
696 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000697
698 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
699 // Doing the promotion here has a win and a loss. The win is the type for
700 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
701 // code generator). The loss is the orginal type isn't preserved. For example:
702 //
703 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
704 // int blockvardecl[5];
705 // sizeof(parmvardecl); // size == 4
706 // sizeof(blockvardecl); // size == 20
707 // }
708 //
709 // For expressions, all implicit conversions are captured using the
710 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
711 //
712 // FIXME: If a source translation tool needs to see the original type, then
713 // we need to consider storing both types (in ParmVarDecl)...
714 //
715 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
716 if (const ArrayType *AT = parmDeclType->getAsArrayType())
717 parmDeclType = Context.getPointerType(AT->getElementType());
718 else if (parmDeclType->isFunctionType())
719 parmDeclType = Context.getPointerType(parmDeclType);
720
721 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffcae537d2007-08-28 18:45:29 +0000722 VarDecl::None, 0);
723 if (PI.InvalidType)
724 New->setInvalidDecl();
725
Chris Lattner4b009652007-07-25 00:24:17 +0000726 // If this has an identifier, add it to the scope stack.
727 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000728 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000729 II->setFETokenInfo(New);
730 FnScope->AddDecl(New);
731 }
732
733 return New;
734}
735
736
737Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
738 assert(CurFunctionDecl == 0 && "Function parsing confused");
739 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
740 "Not a function declarator!");
741 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
742
743 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
744 // for a K&R function.
745 if (!FTI.hasPrototype) {
746 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
747 if (FTI.ArgInfo[i].TypeInfo == 0) {
748 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
749 FTI.ArgInfo[i].Ident->getName());
750 // Implicitly declare the argument as type 'int' for lack of a better
751 // type.
752 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
753 }
754 }
755
756 // Since this is a function definition, act as though we have information
757 // about the arguments.
758 FTI.hasPrototype = true;
759 } else {
760 // FIXME: Diagnose arguments without names in C.
761
762 }
763
764 Scope *GlobalScope = FnBodyScope->getParent();
765
766 FunctionDecl *FD =
Steve Naroff0acc9c92007-09-15 18:49:24 +0000767 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattner4b009652007-07-25 00:24:17 +0000768 CurFunctionDecl = FD;
769
770 // Create Decl objects for each parameter, adding them to the FunctionDecl.
771 llvm::SmallVector<ParmVarDecl*, 16> Params;
772
773 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
774 // no arguments, not a function that takes a single void argument.
775 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
776 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
777 // empty arg list, don't push any params.
778 } else {
779 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
780 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
781 }
782
783 FD->setParams(&Params[0], Params.size());
784
785 return FD;
786}
787
788Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
789 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
790 FD->setBody((Stmt*)Body);
791
792 assert(FD == CurFunctionDecl && "Function parsing confused");
793 CurFunctionDecl = 0;
794
795 // Verify and clean out per-function state.
796
797 // Check goto/label use.
798 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
799 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
800 // Verify that we have no forward references left. If so, there was a goto
801 // or address of a label taken, but no definition of it. Label fwd
802 // definitions are indicated with a null substmt.
803 if (I->second->getSubStmt() == 0) {
804 LabelStmt *L = I->second;
805 // Emit error.
806 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
807
808 // At this point, we have gotos that use the bogus label. Stitch it into
809 // the function body so that they aren't leaked and that the AST is well
810 // formed.
811 L->setSubStmt(new NullStmt(L->getIdentLoc()));
812 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
813 }
814 }
815 LabelMap.clear();
816
817 return FD;
818}
819
820
821/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
822/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +0000823ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
824 IdentifierInfo &II, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000825 if (getLangOptions().C99) // Extension in C99.
826 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
827 else // Legal in C90, but warn about it.
828 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
829
830 // FIXME: handle stuff like:
831 // void foo() { extern float X(); }
832 // void bar() { X(); } <-- implicit decl for X in another scope.
833
834 // Set a Declarator for the implicit definition: int foo();
835 const char *Dummy;
836 DeclSpec DS;
837 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
838 Error = Error; // Silence warning.
839 assert(!Error && "Error setting up implicit decl!");
840 Declarator D(DS, Declarator::BlockContext);
841 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
842 D.SetIdentifier(&II, Loc);
843
844 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000845 if (Scope *FnS = S->getFnParent())
846 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000847 while (S->getParent())
848 S = S->getParent();
849
Steve Narofff0c31dd2007-09-16 16:16:00 +0000850 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattner4b009652007-07-25 00:24:17 +0000851}
852
853
854TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
Steve Naroff2591e1b2007-09-13 23:52:58 +0000855 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +0000856 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
857
858 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000859 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000860
861 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000862 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
863 T, LastDeclarator);
864 if (D.getInvalidType())
865 NewTD->setInvalidDecl();
866 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +0000867}
868
Steve Naroff81f1bba2007-09-06 21:24:23 +0000869Sema::DeclTy *Sema::ObjcStartClassInterface(SourceLocation AtInterfaceLoc,
870 IdentifierInfo *ClassName, SourceLocation ClassLoc,
871 IdentifierInfo *SuperName, SourceLocation SuperLoc,
872 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
873 AttributeList *AttrList) {
874 assert(ClassName && "Missing class identifier");
875 ObjcInterfaceDecl *IDecl;
876
877 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, ClassName);
878
879 // Chain & install the interface decl into the identifier.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000880 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
Steve Naroff81f1bba2007-09-06 21:24:23 +0000881 ClassName->setFETokenInfo(IDecl);
882 return IDecl;
883}
884
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +0000885Sema::DeclTy *Sema::ObjcStartProtoInterface(SourceLocation AtProtoInterfaceLoc,
886 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
887 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
888 assert(ProtocolName && "Missing protocol identifier");
889 ObjcProtocolDecl *PDecl;
890
891 PDecl = new ObjcProtocolDecl(AtProtoInterfaceLoc, ProtocolName);
892
893 // Chain & install the protocol decl into the identifier.
894 PDecl->setNext(ProtocolName->getFETokenInfo<ScopedDecl>());
895 ProtocolName->setFETokenInfo(PDecl);
896 return PDecl;
897}
898
Fariborz Jahanianf25220e2007-09-18 20:26:58 +0000899Sema::DeclTy *Sema::ObjcStartCatInterface(SourceLocation AtInterfaceLoc,
900 IdentifierInfo *ClassName, SourceLocation ClassLoc,
901 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
902 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
903 ObjcCategoryDecl *CDecl;
904 CDecl = new ObjcCategoryDecl(AtInterfaceLoc, ClassName);
905 assert (ClassName->getFETokenInfo<ScopedDecl>() && "Missing @interface decl");
906 Decl *D = static_cast<Decl *>(ClassName->getFETokenInfo<ScopedDecl>());
907 assert(isa<ObjcInterfaceDecl>(D) && "Missing @interface decl");
908
909 // Chain & install the category decl into the identifier.
910 // Note that head of the chain is the @interface class type and follow up
911 // nodes in the chain are the protocol decl nodes.
912 cast<ObjcInterfaceDecl>(D)->setNext(CDecl);
913 return CDecl;
914}
Steve Naroff81f1bba2007-09-06 21:24:23 +0000915/// ObjcClassDeclaration -
916/// Scope will always be top level file scope.
917Action::DeclTy *
918Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
919 IdentifierInfo **IdentList, unsigned NumElts) {
920 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
921
922 for (unsigned i = 0; i != NumElts; ++i) {
923 ObjcInterfaceDecl *IDecl;
924
Steve Narofffaed3bf2007-09-10 20:51:04 +0000925 // FIXME: before we create one, look up the interface decl in a hash table.
Steve Naroff81f1bba2007-09-06 21:24:23 +0000926 IDecl = new ObjcInterfaceDecl(SourceLocation(), IdentList[i], true);
927 // Chain & install the interface decl into the identifier.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000928 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
Steve Naroff81f1bba2007-09-06 21:24:23 +0000929 IdentList[i]->setFETokenInfo(IDecl);
930
931 // Remember that this needs to be removed when the scope is popped.
932 S->AddDecl(IdentList[i]);
933
934 CDecl->setInterfaceDecl((int)i, IDecl);
935 }
936 return CDecl;
937}
938
Chris Lattner4b009652007-07-25 00:24:17 +0000939
Steve Naroff0acc9c92007-09-15 18:49:24 +0000940/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +0000941/// former case, Name will be non-null. In the later case, Name will be null.
942/// TagType indicates what kind of tag this is. TK indicates whether this is a
943/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000944Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +0000945 SourceLocation KWLoc, IdentifierInfo *Name,
946 SourceLocation NameLoc, AttributeList *Attr) {
947 // If this is a use of an existing tag, it must have a name.
948 assert((Name != 0 || TK == TK_Definition) &&
949 "Nameless record must be a definition!");
950
951 Decl::Kind Kind;
952 switch (TagType) {
953 default: assert(0 && "Unknown tag type!");
954 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
955 case DeclSpec::TST_union: Kind = Decl::Union; break;
956//case DeclSpec::TST_class: Kind = Decl::Class; break;
957 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
958 }
959
960 // If this is a named struct, check to see if there was a previous forward
961 // declaration or definition.
962 if (TagDecl *PrevDecl =
963 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
964 NameLoc, S))) {
965
966 // If this is a use of a previous tag, or if the tag is already declared in
967 // the same scope (so that the definition/declaration completes or
968 // rementions the tag), reuse the decl.
969 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
970 // Make sure that this wasn't declared as an enum and now used as a struct
971 // or something similar.
972 if (PrevDecl->getKind() != Kind) {
973 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
974 Diag(PrevDecl->getLocation(), diag::err_previous_use);
975 }
976
977 // If this is a use or a forward declaration, we're good.
978 if (TK != TK_Definition)
979 return PrevDecl;
980
981 // Diagnose attempts to redefine a tag.
982 if (PrevDecl->isDefinition()) {
983 Diag(NameLoc, diag::err_redefinition, Name->getName());
984 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
985 // If this is a redefinition, recover by making this struct be
986 // anonymous, which will make any later references get the previous
987 // definition.
988 Name = 0;
989 } else {
990 // Okay, this is definition of a previously declared or referenced tag.
991 // Move the location of the decl to be the definition site.
992 PrevDecl->setLocation(NameLoc);
993 return PrevDecl;
994 }
995 }
996 // If we get here, this is a definition of a new struct type in a nested
997 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
998 // type.
999 }
1000
1001 // If there is an identifier, use the location of the identifier as the
1002 // location of the decl, otherwise use the location of the struct/union
1003 // keyword.
1004 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1005
1006 // Otherwise, if this is the first time we've seen this tag, create the decl.
1007 TagDecl *New;
1008 switch (Kind) {
1009 default: assert(0 && "Unknown tag kind!");
1010 case Decl::Enum:
1011 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1012 // enum X { A, B, C } D; D should chain to X.
1013 New = new EnumDecl(Loc, Name, 0);
1014 // If this is an undefined enum, warn.
1015 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1016 break;
1017 case Decl::Union:
1018 case Decl::Struct:
1019 case Decl::Class:
1020 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1021 // struct X { int A; } D; D should chain to X.
1022 New = new RecordDecl(Kind, Loc, Name, 0);
1023 break;
1024 }
1025
1026 // If this has an identifier, add it to the scope stack.
1027 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001028 // The scope passed in may not be a decl scope. Zip up the scope tree until
1029 // we find one that is.
1030 while ((S->getFlags() & Scope::DeclScope) == 0)
1031 S = S->getParent();
1032
1033 // Add it to the decl chain.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001034 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001035 Name->setFETokenInfo(New);
1036 S->AddDecl(New);
1037 }
1038
1039 return New;
1040}
1041
Steve Naroff0acc9c92007-09-15 18:49:24 +00001042/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001043/// to create a FieldDecl object for it.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001044Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001045 SourceLocation DeclStart,
1046 Declarator &D, ExprTy *BitfieldWidth) {
1047 IdentifierInfo *II = D.getIdentifier();
1048 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001049 SourceLocation Loc = DeclStart;
1050 if (II) Loc = D.getIdentifierLoc();
1051
1052 // FIXME: Unnamed fields can be handled in various different ways, for
1053 // example, unnamed unions inject all members into the struct namespace!
1054
1055
1056 if (BitWidth) {
1057 // TODO: Validate.
1058 //printf("WARNING: BITFIELDS IGNORED!\n");
1059
1060 // 6.7.2.1p3
1061 // 6.7.2.1p4
1062
1063 } else {
1064 // Not a bitfield.
1065
1066 // validate II.
1067
1068 }
1069
1070 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001071 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1072 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001073
Chris Lattner4b009652007-07-25 00:24:17 +00001074 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1075 // than a variably modified type.
Steve Naroff5eb879b2007-08-31 17:20:07 +00001076 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1077 Diag(Loc, diag::err_typecheck_illegal_vla,
1078 VAT->getSizeExpr()->getSourceRange());
1079 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001080 }
Chris Lattner4b009652007-07-25 00:24:17 +00001081 // FIXME: Chain fielddecls together.
Steve Naroff75494892007-09-11 21:17:26 +00001082 FieldDecl *NewFD;
1083
1084 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Naroffdc1ad762007-09-14 02:20:46 +00001085 NewFD = new FieldDecl(Loc, II, T);
Steve Naroff75494892007-09-11 21:17:26 +00001086 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl)))
Steve Naroffdc1ad762007-09-14 02:20:46 +00001087 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff75494892007-09-11 21:17:26 +00001088 else
Steve Naroff0acc9c92007-09-15 18:49:24 +00001089 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff75494892007-09-11 21:17:26 +00001090
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001091 if (D.getInvalidType() || InvalidDecl)
1092 NewFD->setInvalidDecl();
1093 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001094}
1095
Steve Naroffffeaa552007-09-14 23:09:53 +00001096static void ObjcSetIvarVisibility(ObjcIvarDecl *OIvar,
1097 tok::ObjCKeywordKind ivarVisibility) {
1098 assert(OIvar && "missing instance variable");
1099 switch (ivarVisibility) {
1100 case tok::objc_private:
1101 OIvar->setAccessControl(ObjcIvarDecl::Private);
1102 break;
1103 case tok::objc_public:
1104 OIvar->setAccessControl(ObjcIvarDecl::Public);
1105 break;
1106 case tok::objc_protected:
1107 OIvar->setAccessControl(ObjcIvarDecl::Protected);
1108 break;
1109 case tok::objc_package:
1110 OIvar->setAccessControl(ObjcIvarDecl::Package);
1111 break;
1112 default:
1113 OIvar->setAccessControl(ObjcIvarDecl::None);
1114 break;
1115 }
1116}
1117
Steve Naroff0acc9c92007-09-15 18:49:24 +00001118void Sema::ActOnFields(SourceLocation RecLoc, DeclTy *RecDecl,
1119 DeclTy **Fields, unsigned NumFields,
1120 tok::ObjCKeywordKind *visibility) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001121 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1122 assert(EnclosingDecl && "missing record or interface decl");
1123 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1124
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001125 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001126 // Diagnose code like:
1127 // struct S { struct S {} X; };
1128 // We discover this when we complete the outer S. Reject and ignore the
1129 // outer S.
1130 Diag(Record->getLocation(), diag::err_nested_redefinition,
1131 Record->getKindName());
1132 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001133 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001134 return;
1135 }
Chris Lattner4b009652007-07-25 00:24:17 +00001136 // Verify that all the fields are okay.
1137 unsigned NumNamedMembers = 0;
1138 llvm::SmallVector<FieldDecl*, 32> RecFields;
1139 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00001140
Chris Lattner4b009652007-07-25 00:24:17 +00001141 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001142
Steve Naroff9bb759f2007-09-14 22:20:54 +00001143 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1144 assert(FD && "missing field decl");
1145
1146 // Remember all fields.
1147 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00001148
1149 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001150 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +00001151
Steve Naroffffeaa552007-09-14 23:09:53 +00001152 // If we have visibility info, make sure the AST is set accordingly.
1153 if (visibility)
1154 ObjcSetIvarVisibility(dyn_cast<ObjcIvarDecl>(FD), visibility[i]);
1155
Chris Lattner4b009652007-07-25 00:24:17 +00001156 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001157 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001158 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00001159 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001160 FD->setInvalidDecl();
1161 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001162 continue;
1163 }
Chris Lattner4b009652007-07-25 00:24:17 +00001164 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1165 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001166 if (!Record) { // Incomplete ivar type is always an error.
1167 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001168 FD->setInvalidDecl();
1169 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001170 continue;
1171 }
Chris Lattner4b009652007-07-25 00:24:17 +00001172 if (i != NumFields-1 || // ... that the last member ...
1173 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001174 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001175 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001176 FD->setInvalidDecl();
1177 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001178 continue;
1179 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001180 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00001181 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1182 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001183 FD->setInvalidDecl();
1184 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001185 continue;
1186 }
Chris Lattner4b009652007-07-25 00:24:17 +00001187 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001188 if (Record)
1189 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001190 }
Chris Lattner4b009652007-07-25 00:24:17 +00001191 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1192 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001193 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001194 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1195 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001196 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner4b009652007-07-25 00:24:17 +00001197 Record->setHasFlexibleArrayMember(true);
1198 } else {
1199 // If this is a struct/class and this is not the last element, reject
1200 // it. Note that GCC supports variable sized arrays in the middle of
1201 // structures.
1202 if (i != NumFields-1) {
1203 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1204 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001205 FD->setInvalidDecl();
1206 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001207 continue;
1208 }
Chris Lattner4b009652007-07-25 00:24:17 +00001209 // We support flexible arrays at the end of structs in other structs
1210 // as an extension.
1211 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1212 FD->getName());
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001213 if (Record)
1214 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001215 }
1216 }
1217 }
Chris Lattner4b009652007-07-25 00:24:17 +00001218 // Keep track of the number of named members.
1219 if (IdentifierInfo *II = FD->getIdentifier()) {
1220 // Detect duplicate member names.
1221 if (!FieldIDs.insert(II)) {
1222 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1223 // Find the previous decl.
1224 SourceLocation PrevLoc;
1225 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1226 assert(i != e && "Didn't find previous def!");
1227 if (RecFields[i]->getIdentifier() == II) {
1228 PrevLoc = RecFields[i]->getLocation();
1229 break;
1230 }
1231 }
1232 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001233 FD->setInvalidDecl();
1234 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001235 continue;
1236 }
1237 ++NumNamedMembers;
1238 }
Chris Lattner4b009652007-07-25 00:24:17 +00001239 }
1240
Chris Lattner4b009652007-07-25 00:24:17 +00001241 // Okay, we successfully defined 'Record'.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001242 if (Record)
1243 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001244 else {
1245 ObjcIvarDecl **ClsFields =
1246 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
1247 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1248 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1249 }
Chris Lattner4b009652007-07-25 00:24:17 +00001250}
1251
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001252void Sema::ObjcAddMethodsToClass(DeclTy *ClassDecl,
1253 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001254 // FIXME: Fix this when we can handle methods declared in protocols.
1255 // See Parser::ParseObjCAtProtocolDeclaration
1256 if (!ClassDecl)
1257 return;
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001258 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1259 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1260
1261 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001262 ObjcMethodDecl *Method =
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001263 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1264 if (!Method) continue; // Already issued a diagnostic.
1265 if (Method->isInstance())
1266 insMethods.push_back(Method);
1267 else
1268 clsMethods.push_back(Method);
1269 }
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001270 if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(ClassDecl))) {
1271 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1272 static_cast<Decl*>(ClassDecl));
1273 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1274 &clsMethods[0], clsMethods.size());
1275 }
1276 else if (isa<ObjcProtocolDecl>(static_cast<Decl *>(ClassDecl))) {
1277 ObjcProtocolDecl *Protocol = cast<ObjcProtocolDecl>(
1278 static_cast<Decl*>(ClassDecl));
1279 Protocol->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1280 &clsMethods[0], clsMethods.size());
1281 }
Fariborz Jahanianf25220e2007-09-18 20:26:58 +00001282 else if (isa<ObjcCategoryDecl>(static_cast<Decl *>(ClassDecl))) {
1283 ObjcCategoryDecl *Category = cast<ObjcCategoryDecl>(
1284 static_cast<Decl*>(ClassDecl));
1285 Category->ObjcAddCatMethods(&insMethods[0], insMethods.size(),
1286 &clsMethods[0], clsMethods.size());
1287 }
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001288 else
1289 assert(0 && "Sema::ObjcAddMethodsToClass(): Unknown DeclTy");
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001290 return;
1291}
1292
Fariborz Jahanian8b5ab6f2007-09-18 00:25:23 +00001293Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
Steve Naroff253118b2007-09-17 20:25:27 +00001294 tok::TokenKind MethodType, TypeTy *ReturnType,
1295 ObjcKeywordDecl *Keywords, unsigned NumKeywords,
Fariborz Jahanian8b5ab6f2007-09-18 00:25:23 +00001296 AttributeList *AttrList,
1297 tok::ObjCKeywordKind MethodDeclKind) {
Steve Naroff253118b2007-09-17 20:25:27 +00001298 assert(NumKeywords && "Selector must be specified");
1299
1300 // Derive the selector name from the keyword declarations.
Steve Naroff948fd372007-09-17 14:16:13 +00001301 int len=0;
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 }
Steve Naroffc39ca262007-09-18 23:55:05 +00001307 llvm::SmallString<128> methodName;
Steve Naroff948fd372007-09-17 14:16:13 +00001308 methodName[0] = '\0';
Steve Naroff253118b2007-09-17 20:25:27 +00001309 for (unsigned int i = 0; i < NumKeywords; i++) {
1310 if (Keywords[i].SelectorName)
Steve Naroffc39ca262007-09-18 23:55:05 +00001311 methodName += Keywords[i].SelectorName->getName();
1312 methodName += ":";
Steve Naroff948fd372007-09-17 14:16:13 +00001313 }
Steve Naroffc39ca262007-09-18 23:55:05 +00001314 methodName[len] = '\0';
1315 SelectorInfo &SelName = Context.getSelectorInfo(&methodName[0],
1316 &methodName[0]+len);
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001317 llvm::SmallVector<ParmVarDecl*, 16> Params;
1318
1319 for (unsigned i = 0; i < NumKeywords; i++) {
Steve Naroff253118b2007-09-17 20:25:27 +00001320 ObjcKeywordDecl *arg = &Keywords[i];
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001321 // FIXME: arg->AttrList must be stored too!
1322 ParmVarDecl* Param = new ParmVarDecl(arg->ColonLoc, arg->ArgumentName,
1323 QualType::getFromOpaquePtr(arg->TypeInfo),
1324 VarDecl::None, 0);
1325 // FIXME: 'InvalidType' does not get set by caller yet.
1326 if (arg->InvalidType)
1327 Param->setInvalidDecl();
1328 Params.push_back(Param);
1329 }
1330 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Fariborz Jahanian4a2b0ac2007-09-17 22:36:42 +00001331 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc,
1332 SelName, resultDeclType,
1333 0, -1, AttrList, MethodType == tok::minus);
1334 ObjcMethod->setMethodParams(&Params[0], NumKeywords);
Fariborz Jahanian8b5ab6f2007-09-18 00:25:23 +00001335 if (MethodDeclKind == tok::objc_optional)
Steve Naroffc39ca262007-09-18 23:55:05 +00001336 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Optional);
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001337 else
Steve Naroffc39ca262007-09-18 23:55:05 +00001338 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Required);
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001339 return ObjcMethod;
1340}
1341
Fariborz Jahanian8b5ab6f2007-09-18 00:25:23 +00001342Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001343 tok::TokenKind MethodType, TypeTy *ReturnType,
Fariborz Jahanian8b5ab6f2007-09-18 00:25:23 +00001344 IdentifierInfo *SelectorName, AttributeList *AttrList,
1345 tok::ObjCKeywordKind MethodDeclKind) {
Steve Naroff948fd372007-09-17 14:16:13 +00001346 const char *methodName = SelectorName->getName();
1347 SelectorInfo &SelName = Context.getSelectorInfo(methodName,
1348 methodName+strlen(methodName));
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001349 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Fariborz Jahanian4a2b0ac2007-09-17 22:36:42 +00001350 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc,
1351 SelName, resultDeclType, 0, -1,
1352 AttrList, MethodType == tok::minus);
Fariborz Jahanian8b5ab6f2007-09-18 00:25:23 +00001353 if (MethodDeclKind == tok::objc_optional)
Steve Naroffc39ca262007-09-18 23:55:05 +00001354 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Optional);
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001355 else
Steve Naroffc39ca262007-09-18 23:55:05 +00001356 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Required);
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001357 return ObjcMethod;
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001358}
1359
Steve Naroff0acc9c92007-09-15 18:49:24 +00001360Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001361 DeclTy *lastEnumConst,
1362 SourceLocation IdLoc, IdentifierInfo *Id,
1363 SourceLocation EqualLoc, ExprTy *val) {
1364 theEnumDecl = theEnumDecl; // silence unused warning.
1365 EnumConstantDecl *LastEnumConst =
1366 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1367 Expr *Val = static_cast<Expr*>(val);
1368
Chris Lattnera7549902007-08-26 06:24:45 +00001369 // The scope passed in may not be a decl scope. Zip up the scope tree until
1370 // we find one that is.
1371 while ((S->getFlags() & Scope::DeclScope) == 0)
1372 S = S->getParent();
1373
Chris Lattner4b009652007-07-25 00:24:17 +00001374 // Verify that there isn't already something declared with this name in this
1375 // scope.
Steve Naroffcb597472007-09-13 21:41:19 +00001376 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1377 IdLoc, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001378 if (S->isDeclScope(PrevDecl)) {
1379 if (isa<EnumConstantDecl>(PrevDecl))
1380 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1381 else
1382 Diag(IdLoc, diag::err_redefinition, Id->getName());
1383 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1384 // FIXME: Don't leak memory: delete Val;
1385 return 0;
1386 }
1387 }
1388
1389 llvm::APSInt EnumVal(32);
1390 QualType EltTy;
1391 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001392 // Make sure to promote the operand type to int.
1393 UsualUnaryConversions(Val);
1394
Chris Lattner4b009652007-07-25 00:24:17 +00001395 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1396 SourceLocation ExpLoc;
1397 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1398 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1399 Id->getName());
1400 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001401 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001402 } else {
1403 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001404 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001405 }
1406
1407 if (!Val) {
1408 if (LastEnumConst) {
1409 // Assign the last value + 1.
1410 EnumVal = LastEnumConst->getInitVal();
1411 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001412
1413 // Check for overflow on increment.
1414 if (EnumVal < LastEnumConst->getInitVal())
1415 Diag(IdLoc, diag::warn_enum_value_overflow);
1416
Chris Lattnere7f53a42007-08-27 17:37:24 +00001417 EltTy = LastEnumConst->getType();
1418 } else {
1419 // First value, set to zero.
1420 EltTy = Context.IntTy;
Chris Lattner3496d522007-09-04 02:45:27 +00001421 EnumVal.zextOrTrunc(
1422 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001423 }
Chris Lattner4b009652007-07-25 00:24:17 +00001424 }
1425
Chris Lattner4b009652007-07-25 00:24:17 +00001426 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1427 LastEnumConst);
1428
1429 // Register this decl in the current scope stack.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001430 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001431 Id->setFETokenInfo(New);
1432 S->AddDecl(New);
1433 return New;
1434}
1435
Steve Naroff0acc9c92007-09-15 18:49:24 +00001436void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00001437 DeclTy **Elements, unsigned NumElements) {
1438 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1439 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1440
Chris Lattner435c3fd2007-08-28 05:10:31 +00001441 // TODO: If the result value doesn't fit in an int, it must be a long or long
1442 // long value. ISO C does not support this, but GCC does as an extension,
1443 // emit a warning.
Chris Lattner206754a2007-08-28 06:15:15 +00001444 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner435c3fd2007-08-28 05:10:31 +00001445
1446
Chris Lattner206754a2007-08-28 06:15:15 +00001447 // Verify that all the values are okay, compute the size of the values, and
1448 // reverse the list.
1449 unsigned NumNegativeBits = 0;
1450 unsigned NumPositiveBits = 0;
1451
1452 // Keep track of whether all elements have type int.
1453 bool AllElementsInt = true;
1454
Chris Lattner4b009652007-07-25 00:24:17 +00001455 EnumConstantDecl *EltList = 0;
1456 for (unsigned i = 0; i != NumElements; ++i) {
1457 EnumConstantDecl *ECD =
1458 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1459 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001460
1461 // If the enum value doesn't fit in an int, emit an extension warning.
1462 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1463 "Should have promoted value to int");
1464 const llvm::APSInt &InitVal = ECD->getInitVal();
1465 if (InitVal.getBitWidth() > IntWidth) {
1466 llvm::APSInt V(InitVal);
1467 V.trunc(IntWidth);
1468 V.extend(InitVal.getBitWidth());
1469 if (V != InitVal)
1470 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1471 InitVal.toString());
1472 }
Chris Lattner206754a2007-08-28 06:15:15 +00001473
1474 // Keep track of the size of positive and negative values.
1475 if (InitVal.isUnsigned() || !InitVal.isNegative())
1476 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1477 else
1478 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001479
Chris Lattner206754a2007-08-28 06:15:15 +00001480 // Keep track of whether every enum element has type int (very commmon).
1481 if (AllElementsInt)
1482 AllElementsInt = ECD->getType() == Context.IntTy;
1483
Chris Lattner4b009652007-07-25 00:24:17 +00001484 ECD->setNextDeclarator(EltList);
1485 EltList = ECD;
1486 }
1487
Chris Lattner206754a2007-08-28 06:15:15 +00001488 // Figure out the type that should be used for this enum.
1489 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1490 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001491 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001492
1493 if (NumNegativeBits) {
1494 // If there is a negative value, figure out the smallest integer type (of
1495 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001496 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001497 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001498 BestWidth = IntWidth;
1499 } else {
1500 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1501 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001502 BestType = Context.LongTy;
1503 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001504 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1505 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001506 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1507 BestType = Context.LongLongTy;
1508 }
1509 }
1510 } else {
1511 // If there is no negative value, figure out which of uint, ulong, ulonglong
1512 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001513 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001514 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001515 BestWidth = IntWidth;
1516 } else if (NumPositiveBits <=
1517 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattner206754a2007-08-28 06:15:15 +00001518 BestType = Context.UnsignedLongTy;
1519 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001520 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1521 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001522 "How could an initializer get larger than ULL?");
1523 BestType = Context.UnsignedLongLongTy;
1524 }
1525 }
1526
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001527 // Loop over all of the enumerator constants, changing their types to match
1528 // the type of the enum if needed.
1529 for (unsigned i = 0; i != NumElements; ++i) {
1530 EnumConstantDecl *ECD =
1531 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1532 if (!ECD) continue; // Already issued a diagnostic.
1533
1534 // Standard C says the enumerators have int type, but we allow, as an
1535 // extension, the enumerators to be larger than int size. If each
1536 // enumerator value fits in an int, type it as an int, otherwise type it the
1537 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1538 // that X has type 'int', not 'unsigned'.
1539 if (ECD->getType() == Context.IntTy)
1540 continue; // Already int type.
1541
1542 // Determine whether the value fits into an int.
1543 llvm::APSInt InitVal = ECD->getInitVal();
1544 bool FitsInInt;
1545 if (InitVal.isUnsigned() || !InitVal.isNegative())
1546 FitsInInt = InitVal.getActiveBits() < IntWidth;
1547 else
1548 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1549
1550 // If it fits into an integer type, force it. Otherwise force it to match
1551 // the enum decl type.
1552 QualType NewTy;
1553 unsigned NewWidth;
1554 bool NewSign;
1555 if (FitsInInt) {
1556 NewTy = Context.IntTy;
1557 NewWidth = IntWidth;
1558 NewSign = true;
1559 } else if (ECD->getType() == BestType) {
1560 // Already the right type!
1561 continue;
1562 } else {
1563 NewTy = BestType;
1564 NewWidth = BestWidth;
1565 NewSign = BestType->isSignedIntegerType();
1566 }
1567
1568 // Adjust the APSInt value.
1569 InitVal.extOrTrunc(NewWidth);
1570 InitVal.setIsSigned(NewSign);
1571 ECD->setInitVal(InitVal);
1572
1573 // Adjust the Expr initializer and type.
1574 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1575 ECD->setType(NewTy);
1576 }
Chris Lattner206754a2007-08-28 06:15:15 +00001577
Chris Lattner90a018d2007-08-28 18:24:31 +00001578 Enum->defineElements(EltList, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00001579}
1580
1581void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1582 if (!current) return;
1583
1584 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1585 // remember this in the LastInGroupList list.
1586 if (last)
1587 LastInGroupList.push_back((Decl*)last);
1588}
1589
1590void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1591 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1592 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1593 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1594 if (!newType.isNull()) // install the new vector type into the decl
1595 vDecl->setType(newType);
1596 }
1597 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1598 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1599 rawAttr);
1600 if (!newType.isNull()) // install the new vector type into the decl
1601 tDecl->setUnderlyingType(newType);
1602 }
1603 }
1604 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroff82113e32007-07-29 16:33:31 +00001605 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1606 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1607 else
Chris Lattner4b009652007-07-25 00:24:17 +00001608 Diag(rawAttr->getAttributeLoc(),
1609 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner4b009652007-07-25 00:24:17 +00001610 }
1611 // FIXME: add other attributes...
1612}
1613
1614void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1615 AttributeList *declarator_postfix) {
1616 while (declspec_prefix) {
1617 HandleDeclAttribute(New, declspec_prefix);
1618 declspec_prefix = declspec_prefix->getNext();
1619 }
1620 while (declarator_postfix) {
1621 HandleDeclAttribute(New, declarator_postfix);
1622 declarator_postfix = declarator_postfix->getNext();
1623 }
1624}
1625
Steve Naroff82113e32007-07-29 16:33:31 +00001626void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1627 AttributeList *rawAttr) {
1628 QualType curType = tDecl->getUnderlyingType();
Chris Lattner4b009652007-07-25 00:24:17 +00001629 // check the attribute arugments.
1630 if (rawAttr->getNumArgs() != 1) {
1631 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1632 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001633 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001634 }
1635 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1636 llvm::APSInt vecSize(32);
1637 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1638 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1639 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001640 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001641 }
1642 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1643 // in conjunction with complex types (pointers, arrays, functions, etc.).
1644 Type *canonType = curType.getCanonicalType().getTypePtr();
1645 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1646 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1647 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001648 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001649 }
1650 // unlike gcc's vector_size attribute, the size is specified as the
1651 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00001652 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00001653
1654 if (vectorSize == 0) {
1655 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1656 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001657 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001658 }
Steve Naroff82113e32007-07-29 16:33:31 +00001659 // Instantiate/Install the vector type, the number of elements is > 0.
1660 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1661 // Remember this typedef decl, we will need it later for diagnostics.
1662 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001663}
1664
1665QualType Sema::HandleVectorTypeAttribute(QualType curType,
1666 AttributeList *rawAttr) {
1667 // check the attribute arugments.
1668 if (rawAttr->getNumArgs() != 1) {
1669 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1670 std::string("1"));
1671 return QualType();
1672 }
1673 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1674 llvm::APSInt vecSize(32);
1675 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1676 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1677 sizeExpr->getSourceRange());
1678 return QualType();
1679 }
1680 // navigate to the base type - we need to provide for vector pointers,
1681 // vector arrays, and functions returning vectors.
1682 Type *canonType = curType.getCanonicalType().getTypePtr();
1683
1684 if (canonType->isPointerType() || canonType->isArrayType() ||
1685 canonType->isFunctionType()) {
1686 assert(1 && "HandleVector(): Complex type construction unimplemented");
1687 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1688 do {
1689 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1690 canonType = PT->getPointeeType().getTypePtr();
1691 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1692 canonType = AT->getElementType().getTypePtr();
1693 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1694 canonType = FT->getResultType().getTypePtr();
1695 } while (canonType->isPointerType() || canonType->isArrayType() ||
1696 canonType->isFunctionType());
1697 */
1698 }
1699 // the base type must be integer or float.
1700 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1701 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1702 curType.getCanonicalType().getAsString());
1703 return QualType();
1704 }
Chris Lattner3496d522007-09-04 02:45:27 +00001705 unsigned typeSize = static_cast<unsigned>(
1706 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Chris Lattner4b009652007-07-25 00:24:17 +00001707 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00001708 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00001709
1710 // the vector size needs to be an integral multiple of the type size.
1711 if (vectorSize % typeSize) {
1712 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1713 sizeExpr->getSourceRange());
1714 return QualType();
1715 }
1716 if (vectorSize == 0) {
1717 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1718 sizeExpr->getSourceRange());
1719 return QualType();
1720 }
1721 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1722 // the number of elements to be a power of two (unlike GCC).
1723 // Instantiate the vector type, the number of elements is > 0.
1724 return Context.getVectorType(curType, vectorSize/typeSize);
1725}
1726