blob: d1ce0b4eda97e950a350ce6beeb97481d2441a8a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kaiser2f94f3c2007-09-18 12:16:59 +000025#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "llvm/ADT/SmallSet.h"
Hartmut Kaiser2f94f3c2007-09-18 12:16:59 +000027#if !defined(LLVM_ON_WIN32)
Gabor Greif7ffc9ed2007-09-18 11:01:25 +000028#include <alloca.h>
Hartmut Kaiser2f94f3c2007-09-18 12:16:59 +000029#endif
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31
Reid Spencer5f016e22007-07-11 17:01:13 +000032Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Steve Naroff3536b442007-09-06 21:24:23 +000033 Decl *IIDecl = II.getFETokenInfo<Decl>();
34 if (dyn_cast_or_null<TypedefDecl>(IIDecl) ||
Fariborz Jahanian25e077d2007-09-17 21:07:36 +000035 dyn_cast_or_null<ObjcInterfaceDecl>(IIDecl) ||
36 dyn_cast_or_null<ObjcProtocolDecl>(IIDecl))
Steve Naroff3536b442007-09-06 21:24:23 +000037 return IIDecl;
38 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000039}
40
41void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000042 if (S->decl_empty()) return;
43 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
44
Reid Spencer5f016e22007-07-11 17:01:13 +000045 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
46 I != E; ++I) {
Steve Naroffc752d042007-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
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroffc752d042007-09-13 18:10:37 +000064 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroffc752d042007-09-13 18:10:37 +000087ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
88 SourceLocation IdLoc, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroffc752d042007-09-13 18:10:37 +000095 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroffc752d042007-09-13 18:10:37 +0000121ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner70c8b2e2007-08-26 04:02:13 +0000126 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000127
128 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000129 if (Scope *FnS = S->getFnParent())
130 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroffc752d042007-09-13 18:10:37 +0000136 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff8e74c932007-09-13 21:41:19 +0000155TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff8e74c932007-09-13 21:41:19 +0000177FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff8e74c932007-09-13 21:41:19 +0000210VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofffb22d962007-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 }
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff9e8925e2007-09-04 14:36:54 +0000254bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-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 Naroff6f9f3072007-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 Narofff0090632007-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 Naroff9e8925e2007-09-04 14:36:54 +0000304bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
305 bool isStatic, QualType ElementType) {
Steve Naroff371227d2007-09-04 02:20:04 +0000306 SourceLocation loc;
Steve Naroff9e8925e2007-09-04 14:36:54 +0000307 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff371227d2007-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 Naroff9e8925e2007-09-04 14:36:54 +0000315 if (savExpr != expr) // The type was promoted, update initializer list.
316 IList->setInit(slot, expr);
Steve Naroff371227d2007-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 Naroff6f9f3072007-09-02 15:34:30 +0000323 for (unsigned i = 0; i < IList->getNumInits(); i++) {
324 Expr *expr = IList->getInit(i);
325
Steve Naroff371227d2007-09-04 02:20:04 +0000326 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
327 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000328 int maxElements = CAT->getMaximumElements();
Steve Naroff371227d2007-09-04 02:20:04 +0000329 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
330 maxElements, hadError);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000331 }
Steve Naroff371227d2007-09-04 02:20:04 +0000332 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000333 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000334 }
Steve Naroff371227d2007-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 Naroff7cf8c442007-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 Naroff371227d2007-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 Naroff9e8925e2007-09-04 14:36:54 +0000367 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff371227d2007-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 Naroff6f9f3072007-09-02 15:34:30 +0000385 }
Steve Naroffd35005e2007-09-03 01:24:23 +0000386 return;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000387}
388
Steve Naroff9e8925e2007-09-04 14:36:54 +0000389bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Narofff0090632007-09-02 02:04:30 +0000390 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroffd35005e2007-09-03 01:24:23 +0000391 if (!InitList)
392 return CheckSingleInitializer(Init, DeclType);
393
Steve Narofff0090632007-09-02 02:04:30 +0000394 // We have an InitListExpr, make sure we set the type.
395 Init->setType(DeclType);
Steve Naroffd35005e2007-09-03 01:24:23 +0000396
397 bool hadError = false;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000398
Steve Naroff38374b02007-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 Naroffd35005e2007-09-03 01:24:23 +0000403 if (expr)
404 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
405 expr->getSourceRange());
406
Steve Naroff7cf8c442007-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 Naroff371227d2007-09-04 02:20:04 +0000409 int numInits = 0;
Steve Naroff7cf8c442007-09-04 21:13:33 +0000410 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
411 isStatic, numInits, hadError);
Steve Naroffd35005e2007-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 Naroff371227d2007-09-04 02:20:04 +0000415 ConstVal = numInits;
416 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroffd35005e2007-09-03 01:24:23 +0000417 ArrayType::Normal, 0);
418 }
419 return hadError;
420 }
421 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000422 int maxElements = CAT->getMaximumElements();
423 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
424 isStatic, maxElements, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000425 return hadError;
426 }
Steve Naroff371227d2007-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 Naroffd35005e2007-09-03 01:24:23 +0000431 return hadError;
Steve Naroff38374b02007-09-02 20:30:18 +0000432 }
433 // FIXME: Handle struct/union types.
Steve Naroffd35005e2007-09-03 01:24:23 +0000434 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +0000435}
436
Reid Spencer5f016e22007-07-11 17:01:13 +0000437Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000438Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000439 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000440 IdentifierInfo *II = D.getIdentifier();
441
Chris Lattnere80a59c2007-07-25 00:24:17 +0000442 // 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 Lattner98e08632007-08-28 06:17:15 +0000445 Diag(D.getDeclSpec().getSourceRange().Begin(),
446 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000447 D.getDeclSpec().getSourceRange(), D.getSourceRange());
448 return 0;
449 }
450
Chris Lattner31e05722007-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
Reid Spencer5f016e22007-07-11 17:01:13 +0000456 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000457 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
458 D.getIdentifierLoc(), S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 if (PrevDecl && !S->isDeclScope(PrevDecl))
460 PrevDecl = 0; // If in outer scope, it isn't the same thing.
461
Steve Naroffc752d042007-09-13 18:10:37 +0000462 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000463 bool InvalidDecl = false;
464
Reid Spencer5f016e22007-07-11 17:01:13 +0000465 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
466 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 Naroffd7444aa2007-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;
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 }
487 }
488 } else if (D.isFunctionDeclarator()) {
489 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000490 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000491
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 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 Naroff5912a352007-08-28 20:14:24 +0000499 InvalidDecl = true;
500 break;
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner70c8b2e2007-08-26 04:02:13 +0000507 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff53a32342007-08-28 18:45:29 +0000518 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +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) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff53a32342007-08-28 18:45:29 +0000536 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000537 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000538 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000539 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000540 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000541 }
Reid Spencer5f016e22007-07-11 17:01:13 +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 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000551 New = NewVD;
552 }
553
554 // If this has an identifier, add it to the scope stack.
555 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000556 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000557 II->setFETokenInfo(New);
558 S->AddDecl(New);
559 }
560
561 if (S->getParent() == 0)
562 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-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();
Reid Spencer5f016e22007-07-11 17:01:13 +0000567
568 return New;
569}
570
Steve Naroffbb204692007-09-12 14:07:44 +0000571void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000572 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000573 Expr *Init = static_cast<Expr *>(init);
574
Steve Naroff410e3e22007-09-12 20:13:48 +0000575 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000576
Steve Naroff410e3e22007-09-12 20:13:48 +0000577 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
578 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000579 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
580 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000581 RealDecl->setInvalidDecl();
582 return;
583 }
Steve Naroffbb204692007-09-12 14:07:44 +0000584 // Get the decls type and save a reference for later, since
585 // CheckInitializer may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000586 QualType DclT = VDecl->getType(), SavT = DclT;
587 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000588 VarDecl::StorageClass SC = BVD->getStorageClass();
589 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000590 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000591 BVD->setInvalidDecl();
592 } else if (!BVD->isInvalidDecl()) {
593 CheckInitializer(Init, DclT, SC == VarDecl::Static);
594 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000595 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000596 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000597 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-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 Naroff410e3e22007-09-12 20:13:48 +0000605 if (!VDecl->isInvalidDecl() && (DclT != SavT))
606 VDecl->setType(DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000607
608 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000609 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000610 return;
611}
612
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff94745042007-09-13 23:52:58 +0000616 Decl *GroupDecl = static_cast<Decl*>(group);
617 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000618 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000619
620 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
621 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000622 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000623 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000624 else { // reverse the list.
625 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000626 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-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 Naroff94745042007-09-13 23:52:58 +0000634 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-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 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000676 }
677 return NewGroup;
678}
Steve Naroffe1223f72007-08-28 03:03:08 +0000679
680// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +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.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000690 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000691 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 Naroff6a9f3e32007-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 Naroff53a32342007-08-28 18:45:29 +0000722 VarDecl::None, 0);
723 if (PI.InvalidType)
724 New->setInvalidDecl();
725
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 // If this has an identifier, add it to the scope stack.
727 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000728 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff08d92e42007-09-15 18:49:24 +0000767 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff8c9f13e2007-09-16 16:16:00 +0000823ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
824 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner31e05722007-08-26 06:24:45 +0000845 if (Scope *FnS = S->getFnParent())
846 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000847 while (S->getParent())
848 S = S->getParent();
849
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000850 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +0000851}
852
853
854TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
Steve Naroff94745042007-09-13 23:52:58 +0000855 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000856 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
857
858 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000859 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000860
861 // Scope manipulation handled by caller.
Steve Naroff5912a352007-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;
Reid Spencer5f016e22007-07-11 17:01:13 +0000867}
868
Steve Naroff3536b442007-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 Naroffc752d042007-09-13 18:10:37 +0000880 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
Steve Naroff3536b442007-09-06 21:24:23 +0000881 ClassName->setFETokenInfo(IDecl);
882 return IDecl;
883}
884
Fariborz Jahanian25e077d2007-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
Steve Naroff3536b442007-09-06 21:24:23 +0000899/// ObjcClassDeclaration -
900/// Scope will always be top level file scope.
901Action::DeclTy *
902Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
903 IdentifierInfo **IdentList, unsigned NumElts) {
904 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
905
906 for (unsigned i = 0; i != NumElts; ++i) {
907 ObjcInterfaceDecl *IDecl;
908
Steve Naroff2bd42fa2007-09-10 20:51:04 +0000909 // FIXME: before we create one, look up the interface decl in a hash table.
Steve Naroff3536b442007-09-06 21:24:23 +0000910 IDecl = new ObjcInterfaceDecl(SourceLocation(), IdentList[i], true);
911 // Chain & install the interface decl into the identifier.
Steve Naroffc752d042007-09-13 18:10:37 +0000912 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
Steve Naroff3536b442007-09-06 21:24:23 +0000913 IdentList[i]->setFETokenInfo(IDecl);
914
915 // Remember that this needs to be removed when the scope is popped.
916 S->AddDecl(IdentList[i]);
917
918 CDecl->setInterfaceDecl((int)i, IDecl);
919 }
920 return CDecl;
921}
922
Reid Spencer5f016e22007-07-11 17:01:13 +0000923
Steve Naroff08d92e42007-09-15 18:49:24 +0000924/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +0000925/// former case, Name will be non-null. In the later case, Name will be null.
926/// TagType indicates what kind of tag this is. TK indicates whether this is a
927/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +0000928Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +0000929 SourceLocation KWLoc, IdentifierInfo *Name,
930 SourceLocation NameLoc, AttributeList *Attr) {
931 // If this is a use of an existing tag, it must have a name.
932 assert((Name != 0 || TK == TK_Definition) &&
933 "Nameless record must be a definition!");
934
935 Decl::Kind Kind;
936 switch (TagType) {
937 default: assert(0 && "Unknown tag type!");
938 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
939 case DeclSpec::TST_union: Kind = Decl::Union; break;
940//case DeclSpec::TST_class: Kind = Decl::Class; break;
941 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
942 }
943
944 // If this is a named struct, check to see if there was a previous forward
945 // declaration or definition.
946 if (TagDecl *PrevDecl =
947 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
948 NameLoc, S))) {
949
950 // If this is a use of a previous tag, or if the tag is already declared in
951 // the same scope (so that the definition/declaration completes or
952 // rementions the tag), reuse the decl.
953 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
954 // Make sure that this wasn't declared as an enum and now used as a struct
955 // or something similar.
956 if (PrevDecl->getKind() != Kind) {
957 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
958 Diag(PrevDecl->getLocation(), diag::err_previous_use);
959 }
960
961 // If this is a use or a forward declaration, we're good.
962 if (TK != TK_Definition)
963 return PrevDecl;
964
965 // Diagnose attempts to redefine a tag.
966 if (PrevDecl->isDefinition()) {
967 Diag(NameLoc, diag::err_redefinition, Name->getName());
968 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
969 // If this is a redefinition, recover by making this struct be
970 // anonymous, which will make any later references get the previous
971 // definition.
972 Name = 0;
973 } else {
974 // Okay, this is definition of a previously declared or referenced tag.
975 // Move the location of the decl to be the definition site.
976 PrevDecl->setLocation(NameLoc);
977 return PrevDecl;
978 }
979 }
980 // If we get here, this is a definition of a new struct type in a nested
981 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
982 // type.
983 }
984
985 // If there is an identifier, use the location of the identifier as the
986 // location of the decl, otherwise use the location of the struct/union
987 // keyword.
988 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
989
990 // Otherwise, if this is the first time we've seen this tag, create the decl.
991 TagDecl *New;
992 switch (Kind) {
993 default: assert(0 && "Unknown tag kind!");
994 case Decl::Enum:
995 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
996 // enum X { A, B, C } D; D should chain to X.
997 New = new EnumDecl(Loc, Name, 0);
998 // If this is an undefined enum, warn.
999 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1000 break;
1001 case Decl::Union:
1002 case Decl::Struct:
1003 case Decl::Class:
1004 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1005 // struct X { int A; } D; D should chain to X.
1006 New = new RecordDecl(Kind, Loc, Name, 0);
1007 break;
1008 }
1009
1010 // If this has an identifier, add it to the scope stack.
1011 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001012 // The scope passed in may not be a decl scope. Zip up the scope tree until
1013 // we find one that is.
1014 while ((S->getFlags() & Scope::DeclScope) == 0)
1015 S = S->getParent();
1016
1017 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001018 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001019 Name->setFETokenInfo(New);
1020 S->AddDecl(New);
1021 }
1022
1023 return New;
1024}
1025
Steve Naroff08d92e42007-09-15 18:49:24 +00001026/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001027/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001028Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001029 SourceLocation DeclStart,
1030 Declarator &D, ExprTy *BitfieldWidth) {
1031 IdentifierInfo *II = D.getIdentifier();
1032 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001033 SourceLocation Loc = DeclStart;
1034 if (II) Loc = D.getIdentifierLoc();
1035
1036 // FIXME: Unnamed fields can be handled in various different ways, for
1037 // example, unnamed unions inject all members into the struct namespace!
1038
1039
1040 if (BitWidth) {
1041 // TODO: Validate.
1042 //printf("WARNING: BITFIELDS IGNORED!\n");
1043
1044 // 6.7.2.1p3
1045 // 6.7.2.1p4
1046
1047 } else {
1048 // Not a bitfield.
1049
1050 // validate II.
1051
1052 }
1053
1054 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001055 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1056 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001057
Reid Spencer5f016e22007-07-11 17:01:13 +00001058 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1059 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001060 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1061 Diag(Loc, diag::err_typecheck_illegal_vla,
1062 VAT->getSizeExpr()->getSourceRange());
1063 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001064 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001065 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001066 FieldDecl *NewFD;
1067
1068 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001069 NewFD = new FieldDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001070 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001071 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001072 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001073 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001074
Steve Naroff5912a352007-08-28 20:14:24 +00001075 if (D.getInvalidType() || InvalidDecl)
1076 NewFD->setInvalidDecl();
1077 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001078}
1079
Steve Narofff13271f2007-09-14 23:09:53 +00001080static void ObjcSetIvarVisibility(ObjcIvarDecl *OIvar,
1081 tok::ObjCKeywordKind ivarVisibility) {
1082 assert(OIvar && "missing instance variable");
1083 switch (ivarVisibility) {
1084 case tok::objc_private:
1085 OIvar->setAccessControl(ObjcIvarDecl::Private);
1086 break;
1087 case tok::objc_public:
1088 OIvar->setAccessControl(ObjcIvarDecl::Public);
1089 break;
1090 case tok::objc_protected:
1091 OIvar->setAccessControl(ObjcIvarDecl::Protected);
1092 break;
1093 case tok::objc_package:
1094 OIvar->setAccessControl(ObjcIvarDecl::Package);
1095 break;
1096 default:
1097 OIvar->setAccessControl(ObjcIvarDecl::None);
1098 break;
1099 }
1100}
1101
Steve Naroff08d92e42007-09-15 18:49:24 +00001102void Sema::ActOnFields(SourceLocation RecLoc, DeclTy *RecDecl,
1103 DeclTy **Fields, unsigned NumFields,
1104 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001105 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1106 assert(EnclosingDecl && "missing record or interface decl");
1107 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1108
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001109 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001110 // Diagnose code like:
1111 // struct S { struct S {} X; };
1112 // We discover this when we complete the outer S. Reject and ignore the
1113 // outer S.
1114 Diag(Record->getLocation(), diag::err_nested_redefinition,
1115 Record->getKindName());
1116 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001117 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001118 return;
1119 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 // Verify that all the fields are okay.
1121 unsigned NumNamedMembers = 0;
1122 llvm::SmallVector<FieldDecl*, 32> RecFields;
1123 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001124
Reid Spencer5f016e22007-07-11 17:01:13 +00001125 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001126
Steve Naroff74216642007-09-14 22:20:54 +00001127 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1128 assert(FD && "missing field decl");
1129
1130 // Remember all fields.
1131 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001132
1133 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001134 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001135
Steve Narofff13271f2007-09-14 23:09:53 +00001136 // If we have visibility info, make sure the AST is set accordingly.
1137 if (visibility)
1138 ObjcSetIvarVisibility(dyn_cast<ObjcIvarDecl>(FD), visibility[i]);
1139
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001141 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001142 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001144 FD->setInvalidDecl();
1145 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001146 continue;
1147 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001148 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1149 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001150 if (!Record) { // Incomplete ivar type is always an error.
1151 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001152 FD->setInvalidDecl();
1153 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001154 continue;
1155 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001156 if (i != NumFields-1 || // ... that the last member ...
1157 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001158 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001159 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001160 FD->setInvalidDecl();
1161 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 continue;
1163 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001164 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001165 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1166 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001167 FD->setInvalidDecl();
1168 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001169 continue;
1170 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001172 if (Record)
1173 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001174 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001175 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1176 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001177 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001178 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1179 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001180 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001181 Record->setHasFlexibleArrayMember(true);
1182 } else {
1183 // If this is a struct/class and this is not the last element, reject
1184 // it. Note that GCC supports variable sized arrays in the middle of
1185 // structures.
1186 if (i != NumFields-1) {
1187 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1188 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001189 FD->setInvalidDecl();
1190 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 continue;
1192 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001193 // We support flexible arrays at the end of structs in other structs
1194 // as an extension.
1195 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1196 FD->getName());
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001197 if (Record)
1198 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 }
1200 }
1201 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 // Keep track of the number of named members.
1203 if (IdentifierInfo *II = FD->getIdentifier()) {
1204 // Detect duplicate member names.
1205 if (!FieldIDs.insert(II)) {
1206 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1207 // Find the previous decl.
1208 SourceLocation PrevLoc;
1209 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1210 assert(i != e && "Didn't find previous def!");
1211 if (RecFields[i]->getIdentifier() == II) {
1212 PrevLoc = RecFields[i]->getLocation();
1213 break;
1214 }
1215 }
1216 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001217 FD->setInvalidDecl();
1218 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 continue;
1220 }
1221 ++NumNamedMembers;
1222 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 }
1224
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 // Okay, we successfully defined 'Record'.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001226 if (Record)
1227 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001228 else {
1229 ObjcIvarDecl **ClsFields =
1230 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
1231 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1232 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1233 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001234}
1235
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001236void Sema::ObjcAddMethodsToClass(DeclTy *ClassDecl,
1237 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001238 // FIXME: Fix this when we can handle methods declared in protocols.
1239 // See Parser::ParseObjCAtProtocolDeclaration
1240 if (!ClassDecl)
1241 return;
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001242 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1243 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1244
1245 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001246 ObjcMethodDecl *Method =
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001247 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1248 if (!Method) continue; // Already issued a diagnostic.
1249 if (Method->isInstance())
1250 insMethods.push_back(Method);
1251 else
1252 clsMethods.push_back(Method);
1253 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001254 if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(ClassDecl))) {
1255 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1256 static_cast<Decl*>(ClassDecl));
1257 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1258 &clsMethods[0], clsMethods.size());
1259 }
1260 else if (isa<ObjcProtocolDecl>(static_cast<Decl *>(ClassDecl))) {
1261 ObjcProtocolDecl *Protocol = cast<ObjcProtocolDecl>(
1262 static_cast<Decl*>(ClassDecl));
1263 Protocol->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1264 &clsMethods[0], clsMethods.size());
1265 }
1266 else
1267 assert(0 && "Sema::ObjcAddMethodsToClass(): Unknown DeclTy");
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001268 return;
1269}
1270
Fariborz Jahanian00933592007-09-18 00:25:23 +00001271Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
Steve Naroff37387c92007-09-17 20:25:27 +00001272 tok::TokenKind MethodType, TypeTy *ReturnType,
1273 ObjcKeywordDecl *Keywords, unsigned NumKeywords,
Fariborz Jahanian00933592007-09-18 00:25:23 +00001274 AttributeList *AttrList,
1275 tok::ObjCKeywordKind MethodDeclKind) {
Steve Naroff37387c92007-09-17 20:25:27 +00001276 assert(NumKeywords && "Selector must be specified");
1277
1278 // Derive the selector name from the keyword declarations.
Steve Naroff3f128ad2007-09-17 14:16:13 +00001279 int len=0;
1280 char *methodName;
Steve Naroff37387c92007-09-17 20:25:27 +00001281 for (unsigned int i = 0; i < NumKeywords; i++) {
1282 if (Keywords[i].SelectorName)
1283 len += strlen(Keywords[i].SelectorName->getName());
Steve Naroff3f128ad2007-09-17 14:16:13 +00001284 len++;
1285 }
1286 methodName = (char *) alloca (len + 1);
1287 methodName[0] = '\0';
Steve Naroff37387c92007-09-17 20:25:27 +00001288 for (unsigned int i = 0; i < NumKeywords; i++) {
1289 if (Keywords[i].SelectorName)
1290 strcat(methodName, Keywords[i].SelectorName->getName());
Steve Naroff3f128ad2007-09-17 14:16:13 +00001291 strcat(methodName, ":");
1292 }
Steve Naroff37387c92007-09-17 20:25:27 +00001293 SelectorInfo &SelName = Context.getSelectorInfo(methodName, methodName+len);
Steve Naroff3f128ad2007-09-17 14:16:13 +00001294
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001295 llvm::SmallVector<ParmVarDecl*, 16> Params;
1296
1297 for (unsigned i = 0; i < NumKeywords; i++) {
Steve Naroff37387c92007-09-17 20:25:27 +00001298 ObjcKeywordDecl *arg = &Keywords[i];
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001299 // FIXME: arg->AttrList must be stored too!
1300 ParmVarDecl* Param = new ParmVarDecl(arg->ColonLoc, arg->ArgumentName,
1301 QualType::getFromOpaquePtr(arg->TypeInfo),
1302 VarDecl::None, 0);
1303 // FIXME: 'InvalidType' does not get set by caller yet.
1304 if (arg->InvalidType)
1305 Param->setInvalidDecl();
1306 Params.push_back(Param);
1307 }
1308 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Fariborz Jahanian146fbb02007-09-17 22:36:42 +00001309 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc,
1310 SelName, resultDeclType,
1311 0, -1, AttrList, MethodType == tok::minus);
1312 ObjcMethod->setMethodParams(&Params[0], NumKeywords);
Fariborz Jahanian00933592007-09-18 00:25:23 +00001313 if (MethodDeclKind == tok::objc_optional)
Fariborz Jahanian146fbb02007-09-17 22:36:42 +00001314 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Optional);
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001315 else
Fariborz Jahanian146fbb02007-09-17 22:36:42 +00001316 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Required);
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001317 return ObjcMethod;
1318}
1319
Fariborz Jahanian00933592007-09-18 00:25:23 +00001320Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001321 tok::TokenKind MethodType, TypeTy *ReturnType,
Fariborz Jahanian00933592007-09-18 00:25:23 +00001322 IdentifierInfo *SelectorName, AttributeList *AttrList,
1323 tok::ObjCKeywordKind MethodDeclKind) {
Steve Naroff3f128ad2007-09-17 14:16:13 +00001324 const char *methodName = SelectorName->getName();
1325 SelectorInfo &SelName = Context.getSelectorInfo(methodName,
1326 methodName+strlen(methodName));
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001327 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Fariborz Jahanian146fbb02007-09-17 22:36:42 +00001328 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc,
1329 SelName, resultDeclType, 0, -1,
1330 AttrList, MethodType == tok::minus);
Fariborz Jahanian00933592007-09-18 00:25:23 +00001331 if (MethodDeclKind == tok::objc_optional)
Fariborz Jahanian146fbb02007-09-17 22:36:42 +00001332 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Optional);
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001333 else
Fariborz Jahanian146fbb02007-09-17 22:36:42 +00001334 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Required);
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001335 return ObjcMethod;
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001336}
1337
Steve Naroff08d92e42007-09-15 18:49:24 +00001338Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 DeclTy *lastEnumConst,
1340 SourceLocation IdLoc, IdentifierInfo *Id,
1341 SourceLocation EqualLoc, ExprTy *val) {
1342 theEnumDecl = theEnumDecl; // silence unused warning.
1343 EnumConstantDecl *LastEnumConst =
1344 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1345 Expr *Val = static_cast<Expr*>(val);
1346
Chris Lattner31e05722007-08-26 06:24:45 +00001347 // The scope passed in may not be a decl scope. Zip up the scope tree until
1348 // we find one that is.
1349 while ((S->getFlags() & Scope::DeclScope) == 0)
1350 S = S->getParent();
1351
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 // Verify that there isn't already something declared with this name in this
1353 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001354 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1355 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 if (S->isDeclScope(PrevDecl)) {
1357 if (isa<EnumConstantDecl>(PrevDecl))
1358 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1359 else
1360 Diag(IdLoc, diag::err_redefinition, Id->getName());
1361 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1362 // FIXME: Don't leak memory: delete Val;
1363 return 0;
1364 }
1365 }
1366
1367 llvm::APSInt EnumVal(32);
1368 QualType EltTy;
1369 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001370 // Make sure to promote the operand type to int.
1371 UsualUnaryConversions(Val);
1372
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1374 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001375 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1377 Id->getName());
1378 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001379 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001380 } else {
1381 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001382 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001383 }
1384
1385 if (!Val) {
1386 if (LastEnumConst) {
1387 // Assign the last value + 1.
1388 EnumVal = LastEnumConst->getInitVal();
1389 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001390
1391 // Check for overflow on increment.
1392 if (EnumVal < LastEnumConst->getInitVal())
1393 Diag(IdLoc, diag::warn_enum_value_overflow);
1394
Chris Lattnerb7416f92007-08-27 17:37:24 +00001395 EltTy = LastEnumConst->getType();
1396 } else {
1397 // First value, set to zero.
1398 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001399 EnumVal.zextOrTrunc(
1400 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001401 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001402 }
1403
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1405 LastEnumConst);
1406
1407 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001408 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 Id->setFETokenInfo(New);
1410 S->AddDecl(New);
1411 return New;
1412}
1413
Steve Naroff08d92e42007-09-15 18:49:24 +00001414void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001415 DeclTy **Elements, unsigned NumElements) {
1416 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1417 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1418
Chris Lattnere37f0be2007-08-28 05:10:31 +00001419 // TODO: If the result value doesn't fit in an int, it must be a long or long
1420 // long value. ISO C does not support this, but GCC does as an extension,
1421 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001422 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001423
1424
Chris Lattnerac609682007-08-28 06:15:15 +00001425 // Verify that all the values are okay, compute the size of the values, and
1426 // reverse the list.
1427 unsigned NumNegativeBits = 0;
1428 unsigned NumPositiveBits = 0;
1429
1430 // Keep track of whether all elements have type int.
1431 bool AllElementsInt = true;
1432
Reid Spencer5f016e22007-07-11 17:01:13 +00001433 EnumConstantDecl *EltList = 0;
1434 for (unsigned i = 0; i != NumElements; ++i) {
1435 EnumConstantDecl *ECD =
1436 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1437 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001438
1439 // If the enum value doesn't fit in an int, emit an extension warning.
1440 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1441 "Should have promoted value to int");
1442 const llvm::APSInt &InitVal = ECD->getInitVal();
1443 if (InitVal.getBitWidth() > IntWidth) {
1444 llvm::APSInt V(InitVal);
1445 V.trunc(IntWidth);
1446 V.extend(InitVal.getBitWidth());
1447 if (V != InitVal)
1448 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1449 InitVal.toString());
1450 }
Chris Lattnerac609682007-08-28 06:15:15 +00001451
1452 // Keep track of the size of positive and negative values.
1453 if (InitVal.isUnsigned() || !InitVal.isNegative())
1454 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1455 else
1456 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001457
Chris Lattnerac609682007-08-28 06:15:15 +00001458 // Keep track of whether every enum element has type int (very commmon).
1459 if (AllElementsInt)
1460 AllElementsInt = ECD->getType() == Context.IntTy;
1461
Reid Spencer5f016e22007-07-11 17:01:13 +00001462 ECD->setNextDeclarator(EltList);
1463 EltList = ECD;
1464 }
1465
Chris Lattnerac609682007-08-28 06:15:15 +00001466 // Figure out the type that should be used for this enum.
1467 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1468 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001469 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001470
1471 if (NumNegativeBits) {
1472 // If there is a negative value, figure out the smallest integer type (of
1473 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001474 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001475 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001476 BestWidth = IntWidth;
1477 } else {
1478 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1479 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001480 BestType = Context.LongTy;
1481 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001482 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1483 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001484 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1485 BestType = Context.LongLongTy;
1486 }
1487 }
1488 } else {
1489 // If there is no negative value, figure out which of uint, ulong, ulonglong
1490 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001491 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001492 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001493 BestWidth = IntWidth;
1494 } else if (NumPositiveBits <=
1495 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001496 BestType = Context.UnsignedLongTy;
1497 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001498 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1499 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001500 "How could an initializer get larger than ULL?");
1501 BestType = Context.UnsignedLongLongTy;
1502 }
1503 }
1504
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001505 // Loop over all of the enumerator constants, changing their types to match
1506 // the type of the enum if needed.
1507 for (unsigned i = 0; i != NumElements; ++i) {
1508 EnumConstantDecl *ECD =
1509 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1510 if (!ECD) continue; // Already issued a diagnostic.
1511
1512 // Standard C says the enumerators have int type, but we allow, as an
1513 // extension, the enumerators to be larger than int size. If each
1514 // enumerator value fits in an int, type it as an int, otherwise type it the
1515 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1516 // that X has type 'int', not 'unsigned'.
1517 if (ECD->getType() == Context.IntTy)
1518 continue; // Already int type.
1519
1520 // Determine whether the value fits into an int.
1521 llvm::APSInt InitVal = ECD->getInitVal();
1522 bool FitsInInt;
1523 if (InitVal.isUnsigned() || !InitVal.isNegative())
1524 FitsInInt = InitVal.getActiveBits() < IntWidth;
1525 else
1526 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1527
1528 // If it fits into an integer type, force it. Otherwise force it to match
1529 // the enum decl type.
1530 QualType NewTy;
1531 unsigned NewWidth;
1532 bool NewSign;
1533 if (FitsInInt) {
1534 NewTy = Context.IntTy;
1535 NewWidth = IntWidth;
1536 NewSign = true;
1537 } else if (ECD->getType() == BestType) {
1538 // Already the right type!
1539 continue;
1540 } else {
1541 NewTy = BestType;
1542 NewWidth = BestWidth;
1543 NewSign = BestType->isSignedIntegerType();
1544 }
1545
1546 // Adjust the APSInt value.
1547 InitVal.extOrTrunc(NewWidth);
1548 InitVal.setIsSigned(NewSign);
1549 ECD->setInitVal(InitVal);
1550
1551 // Adjust the Expr initializer and type.
1552 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1553 ECD->setType(NewTy);
1554 }
Chris Lattnerac609682007-08-28 06:15:15 +00001555
Chris Lattnere00b18c2007-08-28 18:24:31 +00001556 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001557}
1558
1559void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1560 if (!current) return;
1561
1562 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1563 // remember this in the LastInGroupList list.
1564 if (last)
1565 LastInGroupList.push_back((Decl*)last);
1566}
1567
1568void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1569 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1570 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1571 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1572 if (!newType.isNull()) // install the new vector type into the decl
1573 vDecl->setType(newType);
1574 }
1575 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1576 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1577 rawAttr);
1578 if (!newType.isNull()) // install the new vector type into the decl
1579 tDecl->setUnderlyingType(newType);
1580 }
1581 }
Steve Naroff73322922007-07-18 18:00:27 +00001582 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001583 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1584 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1585 else
Steve Naroff73322922007-07-18 18:00:27 +00001586 Diag(rawAttr->getAttributeLoc(),
1587 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00001588 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 // FIXME: add other attributes...
1590}
1591
1592void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1593 AttributeList *declarator_postfix) {
1594 while (declspec_prefix) {
1595 HandleDeclAttribute(New, declspec_prefix);
1596 declspec_prefix = declspec_prefix->getNext();
1597 }
1598 while (declarator_postfix) {
1599 HandleDeclAttribute(New, declarator_postfix);
1600 declarator_postfix = declarator_postfix->getNext();
1601 }
1602}
1603
Steve Naroffbea0b342007-07-29 16:33:31 +00001604void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1605 AttributeList *rawAttr) {
1606 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00001607 // check the attribute arugments.
1608 if (rawAttr->getNumArgs() != 1) {
1609 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1610 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001611 return;
Steve Naroff73322922007-07-18 18:00:27 +00001612 }
1613 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1614 llvm::APSInt vecSize(32);
1615 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1616 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1617 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001618 return;
Steve Naroff73322922007-07-18 18:00:27 +00001619 }
1620 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1621 // in conjunction with complex types (pointers, arrays, functions, etc.).
1622 Type *canonType = curType.getCanonicalType().getTypePtr();
1623 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1624 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1625 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001626 return;
Steve Naroff73322922007-07-18 18:00:27 +00001627 }
1628 // unlike gcc's vector_size attribute, the size is specified as the
1629 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001630 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001631
1632 if (vectorSize == 0) {
1633 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1634 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001635 return;
Steve Naroff73322922007-07-18 18:00:27 +00001636 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001637 // Instantiate/Install the vector type, the number of elements is > 0.
1638 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1639 // Remember this typedef decl, we will need it later for diagnostics.
1640 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001641}
1642
Reid Spencer5f016e22007-07-11 17:01:13 +00001643QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001644 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 // check the attribute arugments.
1646 if (rawAttr->getNumArgs() != 1) {
1647 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1648 std::string("1"));
1649 return QualType();
1650 }
1651 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1652 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001653 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001654 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1655 sizeExpr->getSourceRange());
1656 return QualType();
1657 }
1658 // navigate to the base type - we need to provide for vector pointers,
1659 // vector arrays, and functions returning vectors.
1660 Type *canonType = curType.getCanonicalType().getTypePtr();
1661
Steve Naroff73322922007-07-18 18:00:27 +00001662 if (canonType->isPointerType() || canonType->isArrayType() ||
1663 canonType->isFunctionType()) {
1664 assert(1 && "HandleVector(): Complex type construction unimplemented");
1665 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1666 do {
1667 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1668 canonType = PT->getPointeeType().getTypePtr();
1669 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1670 canonType = AT->getElementType().getTypePtr();
1671 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1672 canonType = FT->getResultType().getTypePtr();
1673 } while (canonType->isPointerType() || canonType->isArrayType() ||
1674 canonType->isFunctionType());
1675 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001676 }
1677 // the base type must be integer or float.
1678 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1679 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1680 curType.getCanonicalType().getAsString());
1681 return QualType();
1682 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00001683 unsigned typeSize = static_cast<unsigned>(
1684 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001686 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00001687
1688 // the vector size needs to be an integral multiple of the type size.
1689 if (vectorSize % typeSize) {
1690 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1691 sizeExpr->getSourceRange());
1692 return QualType();
1693 }
1694 if (vectorSize == 0) {
1695 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1696 sizeExpr->getSourceRange());
1697 return QualType();
1698 }
1699 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1700 // the number of elements to be a power of two (unlike GCC).
1701 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00001702 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001703}
1704