blob: f478bf3df9ae7928f116d4afab2b68a076ec7d52 [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"
25#include "llvm/ADT/SmallSet.h"
26using namespace clang;
27
Chris Lattner4b009652007-07-25 00:24:17 +000028Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
29 return dyn_cast_or_null<TypedefDecl>(II.getFETokenInfo<Decl>());
30}
31
32void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000033 if (S->decl_empty()) return;
34 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
35
Chris Lattner4b009652007-07-25 00:24:17 +000036 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
37 I != E; ++I) {
38 Decl *D = static_cast<Decl*>(*I);
39 assert(D && "This decl didn't get pushed??");
40 IdentifierInfo *II = D->getIdentifier();
41 if (!II) continue;
42
43 // Unlink this decl from the identifier. Because the scope contains decls
44 // in an unordered collection, and because we have multiple identifier
45 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
46 if (II->getFETokenInfo<Decl>() == D) {
47 // Normal case, no multiple decls in different namespaces.
48 II->setFETokenInfo(D->getNext());
49 } else {
50 // Scan ahead. There are only three namespaces in C, so this loop can
51 // never execute more than 3 times.
52 Decl *SomeDecl = II->getFETokenInfo<Decl>();
53 while (SomeDecl->getNext() != D) {
54 SomeDecl = SomeDecl->getNext();
55 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
56 }
57 SomeDecl->setNext(D->getNext());
58 }
59
60 // This will have to be revisited for C++: there we want to nest stuff in
61 // namespace decls etc. Even for C, we might want a top-level translation
62 // unit decl or something.
63 if (!CurFunctionDecl)
64 continue;
65
66 // Chain this decl to the containing function, it now owns the memory for
67 // the decl.
68 D->setNext(CurFunctionDecl->getDeclChain());
69 CurFunctionDecl->setDeclChain(D);
70 }
71}
72
73/// LookupScopedDecl - Look up the inner-most declaration in the specified
74/// namespace.
75Decl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
76 SourceLocation IdLoc, Scope *S) {
77 if (II == 0) return 0;
78 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
79
80 // Scan up the scope chain looking for a decl that matches this identifier
81 // that is in the appropriate namespace. This search should not take long, as
82 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
83 for (Decl *D = II->getFETokenInfo<Decl>(); D; D = D->getNext())
84 if (D->getIdentifierNamespace() == NS)
85 return D;
86
87 // If we didn't find a use of this identifier, and if the identifier
88 // corresponds to a compiler builtin, create the decl object for the builtin
89 // now, injecting it into translation unit scope, and return it.
90 if (NS == Decl::IDNS_Ordinary) {
91 // If this is a builtin on some other target, or if this builtin varies
92 // across targets (e.g. in type), emit a diagnostic and mark the translation
93 // unit non-portable for using it.
94 if (II->isNonPortableBuiltin()) {
95 // Only emit this diagnostic once for this builtin.
96 II->setNonPortableBuiltin(false);
97 Context.Target.DiagnoseNonPortability(IdLoc,
98 diag::port_target_builtin_use);
99 }
100 // If this is a builtin on this (or all) targets, create the decl.
101 if (unsigned BuiltinID = II->getBuiltinID())
102 return LazilyCreateBuiltin(II, BuiltinID, S);
103 }
104 return 0;
105}
106
107/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
108/// lazily create a decl for it.
109Decl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
110 Builtin::ID BID = (Builtin::ID)bid;
111
112 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
113 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner987058a2007-08-26 04:02:13 +0000114 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000115
116 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000117 if (Scope *FnS = S->getFnParent())
118 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000119 while (S->getParent())
120 S = S->getParent();
121 S->AddDecl(New);
122
123 // Add this decl to the end of the identifier info.
124 if (Decl *LastDecl = II->getFETokenInfo<Decl>()) {
125 // Scan until we find the last (outermost) decl in the id chain.
126 while (LastDecl->getNext())
127 LastDecl = LastDecl->getNext();
128 // Insert before (outside) it.
129 LastDecl->setNext(New);
130 } else {
131 II->setFETokenInfo(New);
132 }
133 // Make sure clients iterating over decls see this.
134 LastInGroupList.push_back(New);
135
136 return New;
137}
138
139/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
140/// and scope as a previous declaration 'Old'. Figure out how to resolve this
141/// situation, merging decls or emitting diagnostics as appropriate.
142///
143TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
144 // Verify the old decl was also a typedef.
145 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
146 if (!Old) {
147 Diag(New->getLocation(), diag::err_redefinition_different_kind,
148 New->getName());
149 Diag(OldD->getLocation(), diag::err_previous_definition);
150 return New;
151 }
152
153 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
154 // TODO: This is totally simplistic. It should handle merging functions
155 // together etc, merging extern int X; int X; ...
156 Diag(New->getLocation(), diag::err_redefinition, New->getName());
157 Diag(Old->getLocation(), diag::err_previous_definition);
158 return New;
159}
160
161/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
162/// and scope as a previous declaration 'Old'. Figure out how to resolve this
163/// situation, merging decls or emitting diagnostics as appropriate.
164///
165FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
166 // Verify the old decl was also a function.
167 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
168 if (!Old) {
169 Diag(New->getLocation(), diag::err_redefinition_different_kind,
170 New->getName());
171 Diag(OldD->getLocation(), diag::err_previous_definition);
172 return New;
173 }
174
175 // This is not right, but it's a start. If 'Old' is a function prototype with
176 // the same type as 'New', silently allow this. FIXME: We should link up decl
177 // objects here.
178 if (Old->getBody() == 0 &&
179 Old->getCanonicalType() == New->getCanonicalType()) {
180 return New;
181 }
182
183 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
184 // TODO: This is totally simplistic. It should handle merging functions
185 // together etc, merging extern int X; int X; ...
186 Diag(New->getLocation(), diag::err_redefinition, New->getName());
187 Diag(Old->getLocation(), diag::err_previous_definition);
188 return New;
189}
190
191/// MergeVarDecl - We just parsed a variable 'New' which has the same name
192/// and scope as a previous declaration 'Old'. Figure out how to resolve this
193/// situation, merging decls or emitting diagnostics as appropriate.
194///
195/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
196/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
197///
198VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
199 // Verify the old decl was also a variable.
200 VarDecl *Old = dyn_cast<VarDecl>(OldD);
201 if (!Old) {
202 Diag(New->getLocation(), diag::err_redefinition_different_kind,
203 New->getName());
204 Diag(OldD->getLocation(), diag::err_previous_definition);
205 return New;
206 }
Steve Naroff83c13012007-08-30 01:06:46 +0000207 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
208 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
209 bool OldIsTentative = false;
210
211 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
212 // Handle C "tentative" external object definitions. FIXME: finish!
213 if (!OldFSDecl->getInit() &&
214 (OldFSDecl->getStorageClass() == VarDecl::None ||
215 OldFSDecl->getStorageClass() == VarDecl::Static))
216 OldIsTentative = true;
217 }
Chris Lattner4b009652007-07-25 00:24:17 +0000218 // Verify the types match.
219 if (Old->getCanonicalType() != New->getCanonicalType()) {
220 Diag(New->getLocation(), diag::err_redefinition, New->getName());
221 Diag(Old->getLocation(), diag::err_previous_definition);
222 return New;
223 }
224 // We've verified the types match, now check if Old is "extern".
225 if (Old->getStorageClass() != VarDecl::Extern) {
226 Diag(New->getLocation(), diag::err_redefinition, New->getName());
227 Diag(Old->getLocation(), diag::err_previous_definition);
228 }
229 return New;
230}
231
232/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
233/// no declarator (e.g. "struct foo;") is parsed.
234Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
235 // TODO: emit error on 'int;' or 'const enum foo;'.
236 // TODO: emit error on 'typedef int;'
237 // if (!DS.isMissingDeclaratorOk()) Diag(...);
238
239 return 0;
240}
241
Steve Naroffe14e5542007-09-02 02:04:30 +0000242bool Sema::CheckSingleInitializer(Expr *Init, QualType DeclType) {
243 AssignmentCheckResult result;
244 SourceLocation loc = Init->getLocStart();
245 // Get the type before calling CheckSingleAssignmentConstraints(), since
246 // it can promote the expression.
247 QualType rhsType = Init->getType();
248
249 result = CheckSingleAssignmentConstraints(DeclType, Init);
250
251 // decode the result (notice that extensions still return a type).
252 switch (result) {
253 case Compatible:
254 break;
255 case Incompatible:
Steve Naroff9091f3f2007-09-02 15:34:30 +0000256 // FIXME: tighten up this check which should allow:
257 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
258 if (rhsType == Context.getPointerType(Context.CharTy))
259 break;
Steve Naroffe14e5542007-09-02 02:04:30 +0000260 Diag(loc, diag::err_typecheck_assign_incompatible,
261 DeclType.getAsString(), rhsType.getAsString(),
262 Init->getSourceRange());
263 return true;
264 case PointerFromInt:
265 // check for null pointer constant (C99 6.3.2.3p3)
266 if (!Init->isNullPointerConstant(Context)) {
267 Diag(loc, diag::ext_typecheck_assign_pointer_int,
268 DeclType.getAsString(), rhsType.getAsString(),
269 Init->getSourceRange());
270 return true;
271 }
272 break;
273 case IntFromPointer:
274 Diag(loc, diag::ext_typecheck_assign_pointer_int,
275 DeclType.getAsString(), rhsType.getAsString(),
276 Init->getSourceRange());
277 break;
278 case IncompatiblePointer:
279 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
280 DeclType.getAsString(), rhsType.getAsString(),
281 Init->getSourceRange());
282 break;
283 case CompatiblePointerDiscardsQualifiers:
284 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
285 DeclType.getAsString(), rhsType.getAsString(),
286 Init->getSourceRange());
287 break;
288 }
289 return false;
290}
291
Steve Naroff509d0b52007-09-04 02:20:04 +0000292bool Sema::CheckInitExpr(Expr *expr, bool isStatic, QualType ElementType) {
293 SourceLocation loc;
294
295 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
296 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
297 return true;
298 } else if (CheckSingleInitializer(expr, ElementType)) {
299 return true; // types weren't compatible.
300 }
301 return false;
302}
303
304void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
305 QualType ElementType, bool isStatic,
306 int &nInitializers, bool &hadError) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000307 for (unsigned i = 0; i < IList->getNumInits(); i++) {
308 Expr *expr = IList->getInit(i);
309
Steve Naroff509d0b52007-09-04 02:20:04 +0000310 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
311 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
312 QualType ElmtType = CAT->getElementType();
313 int maxElements = CAT->getSize().getZExtValue();
314
315 // If we have a multi-dimensional array, navigate to the base type. Also
316 // compute the absolute array, so we can detect excess elements.
317 while ((CAT = ElmtType->getAsConstantArrayType())) {
318 ElmtType = CAT->getElementType();
319 maxElements *= CAT->getSize().getZExtValue();
320 }
321 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
322 maxElements, hadError);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000323 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000324 } else {
325 hadError = CheckInitExpr(expr, isStatic, ElementType);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000326 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000327 nInitializers++;
328 }
329 return;
330}
331
332// FIXME: Doesn't deal with arrays of structures yet.
333void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
334 QualType ElementType, bool isStatic,
335 int &totalInits, bool &hadError) {
336 int maxElementsAtThisLevel = 0;
337 int nInitsAtLevel = 0;
338
339 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
340 // We have a constant array type, compute maxElements *at this level*.
341 QualType ElmtType = CAT->getElementType();
342 maxElementsAtThisLevel = CAT->getSize().getZExtValue();
343
344 // Set DeclType, important for correctly handling multi-dimensional arrays.
345 DeclType = ElmtType;
346
347 // If we have a multi-dimensional array, navigate to the base type. Also
348 // compute the absolute size of the array *at this level* array, so we can
349 // detect excess elements.
350 while ((CAT = ElmtType->getAsConstantArrayType())) {
351 ElmtType = CAT->getElementType();
352 maxElementsAtThisLevel *= CAT->getSize().getZExtValue();
353 }
354 } else if (DeclType->isScalarType()) {
355 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
356 IList->getSourceRange());
357 maxElementsAtThisLevel = 1;
358 }
359 // The empty init list "{ }" is treated specially below.
360 unsigned numInits = IList->getNumInits();
361 if (numInits) {
362 for (unsigned i = 0; i < numInits; i++) {
363 Expr *expr = IList->getInit(i);
364
365 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
366 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
367 totalInits, hadError);
368 } else {
369 hadError = CheckInitExpr(expr, isStatic, ElementType);
370 nInitsAtLevel++; // increment the number of initializers at this level.
371 totalInits--; // decrement the total number of initializers.
372
373 // Check if we have space for another initializer.
374 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
375 Diag(expr->getLocStart(), diag::warn_excess_initializers,
376 expr->getSourceRange());
377 }
378 }
379 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
380 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
381 } else {
382 // we have an initializer list with no elements.
383 totalInits -= maxElementsAtThisLevel;
384 if (totalInits < 0)
385 Diag(IList->getLocStart(), diag::warn_excess_initializers,
386 IList->getSourceRange());
Steve Naroff9091f3f2007-09-02 15:34:30 +0000387 }
Steve Naroff1c9de712007-09-03 01:24:23 +0000388 return;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000389}
390
Steve Naroff1c9de712007-09-03 01:24:23 +0000391bool Sema::CheckInitializer(Expr *Init, QualType &DeclType, bool isStatic) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000392 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroff1c9de712007-09-03 01:24:23 +0000393 if (!InitList)
394 return CheckSingleInitializer(Init, DeclType);
395
Steve Naroffe14e5542007-09-02 02:04:30 +0000396 // We have an InitListExpr, make sure we set the type.
397 Init->setType(DeclType);
Steve Naroff1c9de712007-09-03 01:24:23 +0000398
399 bool hadError = false;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000400
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000401 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
402 // of unknown size ("[]") or an object type that is not a variable array type.
403 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
404 Expr *expr = VAT->getSizeExpr();
Steve Naroff1c9de712007-09-03 01:24:23 +0000405 if (expr)
406 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
407 expr->getSourceRange());
408
409 // We have a VariableArrayType with unknown size.
410 QualType ElmtType = VAT->getElementType();
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000411
Steve Naroff509d0b52007-09-04 02:20:04 +0000412 // Set DeclType, important for correctly handling multi-dimensional arrays.
413 DeclType = ElmtType;
Steve Naroff1c9de712007-09-03 01:24:23 +0000414
Steve Naroff509d0b52007-09-04 02:20:04 +0000415 // If we have a multi-dimensional array, navigate to the base type.
416 // Use getAsArrayType(), since it is illegal for an array to have an
417 // incomplete element type. For example, "int [][]" is illegal.
418 const ArrayType *ATY;
419 while ((ATY = ElmtType->getAsArrayType())) {
420 ElmtType = ATY->getElementType();
421 }
422 int numInits = 0;
423 CheckVariableInitList(DeclType, InitList, ElmtType, isStatic, numInits,
424 hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000425 if (!hadError) {
426 // Return a new array type from the number of initializers (C99 6.7.8p22).
427 llvm::APSInt ConstVal(32);
Steve Naroff509d0b52007-09-04 02:20:04 +0000428 ConstVal = numInits;
429 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroff1c9de712007-09-03 01:24:23 +0000430 ArrayType::Normal, 0);
431 }
432 return hadError;
433 }
434 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
435 QualType ElmtType = CAT->getElementType();
Steve Naroff509d0b52007-09-04 02:20:04 +0000436 int maxElements = CAT->getSize().getZExtValue();
Steve Naroff1c9de712007-09-03 01:24:23 +0000437
438 // If we have a multi-dimensional array, navigate to the base type. Also
439 // compute the absolute size of the array, so we can detect excess elements.
440 while ((CAT = ElmtType->getAsConstantArrayType())) {
441 ElmtType = CAT->getElementType();
Steve Naroff509d0b52007-09-04 02:20:04 +0000442 maxElements *= CAT->getSize().getZExtValue();
Steve Naroff1c9de712007-09-03 01:24:23 +0000443 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000444 CheckConstantInitList(DeclType, InitList, ElmtType, isStatic, maxElements,
445 hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000446 return hadError;
447 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000448 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
449 int maxElements = 1;
450 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
451 hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000452 return hadError;
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000453 }
454 // FIXME: Handle struct/union types.
Steve Naroff1c9de712007-09-03 01:24:23 +0000455 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +0000456}
457
Chris Lattner4b009652007-07-25 00:24:17 +0000458Sema::DeclTy *
459Sema::ParseDeclarator(Scope *S, Declarator &D, ExprTy *init,
460 DeclTy *lastDeclarator) {
461 Decl *LastDeclarator = (Decl*)lastDeclarator;
462 Expr *Init = static_cast<Expr*>(init);
463 IdentifierInfo *II = D.getIdentifier();
464
465 // All of these full declarators require an identifier. If it doesn't have
466 // one, the ParsedFreeStandingDeclSpec action should be used.
467 if (II == 0) {
Chris Lattner87492f42007-08-28 06:17:15 +0000468 Diag(D.getDeclSpec().getSourceRange().Begin(),
469 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000470 D.getDeclSpec().getSourceRange(), D.getSourceRange());
471 return 0;
472 }
473
Chris Lattnera7549902007-08-26 06:24:45 +0000474 // The scope passed in may not be a decl scope. Zip up the scope tree until
475 // we find one that is.
476 while ((S->getFlags() & Scope::DeclScope) == 0)
477 S = S->getParent();
478
Chris Lattner4b009652007-07-25 00:24:17 +0000479 // See if this is a redefinition of a variable in the same scope.
480 Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
481 D.getIdentifierLoc(), S);
482 if (PrevDecl && !S->isDeclScope(PrevDecl))
483 PrevDecl = 0; // If in outer scope, it isn't the same thing.
484
485 Decl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000486 bool InvalidDecl = false;
487
Chris Lattner4b009652007-07-25 00:24:17 +0000488 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
489 assert(Init == 0 && "Can't have initializer for a typedef!");
490 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
491 if (!NewTD) return 0;
492
493 // Handle attributes prior to checking for duplicates in MergeVarDecl
494 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
495 D.getAttributes());
496 // Merge the decl with the existing one if appropriate.
497 if (PrevDecl) {
498 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
499 if (NewTD == 0) return 0;
500 }
501 New = NewTD;
502 if (S->getParent() == 0) {
503 // C99 6.7.7p2: If a typedef name specifies a variably modified type
504 // then it shall have block scope.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000505 if (const VariableArrayType *VAT =
506 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
507 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
508 VAT->getSizeExpr()->getSourceRange());
509 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000510 }
511 }
512 } else if (D.isFunctionDeclarator()) {
513 assert(Init == 0 && "Can't have an initializer for a functiondecl!");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000514
Chris Lattner4b009652007-07-25 00:24:17 +0000515 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000516 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000517
518 FunctionDecl::StorageClass SC;
519 switch (D.getDeclSpec().getStorageClassSpec()) {
520 default: assert(0 && "Unknown storage class!");
521 case DeclSpec::SCS_auto:
522 case DeclSpec::SCS_register:
523 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
524 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000525 InvalidDecl = true;
526 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000527 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
528 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
529 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
530 }
531
532 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000533 D.getDeclSpec().isInlineSpecified(),
Chris Lattner4b009652007-07-25 00:24:17 +0000534 LastDeclarator);
535
536 // Merge the decl with the existing one if appropriate.
537 if (PrevDecl) {
538 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
539 if (NewFD == 0) return 0;
540 }
541 New = NewFD;
542 } else {
543 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffcae537d2007-08-28 18:45:29 +0000544 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000545
546 VarDecl *NewVD;
547 VarDecl::StorageClass SC;
548 switch (D.getDeclSpec().getStorageClassSpec()) {
549 default: assert(0 && "Unknown storage class!");
550 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
551 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
552 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
553 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
554 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
555 }
556 if (S->getParent() == 0) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000557 if (Init) {
558 if (SC == VarDecl::Extern)
559 Diag(D.getIdentifierLoc(), diag::warn_extern_init);
Steve Naroff509d0b52007-09-04 02:20:04 +0000560 if (!D.getInvalidType())
561 CheckInitializer(Init, R, true);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000562 }
Chris Lattner4b009652007-07-25 00:24:17 +0000563 // File scope. C99 6.9.2p2: A declaration of an identifier for and
564 // object that has file scope without an initializer, and without a
565 // storage-class specifier or with the storage-class specifier "static",
566 // constitutes a tentative definition. Note: A tentative definition with
567 // external linkage is valid (C99 6.2.2p5).
568 if (!Init && SC == VarDecl::Static) {
569 // C99 6.9.2p3: If the declaration of an identifier for an object is
570 // a tentative definition and has internal linkage (C99 6.2.2p3), the
571 // declared type shall not be an incomplete type.
572 if (R->isIncompleteType()) {
573 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
574 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000575 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000576 }
577 }
578 // C99 6.9p2: The storage-class specifiers auto and register shall not
579 // appear in the declaration specifiers in an external declaration.
580 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
581 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
582 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000583 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000584 }
Steve Naroff5eb879b2007-08-31 17:20:07 +0000585 if (SC == VarDecl::Static) {
586 // C99 6.7.5.2p2: If an identifier is declared to be an object with
587 // static storage duration, it shall not have a variable length array.
588 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
589 Expr *Size = VLA->getSizeExpr();
590 if (Size || (!Size && !Init)) {
591 // FIXME: Since we don't support initializers yet, we only emit this
592 // error when we don't have an initializer. Once initializers are
593 // implemented, the VLA will change to a CLA.
594 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
595 InvalidDecl = true;
596 }
597 }
Chris Lattner4b009652007-07-25 00:24:17 +0000598 }
599 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000600 } else {
601 if (Init) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000602 if (SC == VarDecl::Extern) { // C99 6.7.8p5
603 Diag(D.getIdentifierLoc(), diag::err_block_extern_cant_init);
604 InvalidDecl = true;
Steve Naroff509d0b52007-09-04 02:20:04 +0000605 } else if (!D.getInvalidType()) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000606 CheckInitializer(Init, R, SC == VarDecl::Static);
607 }
Steve Naroffe14e5542007-09-02 02:04:30 +0000608 }
Chris Lattner4b009652007-07-25 00:24:17 +0000609 // Block scope. C99 6.7p7: If an identifier for an object is declared with
610 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
611 if (SC != VarDecl::Extern) {
612 if (R->isIncompleteType()) {
613 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
614 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000615 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000616 }
617 }
618 if (SC == VarDecl::Static) {
619 // C99 6.7.5.2p2: If an identifier is declared to be an object with
620 // static storage duration, it shall not have a variable length array.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000621 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
622 Expr *Size = VLA->getSizeExpr();
623 if (Size || (!Size && !Init)) {
624 // FIXME: Since we don't support initializers yet, we only emit this
625 // error when we don't have an initializer. Once initializers are
626 // implemented, the VLA will change to a CLA.
627 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffcae537d2007-08-28 18:45:29 +0000628 InvalidDecl = true;
Steve Naroff5eb879b2007-08-31 17:20:07 +0000629 }
Chris Lattner4b009652007-07-25 00:24:17 +0000630 }
631 }
632 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000633 }
Chris Lattner4b009652007-07-25 00:24:17 +0000634 // Handle attributes prior to checking for duplicates in MergeVarDecl
635 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
636 D.getAttributes());
637
638 // Merge the decl with the existing one if appropriate.
639 if (PrevDecl) {
640 NewVD = MergeVarDecl(NewVD, PrevDecl);
641 if (NewVD == 0) return 0;
642 }
Steve Naroffe14e5542007-09-02 02:04:30 +0000643 if (Init) { // FIXME: This will likely move up above...for now, it stays.
Steve Naroff0f32f432007-08-24 22:33:52 +0000644 NewVD->setInit(Init);
645 }
Chris Lattner4b009652007-07-25 00:24:17 +0000646 New = NewVD;
647 }
648
649 // If this has an identifier, add it to the scope stack.
650 if (II) {
651 New->setNext(II->getFETokenInfo<Decl>());
652 II->setFETokenInfo(New);
653 S->AddDecl(New);
654 }
655
656 if (S->getParent() == 0)
657 AddTopLevelDecl(New, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000658
659 // If any semantic error occurred, mark the decl as invalid.
660 if (D.getInvalidType() || InvalidDecl)
661 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000662
663 return New;
664}
665
666/// The declarators are chained together backwards, reverse the list.
667Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
668 // Often we have single declarators, handle them quickly.
669 Decl *Group = static_cast<Decl*>(group);
670 if (Group == 0 || Group->getNextDeclarator() == 0) return Group;
671
672 Decl *NewGroup = 0;
673 while (Group) {
674 Decl *Next = Group->getNextDeclarator();
675 Group->setNextDeclarator(NewGroup);
676 NewGroup = Group;
677 Group = Next;
678 }
679 return NewGroup;
680}
Steve Naroff91b03f72007-08-28 03:03:08 +0000681
682// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000683ParmVarDecl *
684Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
685 Scope *FnScope) {
686 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
687
688 IdentifierInfo *II = PI.Ident;
689 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
690 // Can this happen for params? We already checked that they don't conflict
691 // among each other. Here they can only shadow globals, which is ok.
692 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
693 PI.IdentLoc, FnScope)) {
694
695 }
696
697 // FIXME: Handle storage class (auto, register). No declarator?
698 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000699
700 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
701 // Doing the promotion here has a win and a loss. The win is the type for
702 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
703 // code generator). The loss is the orginal type isn't preserved. For example:
704 //
705 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
706 // int blockvardecl[5];
707 // sizeof(parmvardecl); // size == 4
708 // sizeof(blockvardecl); // size == 20
709 // }
710 //
711 // For expressions, all implicit conversions are captured using the
712 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
713 //
714 // FIXME: If a source translation tool needs to see the original type, then
715 // we need to consider storing both types (in ParmVarDecl)...
716 //
717 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
718 if (const ArrayType *AT = parmDeclType->getAsArrayType())
719 parmDeclType = Context.getPointerType(AT->getElementType());
720 else if (parmDeclType->isFunctionType())
721 parmDeclType = Context.getPointerType(parmDeclType);
722
723 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffcae537d2007-08-28 18:45:29 +0000724 VarDecl::None, 0);
725 if (PI.InvalidType)
726 New->setInvalidDecl();
727
Chris Lattner4b009652007-07-25 00:24:17 +0000728 // If this has an identifier, add it to the scope stack.
729 if (II) {
730 New->setNext(II->getFETokenInfo<Decl>());
731 II->setFETokenInfo(New);
732 FnScope->AddDecl(New);
733 }
734
735 return New;
736}
737
738
739Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
740 assert(CurFunctionDecl == 0 && "Function parsing confused");
741 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
742 "Not a function declarator!");
743 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
744
745 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
746 // for a K&R function.
747 if (!FTI.hasPrototype) {
748 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
749 if (FTI.ArgInfo[i].TypeInfo == 0) {
750 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
751 FTI.ArgInfo[i].Ident->getName());
752 // Implicitly declare the argument as type 'int' for lack of a better
753 // type.
754 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
755 }
756 }
757
758 // Since this is a function definition, act as though we have information
759 // about the arguments.
760 FTI.hasPrototype = true;
761 } else {
762 // FIXME: Diagnose arguments without names in C.
763
764 }
765
766 Scope *GlobalScope = FnBodyScope->getParent();
767
768 FunctionDecl *FD =
769 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0, 0));
770 CurFunctionDecl = FD;
771
772 // Create Decl objects for each parameter, adding them to the FunctionDecl.
773 llvm::SmallVector<ParmVarDecl*, 16> Params;
774
775 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
776 // no arguments, not a function that takes a single void argument.
777 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
778 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
779 // empty arg list, don't push any params.
780 } else {
781 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
782 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
783 }
784
785 FD->setParams(&Params[0], Params.size());
786
787 return FD;
788}
789
790Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
791 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
792 FD->setBody((Stmt*)Body);
793
794 assert(FD == CurFunctionDecl && "Function parsing confused");
795 CurFunctionDecl = 0;
796
797 // Verify and clean out per-function state.
798
799 // Check goto/label use.
800 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
801 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
802 // Verify that we have no forward references left. If so, there was a goto
803 // or address of a label taken, but no definition of it. Label fwd
804 // definitions are indicated with a null substmt.
805 if (I->second->getSubStmt() == 0) {
806 LabelStmt *L = I->second;
807 // Emit error.
808 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
809
810 // At this point, we have gotos that use the bogus label. Stitch it into
811 // the function body so that they aren't leaked and that the AST is well
812 // formed.
813 L->setSubStmt(new NullStmt(L->getIdentLoc()));
814 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
815 }
816 }
817 LabelMap.clear();
818
819 return FD;
820}
821
822
823/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
824/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
825Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
826 Scope *S) {
827 if (getLangOptions().C99) // Extension in C99.
828 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
829 else // Legal in C90, but warn about it.
830 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
831
832 // FIXME: handle stuff like:
833 // void foo() { extern float X(); }
834 // void bar() { X(); } <-- implicit decl for X in another scope.
835
836 // Set a Declarator for the implicit definition: int foo();
837 const char *Dummy;
838 DeclSpec DS;
839 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
840 Error = Error; // Silence warning.
841 assert(!Error && "Error setting up implicit decl!");
842 Declarator D(DS, Declarator::BlockContext);
843 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
844 D.SetIdentifier(&II, Loc);
845
846 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000847 if (Scope *FnS = S->getFnParent())
848 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000849 while (S->getParent())
850 S = S->getParent();
851
852 return static_cast<Decl*>(ParseDeclarator(S, D, 0, 0));
853}
854
855
856TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
857 Decl *LastDeclarator) {
858 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
859
860 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000861 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000862
863 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000864 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
865 T, LastDeclarator);
866 if (D.getInvalidType())
867 NewTD->setInvalidDecl();
868 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +0000869}
870
871
872/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
873/// former case, Name will be non-null. In the later case, Name will be null.
874/// TagType indicates what kind of tag this is. TK indicates whether this is a
875/// reference/declaration/definition of a tag.
876Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
877 SourceLocation KWLoc, IdentifierInfo *Name,
878 SourceLocation NameLoc, AttributeList *Attr) {
879 // If this is a use of an existing tag, it must have a name.
880 assert((Name != 0 || TK == TK_Definition) &&
881 "Nameless record must be a definition!");
882
883 Decl::Kind Kind;
884 switch (TagType) {
885 default: assert(0 && "Unknown tag type!");
886 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
887 case DeclSpec::TST_union: Kind = Decl::Union; break;
888//case DeclSpec::TST_class: Kind = Decl::Class; break;
889 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
890 }
891
892 // If this is a named struct, check to see if there was a previous forward
893 // declaration or definition.
894 if (TagDecl *PrevDecl =
895 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
896 NameLoc, S))) {
897
898 // If this is a use of a previous tag, or if the tag is already declared in
899 // the same scope (so that the definition/declaration completes or
900 // rementions the tag), reuse the decl.
901 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
902 // Make sure that this wasn't declared as an enum and now used as a struct
903 // or something similar.
904 if (PrevDecl->getKind() != Kind) {
905 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
906 Diag(PrevDecl->getLocation(), diag::err_previous_use);
907 }
908
909 // If this is a use or a forward declaration, we're good.
910 if (TK != TK_Definition)
911 return PrevDecl;
912
913 // Diagnose attempts to redefine a tag.
914 if (PrevDecl->isDefinition()) {
915 Diag(NameLoc, diag::err_redefinition, Name->getName());
916 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
917 // If this is a redefinition, recover by making this struct be
918 // anonymous, which will make any later references get the previous
919 // definition.
920 Name = 0;
921 } else {
922 // Okay, this is definition of a previously declared or referenced tag.
923 // Move the location of the decl to be the definition site.
924 PrevDecl->setLocation(NameLoc);
925 return PrevDecl;
926 }
927 }
928 // If we get here, this is a definition of a new struct type in a nested
929 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
930 // type.
931 }
932
933 // If there is an identifier, use the location of the identifier as the
934 // location of the decl, otherwise use the location of the struct/union
935 // keyword.
936 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
937
938 // Otherwise, if this is the first time we've seen this tag, create the decl.
939 TagDecl *New;
940 switch (Kind) {
941 default: assert(0 && "Unknown tag kind!");
942 case Decl::Enum:
943 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
944 // enum X { A, B, C } D; D should chain to X.
945 New = new EnumDecl(Loc, Name, 0);
946 // If this is an undefined enum, warn.
947 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
948 break;
949 case Decl::Union:
950 case Decl::Struct:
951 case Decl::Class:
952 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
953 // struct X { int A; } D; D should chain to X.
954 New = new RecordDecl(Kind, Loc, Name, 0);
955 break;
956 }
957
958 // If this has an identifier, add it to the scope stack.
959 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +0000960 // The scope passed in may not be a decl scope. Zip up the scope tree until
961 // we find one that is.
962 while ((S->getFlags() & Scope::DeclScope) == 0)
963 S = S->getParent();
964
965 // Add it to the decl chain.
Chris Lattner4b009652007-07-25 00:24:17 +0000966 New->setNext(Name->getFETokenInfo<Decl>());
967 Name->setFETokenInfo(New);
968 S->AddDecl(New);
969 }
970
971 return New;
972}
973
974/// ParseField - Each field of a struct/union/class is passed into this in order
975/// to create a FieldDecl object for it.
976Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
977 SourceLocation DeclStart,
978 Declarator &D, ExprTy *BitfieldWidth) {
979 IdentifierInfo *II = D.getIdentifier();
980 Expr *BitWidth = (Expr*)BitfieldWidth;
981
982 SourceLocation Loc = DeclStart;
983 if (II) Loc = D.getIdentifierLoc();
984
985 // FIXME: Unnamed fields can be handled in various different ways, for
986 // example, unnamed unions inject all members into the struct namespace!
987
988
989 if (BitWidth) {
990 // TODO: Validate.
991 //printf("WARNING: BITFIELDS IGNORED!\n");
992
993 // 6.7.2.1p3
994 // 6.7.2.1p4
995
996 } else {
997 // Not a bitfield.
998
999 // validate II.
1000
1001 }
1002
1003 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001004 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1005 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001006
Chris Lattner4b009652007-07-25 00:24:17 +00001007 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1008 // than a variably modified type.
Steve Naroff5eb879b2007-08-31 17:20:07 +00001009 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1010 Diag(Loc, diag::err_typecheck_illegal_vla,
1011 VAT->getSizeExpr()->getSourceRange());
1012 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001013 }
Chris Lattner4b009652007-07-25 00:24:17 +00001014 // FIXME: Chain fielddecls together.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001015 FieldDecl *NewFD = new FieldDecl(Loc, II, T, 0);
1016 if (D.getInvalidType() || InvalidDecl)
1017 NewFD->setInvalidDecl();
1018 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001019}
1020
1021void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
1022 DeclTy **Fields, unsigned NumFields) {
1023 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
1024 if (Record->isDefinition()) {
1025 // Diagnose code like:
1026 // struct S { struct S {} X; };
1027 // We discover this when we complete the outer S. Reject and ignore the
1028 // outer S.
1029 Diag(Record->getLocation(), diag::err_nested_redefinition,
1030 Record->getKindName());
1031 Diag(RecLoc, diag::err_previous_definition);
1032 return;
1033 }
1034
1035 // Verify that all the fields are okay.
1036 unsigned NumNamedMembers = 0;
1037 llvm::SmallVector<FieldDecl*, 32> RecFields;
1038 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
1039
1040 for (unsigned i = 0; i != NumFields; ++i) {
1041 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1042 if (!FD) continue; // Already issued a diagnostic.
1043
1044 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001045 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +00001046
1047 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001048 if (FDTy->isFunctionType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001049 Diag(FD->getLocation(), diag::err_field_declared_as_function,
1050 FD->getName());
1051 delete FD;
1052 continue;
1053 }
1054
1055 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1056 if (FDTy->isIncompleteType()) {
1057 if (i != NumFields-1 || // ... that the last member ...
1058 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001059 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001060 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1061 delete FD;
1062 continue;
1063 }
1064 if (NumNamedMembers < 1) { //... must have more than named member ...
1065 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1066 FD->getName());
1067 delete FD;
1068 continue;
1069 }
1070
1071 // Okay, we have a legal flexible array member at the end of the struct.
1072 Record->setHasFlexibleArrayMember(true);
1073 }
1074
1075
1076 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1077 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001078 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001079 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1080 // If this is a member of a union, then entire union becomes "flexible".
1081 if (Record->getKind() == Decl::Union) {
1082 Record->setHasFlexibleArrayMember(true);
1083 } else {
1084 // If this is a struct/class and this is not the last element, reject
1085 // it. Note that GCC supports variable sized arrays in the middle of
1086 // structures.
1087 if (i != NumFields-1) {
1088 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1089 FD->getName());
1090 delete FD;
1091 continue;
1092 }
1093
1094 // We support flexible arrays at the end of structs in other structs
1095 // as an extension.
1096 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1097 FD->getName());
1098 Record->setHasFlexibleArrayMember(true);
1099 }
1100 }
1101 }
1102
1103 // Keep track of the number of named members.
1104 if (IdentifierInfo *II = FD->getIdentifier()) {
1105 // Detect duplicate member names.
1106 if (!FieldIDs.insert(II)) {
1107 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1108 // Find the previous decl.
1109 SourceLocation PrevLoc;
1110 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1111 assert(i != e && "Didn't find previous def!");
1112 if (RecFields[i]->getIdentifier() == II) {
1113 PrevLoc = RecFields[i]->getLocation();
1114 break;
1115 }
1116 }
1117 Diag(PrevLoc, diag::err_previous_definition);
1118 delete FD;
1119 continue;
1120 }
1121 ++NumNamedMembers;
1122 }
1123
1124 // Remember good fields.
1125 RecFields.push_back(FD);
1126 }
1127
1128
1129 // Okay, we successfully defined 'Record'.
1130 Record->defineBody(&RecFields[0], RecFields.size());
1131}
1132
1133Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
1134 DeclTy *lastEnumConst,
1135 SourceLocation IdLoc, IdentifierInfo *Id,
1136 SourceLocation EqualLoc, ExprTy *val) {
1137 theEnumDecl = theEnumDecl; // silence unused warning.
1138 EnumConstantDecl *LastEnumConst =
1139 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1140 Expr *Val = static_cast<Expr*>(val);
1141
Chris Lattnera7549902007-08-26 06:24:45 +00001142 // The scope passed in may not be a decl scope. Zip up the scope tree until
1143 // we find one that is.
1144 while ((S->getFlags() & Scope::DeclScope) == 0)
1145 S = S->getParent();
1146
Chris Lattner4b009652007-07-25 00:24:17 +00001147 // Verify that there isn't already something declared with this name in this
1148 // scope.
1149 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
1150 if (S->isDeclScope(PrevDecl)) {
1151 if (isa<EnumConstantDecl>(PrevDecl))
1152 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1153 else
1154 Diag(IdLoc, diag::err_redefinition, Id->getName());
1155 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1156 // FIXME: Don't leak memory: delete Val;
1157 return 0;
1158 }
1159 }
1160
1161 llvm::APSInt EnumVal(32);
1162 QualType EltTy;
1163 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001164 // Make sure to promote the operand type to int.
1165 UsualUnaryConversions(Val);
1166
Chris Lattner4b009652007-07-25 00:24:17 +00001167 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1168 SourceLocation ExpLoc;
1169 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1170 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1171 Id->getName());
1172 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001173 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001174 } else {
1175 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001176 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001177 }
1178
1179 if (!Val) {
1180 if (LastEnumConst) {
1181 // Assign the last value + 1.
1182 EnumVal = LastEnumConst->getInitVal();
1183 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001184
1185 // Check for overflow on increment.
1186 if (EnumVal < LastEnumConst->getInitVal())
1187 Diag(IdLoc, diag::warn_enum_value_overflow);
1188
Chris Lattnere7f53a42007-08-27 17:37:24 +00001189 EltTy = LastEnumConst->getType();
1190 } else {
1191 // First value, set to zero.
1192 EltTy = Context.IntTy;
Chris Lattner2cda8792007-08-27 21:16:18 +00001193 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy, IdLoc));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001194 }
Chris Lattner4b009652007-07-25 00:24:17 +00001195 }
1196
Chris Lattner4b009652007-07-25 00:24:17 +00001197 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1198 LastEnumConst);
1199
1200 // Register this decl in the current scope stack.
1201 New->setNext(Id->getFETokenInfo<Decl>());
1202 Id->setFETokenInfo(New);
1203 S->AddDecl(New);
1204 return New;
1205}
1206
1207void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1208 DeclTy **Elements, unsigned NumElements) {
1209 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1210 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1211
Chris Lattner435c3fd2007-08-28 05:10:31 +00001212 // TODO: If the result value doesn't fit in an int, it must be a long or long
1213 // long value. ISO C does not support this, but GCC does as an extension,
1214 // emit a warning.
Chris Lattner206754a2007-08-28 06:15:15 +00001215 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner435c3fd2007-08-28 05:10:31 +00001216
1217
Chris Lattner206754a2007-08-28 06:15:15 +00001218 // Verify that all the values are okay, compute the size of the values, and
1219 // reverse the list.
1220 unsigned NumNegativeBits = 0;
1221 unsigned NumPositiveBits = 0;
1222
1223 // Keep track of whether all elements have type int.
1224 bool AllElementsInt = true;
1225
Chris Lattner4b009652007-07-25 00:24:17 +00001226 EnumConstantDecl *EltList = 0;
1227 for (unsigned i = 0; i != NumElements; ++i) {
1228 EnumConstantDecl *ECD =
1229 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1230 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001231
1232 // If the enum value doesn't fit in an int, emit an extension warning.
1233 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1234 "Should have promoted value to int");
1235 const llvm::APSInt &InitVal = ECD->getInitVal();
1236 if (InitVal.getBitWidth() > IntWidth) {
1237 llvm::APSInt V(InitVal);
1238 V.trunc(IntWidth);
1239 V.extend(InitVal.getBitWidth());
1240 if (V != InitVal)
1241 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1242 InitVal.toString());
1243 }
Chris Lattner206754a2007-08-28 06:15:15 +00001244
1245 // Keep track of the size of positive and negative values.
1246 if (InitVal.isUnsigned() || !InitVal.isNegative())
1247 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1248 else
1249 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001250
Chris Lattner206754a2007-08-28 06:15:15 +00001251 // Keep track of whether every enum element has type int (very commmon).
1252 if (AllElementsInt)
1253 AllElementsInt = ECD->getType() == Context.IntTy;
1254
Chris Lattner4b009652007-07-25 00:24:17 +00001255 ECD->setNextDeclarator(EltList);
1256 EltList = ECD;
1257 }
1258
Chris Lattner206754a2007-08-28 06:15:15 +00001259 // Figure out the type that should be used for this enum.
1260 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1261 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001262 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001263
1264 if (NumNegativeBits) {
1265 // If there is a negative value, figure out the smallest integer type (of
1266 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001267 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001268 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001269 BestWidth = IntWidth;
1270 } else {
1271 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1272 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001273 BestType = Context.LongTy;
1274 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001275 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1276 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001277 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1278 BestType = Context.LongLongTy;
1279 }
1280 }
1281 } else {
1282 // If there is no negative value, figure out which of uint, ulong, ulonglong
1283 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001284 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001285 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001286 BestWidth = IntWidth;
1287 } else if (NumPositiveBits <=
1288 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattner206754a2007-08-28 06:15:15 +00001289 BestType = Context.UnsignedLongTy;
1290 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001291 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1292 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001293 "How could an initializer get larger than ULL?");
1294 BestType = Context.UnsignedLongLongTy;
1295 }
1296 }
1297
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001298 // Loop over all of the enumerator constants, changing their types to match
1299 // the type of the enum if needed.
1300 for (unsigned i = 0; i != NumElements; ++i) {
1301 EnumConstantDecl *ECD =
1302 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1303 if (!ECD) continue; // Already issued a diagnostic.
1304
1305 // Standard C says the enumerators have int type, but we allow, as an
1306 // extension, the enumerators to be larger than int size. If each
1307 // enumerator value fits in an int, type it as an int, otherwise type it the
1308 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1309 // that X has type 'int', not 'unsigned'.
1310 if (ECD->getType() == Context.IntTy)
1311 continue; // Already int type.
1312
1313 // Determine whether the value fits into an int.
1314 llvm::APSInt InitVal = ECD->getInitVal();
1315 bool FitsInInt;
1316 if (InitVal.isUnsigned() || !InitVal.isNegative())
1317 FitsInInt = InitVal.getActiveBits() < IntWidth;
1318 else
1319 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1320
1321 // If it fits into an integer type, force it. Otherwise force it to match
1322 // the enum decl type.
1323 QualType NewTy;
1324 unsigned NewWidth;
1325 bool NewSign;
1326 if (FitsInInt) {
1327 NewTy = Context.IntTy;
1328 NewWidth = IntWidth;
1329 NewSign = true;
1330 } else if (ECD->getType() == BestType) {
1331 // Already the right type!
1332 continue;
1333 } else {
1334 NewTy = BestType;
1335 NewWidth = BestWidth;
1336 NewSign = BestType->isSignedIntegerType();
1337 }
1338
1339 // Adjust the APSInt value.
1340 InitVal.extOrTrunc(NewWidth);
1341 InitVal.setIsSigned(NewSign);
1342 ECD->setInitVal(InitVal);
1343
1344 // Adjust the Expr initializer and type.
1345 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1346 ECD->setType(NewTy);
1347 }
Chris Lattner206754a2007-08-28 06:15:15 +00001348
Chris Lattner90a018d2007-08-28 18:24:31 +00001349 Enum->defineElements(EltList, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00001350}
1351
1352void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1353 if (!current) return;
1354
1355 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1356 // remember this in the LastInGroupList list.
1357 if (last)
1358 LastInGroupList.push_back((Decl*)last);
1359}
1360
1361void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1362 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1363 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1364 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1365 if (!newType.isNull()) // install the new vector type into the decl
1366 vDecl->setType(newType);
1367 }
1368 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1369 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1370 rawAttr);
1371 if (!newType.isNull()) // install the new vector type into the decl
1372 tDecl->setUnderlyingType(newType);
1373 }
1374 }
1375 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroff82113e32007-07-29 16:33:31 +00001376 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1377 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1378 else
Chris Lattner4b009652007-07-25 00:24:17 +00001379 Diag(rawAttr->getAttributeLoc(),
1380 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner4b009652007-07-25 00:24:17 +00001381 }
1382 // FIXME: add other attributes...
1383}
1384
1385void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1386 AttributeList *declarator_postfix) {
1387 while (declspec_prefix) {
1388 HandleDeclAttribute(New, declspec_prefix);
1389 declspec_prefix = declspec_prefix->getNext();
1390 }
1391 while (declarator_postfix) {
1392 HandleDeclAttribute(New, declarator_postfix);
1393 declarator_postfix = declarator_postfix->getNext();
1394 }
1395}
1396
Steve Naroff82113e32007-07-29 16:33:31 +00001397void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1398 AttributeList *rawAttr) {
1399 QualType curType = tDecl->getUnderlyingType();
Chris Lattner4b009652007-07-25 00:24:17 +00001400 // check the attribute arugments.
1401 if (rawAttr->getNumArgs() != 1) {
1402 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1403 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001404 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001405 }
1406 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1407 llvm::APSInt vecSize(32);
1408 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1409 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1410 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001411 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001412 }
1413 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1414 // in conjunction with complex types (pointers, arrays, functions, etc.).
1415 Type *canonType = curType.getCanonicalType().getTypePtr();
1416 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1417 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1418 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001419 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001420 }
1421 // unlike gcc's vector_size attribute, the size is specified as the
1422 // number of elements, not the number of bytes.
1423 unsigned vectorSize = vecSize.getZExtValue();
1424
1425 if (vectorSize == 0) {
1426 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1427 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001428 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001429 }
Steve Naroff82113e32007-07-29 16:33:31 +00001430 // Instantiate/Install the vector type, the number of elements is > 0.
1431 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1432 // Remember this typedef decl, we will need it later for diagnostics.
1433 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001434}
1435
1436QualType Sema::HandleVectorTypeAttribute(QualType curType,
1437 AttributeList *rawAttr) {
1438 // check the attribute arugments.
1439 if (rawAttr->getNumArgs() != 1) {
1440 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1441 std::string("1"));
1442 return QualType();
1443 }
1444 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1445 llvm::APSInt vecSize(32);
1446 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1447 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1448 sizeExpr->getSourceRange());
1449 return QualType();
1450 }
1451 // navigate to the base type - we need to provide for vector pointers,
1452 // vector arrays, and functions returning vectors.
1453 Type *canonType = curType.getCanonicalType().getTypePtr();
1454
1455 if (canonType->isPointerType() || canonType->isArrayType() ||
1456 canonType->isFunctionType()) {
1457 assert(1 && "HandleVector(): Complex type construction unimplemented");
1458 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1459 do {
1460 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1461 canonType = PT->getPointeeType().getTypePtr();
1462 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1463 canonType = AT->getElementType().getTypePtr();
1464 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1465 canonType = FT->getResultType().getTypePtr();
1466 } while (canonType->isPointerType() || canonType->isArrayType() ||
1467 canonType->isFunctionType());
1468 */
1469 }
1470 // the base type must be integer or float.
1471 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1472 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1473 curType.getCanonicalType().getAsString());
1474 return QualType();
1475 }
1476 unsigned typeSize = Context.getTypeSize(curType, rawAttr->getAttributeLoc());
1477 // vecSize is specified in bytes - convert to bits.
1478 unsigned vectorSize = vecSize.getZExtValue() * 8;
1479
1480 // the vector size needs to be an integral multiple of the type size.
1481 if (vectorSize % typeSize) {
1482 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1483 sizeExpr->getSourceRange());
1484 return QualType();
1485 }
1486 if (vectorSize == 0) {
1487 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1488 sizeExpr->getSourceRange());
1489 return QualType();
1490 }
1491 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1492 // the number of elements to be a power of two (unlike GCC).
1493 // Instantiate the vector type, the number of elements is > 0.
1494 return Context.getVectorType(curType, vectorSize/typeSize);
1495}
1496