blob: b178e099ba21b8a4d0b7789a73e547cf480c4789 [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 Naroffe6a8c9b2007-09-04 14:36:54 +0000242bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000243 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 Naroffe6a8c9b2007-09-04 14:36:54 +0000292bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
293 bool isStatic, QualType ElementType) {
Steve Naroff509d0b52007-09-04 02:20:04 +0000294 SourceLocation loc;
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000295 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff509d0b52007-09-04 02:20:04 +0000296
297 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
298 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
299 return true;
300 } else if (CheckSingleInitializer(expr, ElementType)) {
301 return true; // types weren't compatible.
302 }
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000303 if (savExpr != expr) // The type was promoted, update initializer list.
304 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000305 return false;
306}
307
308void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
309 QualType ElementType, bool isStatic,
310 int &nInitializers, bool &hadError) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000311 for (unsigned i = 0; i < IList->getNumInits(); i++) {
312 Expr *expr = IList->getInit(i);
313
Steve Naroff509d0b52007-09-04 02:20:04 +0000314 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
315 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
316 QualType ElmtType = CAT->getElementType();
317 int maxElements = CAT->getSize().getZExtValue();
318
319 // If we have a multi-dimensional array, navigate to the base type. Also
320 // compute the absolute array, so we can detect excess elements.
321 while ((CAT = ElmtType->getAsConstantArrayType())) {
322 ElmtType = CAT->getElementType();
323 maxElements *= CAT->getSize().getZExtValue();
324 }
325 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
326 maxElements, hadError);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000327 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000328 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000329 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000330 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000331 nInitializers++;
332 }
333 return;
334}
335
336// FIXME: Doesn't deal with arrays of structures yet.
337void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
338 QualType ElementType, bool isStatic,
339 int &totalInits, bool &hadError) {
340 int maxElementsAtThisLevel = 0;
341 int nInitsAtLevel = 0;
342
343 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
344 // We have a constant array type, compute maxElements *at this level*.
345 QualType ElmtType = CAT->getElementType();
346 maxElementsAtThisLevel = CAT->getSize().getZExtValue();
347
348 // Set DeclType, important for correctly handling multi-dimensional arrays.
349 DeclType = ElmtType;
350
351 // If we have a multi-dimensional array, navigate to the base type. Also
352 // compute the absolute size of the array *at this level* array, so we can
353 // detect excess elements.
354 while ((CAT = ElmtType->getAsConstantArrayType())) {
355 ElmtType = CAT->getElementType();
356 maxElementsAtThisLevel *= CAT->getSize().getZExtValue();
357 }
358 } else if (DeclType->isScalarType()) {
359 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
360 IList->getSourceRange());
361 maxElementsAtThisLevel = 1;
362 }
363 // The empty init list "{ }" is treated specially below.
364 unsigned numInits = IList->getNumInits();
365 if (numInits) {
366 for (unsigned i = 0; i < numInits; i++) {
367 Expr *expr = IList->getInit(i);
368
369 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
370 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
371 totalInits, hadError);
372 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000373 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff509d0b52007-09-04 02:20:04 +0000374 nInitsAtLevel++; // increment the number of initializers at this level.
375 totalInits--; // decrement the total number of initializers.
376
377 // Check if we have space for another initializer.
378 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
379 Diag(expr->getLocStart(), diag::warn_excess_initializers,
380 expr->getSourceRange());
381 }
382 }
383 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
384 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
385 } else {
386 // we have an initializer list with no elements.
387 totalInits -= maxElementsAtThisLevel;
388 if (totalInits < 0)
389 Diag(IList->getLocStart(), diag::warn_excess_initializers,
390 IList->getSourceRange());
Steve Naroff9091f3f2007-09-02 15:34:30 +0000391 }
Steve Naroff1c9de712007-09-03 01:24:23 +0000392 return;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000393}
394
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000395bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000396 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroff1c9de712007-09-03 01:24:23 +0000397 if (!InitList)
398 return CheckSingleInitializer(Init, DeclType);
399
Steve Naroffe14e5542007-09-02 02:04:30 +0000400 // We have an InitListExpr, make sure we set the type.
401 Init->setType(DeclType);
Steve Naroff1c9de712007-09-03 01:24:23 +0000402
403 bool hadError = false;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000404
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000405 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
406 // of unknown size ("[]") or an object type that is not a variable array type.
407 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
408 Expr *expr = VAT->getSizeExpr();
Steve Naroff1c9de712007-09-03 01:24:23 +0000409 if (expr)
410 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
411 expr->getSourceRange());
412
413 // We have a VariableArrayType with unknown size.
414 QualType ElmtType = VAT->getElementType();
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000415
Steve Naroff509d0b52007-09-04 02:20:04 +0000416 // Set DeclType, important for correctly handling multi-dimensional arrays.
417 DeclType = ElmtType;
Steve Naroff1c9de712007-09-03 01:24:23 +0000418
Steve Naroff509d0b52007-09-04 02:20:04 +0000419 // If we have a multi-dimensional array, navigate to the base type.
420 // Use getAsArrayType(), since it is illegal for an array to have an
421 // incomplete element type. For example, "int [][]" is illegal.
422 const ArrayType *ATY;
423 while ((ATY = ElmtType->getAsArrayType())) {
424 ElmtType = ATY->getElementType();
425 }
426 int numInits = 0;
427 CheckVariableInitList(DeclType, InitList, ElmtType, isStatic, numInits,
428 hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000429 if (!hadError) {
430 // Return a new array type from the number of initializers (C99 6.7.8p22).
431 llvm::APSInt ConstVal(32);
Steve Naroff509d0b52007-09-04 02:20:04 +0000432 ConstVal = numInits;
433 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroff1c9de712007-09-03 01:24:23 +0000434 ArrayType::Normal, 0);
435 }
436 return hadError;
437 }
438 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
439 QualType ElmtType = CAT->getElementType();
Steve Naroff509d0b52007-09-04 02:20:04 +0000440 int maxElements = CAT->getSize().getZExtValue();
Steve Naroff1c9de712007-09-03 01:24:23 +0000441
442 // If we have a multi-dimensional array, navigate to the base type. Also
443 // compute the absolute size of the array, so we can detect excess elements.
444 while ((CAT = ElmtType->getAsConstantArrayType())) {
445 ElmtType = CAT->getElementType();
Steve Naroff509d0b52007-09-04 02:20:04 +0000446 maxElements *= CAT->getSize().getZExtValue();
Steve Naroff1c9de712007-09-03 01:24:23 +0000447 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000448 CheckConstantInitList(DeclType, InitList, ElmtType, isStatic, maxElements,
449 hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000450 return hadError;
451 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000452 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
453 int maxElements = 1;
454 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
455 hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000456 return hadError;
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000457 }
458 // FIXME: Handle struct/union types.
Steve Naroff1c9de712007-09-03 01:24:23 +0000459 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +0000460}
461
Chris Lattner4b009652007-07-25 00:24:17 +0000462Sema::DeclTy *
463Sema::ParseDeclarator(Scope *S, Declarator &D, ExprTy *init,
464 DeclTy *lastDeclarator) {
465 Decl *LastDeclarator = (Decl*)lastDeclarator;
466 Expr *Init = static_cast<Expr*>(init);
467 IdentifierInfo *II = D.getIdentifier();
468
469 // All of these full declarators require an identifier. If it doesn't have
470 // one, the ParsedFreeStandingDeclSpec action should be used.
471 if (II == 0) {
Chris Lattner87492f42007-08-28 06:17:15 +0000472 Diag(D.getDeclSpec().getSourceRange().Begin(),
473 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000474 D.getDeclSpec().getSourceRange(), D.getSourceRange());
475 return 0;
476 }
477
Chris Lattnera7549902007-08-26 06:24:45 +0000478 // The scope passed in may not be a decl scope. Zip up the scope tree until
479 // we find one that is.
480 while ((S->getFlags() & Scope::DeclScope) == 0)
481 S = S->getParent();
482
Chris Lattner4b009652007-07-25 00:24:17 +0000483 // See if this is a redefinition of a variable in the same scope.
484 Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
485 D.getIdentifierLoc(), S);
486 if (PrevDecl && !S->isDeclScope(PrevDecl))
487 PrevDecl = 0; // If in outer scope, it isn't the same thing.
488
489 Decl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000490 bool InvalidDecl = false;
491
Chris Lattner4b009652007-07-25 00:24:17 +0000492 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
493 assert(Init == 0 && "Can't have initializer for a typedef!");
494 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
495 if (!NewTD) return 0;
496
497 // Handle attributes prior to checking for duplicates in MergeVarDecl
498 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
499 D.getAttributes());
500 // Merge the decl with the existing one if appropriate.
501 if (PrevDecl) {
502 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
503 if (NewTD == 0) return 0;
504 }
505 New = NewTD;
506 if (S->getParent() == 0) {
507 // C99 6.7.7p2: If a typedef name specifies a variably modified type
508 // then it shall have block scope.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000509 if (const VariableArrayType *VAT =
510 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
511 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
512 VAT->getSizeExpr()->getSourceRange());
513 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000514 }
515 }
516 } else if (D.isFunctionDeclarator()) {
517 assert(Init == 0 && "Can't have an initializer for a functiondecl!");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000518
Chris Lattner4b009652007-07-25 00:24:17 +0000519 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000520 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000521
522 FunctionDecl::StorageClass SC;
523 switch (D.getDeclSpec().getStorageClassSpec()) {
524 default: assert(0 && "Unknown storage class!");
525 case DeclSpec::SCS_auto:
526 case DeclSpec::SCS_register:
527 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
528 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000529 InvalidDecl = true;
530 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000531 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
532 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
533 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
534 }
535
536 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000537 D.getDeclSpec().isInlineSpecified(),
Chris Lattner4b009652007-07-25 00:24:17 +0000538 LastDeclarator);
539
540 // Merge the decl with the existing one if appropriate.
541 if (PrevDecl) {
542 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
543 if (NewFD == 0) return 0;
544 }
545 New = NewFD;
546 } else {
547 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffcae537d2007-08-28 18:45:29 +0000548 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000549
550 VarDecl *NewVD;
551 VarDecl::StorageClass SC;
552 switch (D.getDeclSpec().getStorageClassSpec()) {
553 default: assert(0 && "Unknown storage class!");
554 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
555 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
556 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
557 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
558 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
559 }
560 if (S->getParent() == 0) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000561 if (Init) {
562 if (SC == VarDecl::Extern)
563 Diag(D.getIdentifierLoc(), diag::warn_extern_init);
Steve Naroff509d0b52007-09-04 02:20:04 +0000564 if (!D.getInvalidType())
565 CheckInitializer(Init, R, true);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000566 }
Chris Lattner4b009652007-07-25 00:24:17 +0000567 // File scope. C99 6.9.2p2: A declaration of an identifier for and
568 // object that has file scope without an initializer, and without a
569 // storage-class specifier or with the storage-class specifier "static",
570 // constitutes a tentative definition. Note: A tentative definition with
571 // external linkage is valid (C99 6.2.2p5).
572 if (!Init && SC == VarDecl::Static) {
573 // C99 6.9.2p3: If the declaration of an identifier for an object is
574 // a tentative definition and has internal linkage (C99 6.2.2p3), the
575 // declared type shall not be an incomplete type.
576 if (R->isIncompleteType()) {
577 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
578 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000579 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000580 }
581 }
582 // C99 6.9p2: The storage-class specifiers auto and register shall not
583 // appear in the declaration specifiers in an external declaration.
584 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
585 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
586 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000587 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000588 }
Steve Naroff5eb879b2007-08-31 17:20:07 +0000589 if (SC == VarDecl::Static) {
590 // C99 6.7.5.2p2: If an identifier is declared to be an object with
591 // static storage duration, it shall not have a variable length array.
592 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
593 Expr *Size = VLA->getSizeExpr();
594 if (Size || (!Size && !Init)) {
595 // FIXME: Since we don't support initializers yet, we only emit this
596 // error when we don't have an initializer. Once initializers are
597 // implemented, the VLA will change to a CLA.
598 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
599 InvalidDecl = true;
600 }
601 }
Chris Lattner4b009652007-07-25 00:24:17 +0000602 }
603 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000604 } else {
605 if (Init) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000606 if (SC == VarDecl::Extern) { // C99 6.7.8p5
607 Diag(D.getIdentifierLoc(), diag::err_block_extern_cant_init);
608 InvalidDecl = true;
Steve Naroff509d0b52007-09-04 02:20:04 +0000609 } else if (!D.getInvalidType()) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000610 CheckInitializer(Init, R, SC == VarDecl::Static);
611 }
Steve Naroffe14e5542007-09-02 02:04:30 +0000612 }
Chris Lattner4b009652007-07-25 00:24:17 +0000613 // Block scope. C99 6.7p7: If an identifier for an object is declared with
614 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
615 if (SC != VarDecl::Extern) {
616 if (R->isIncompleteType()) {
617 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
618 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000619 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000620 }
621 }
622 if (SC == VarDecl::Static) {
623 // C99 6.7.5.2p2: If an identifier is declared to be an object with
624 // static storage duration, it shall not have a variable length array.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000625 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
626 Expr *Size = VLA->getSizeExpr();
627 if (Size || (!Size && !Init)) {
628 // FIXME: Since we don't support initializers yet, we only emit this
629 // error when we don't have an initializer. Once initializers are
630 // implemented, the VLA will change to a CLA.
631 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffcae537d2007-08-28 18:45:29 +0000632 InvalidDecl = true;
Steve Naroff5eb879b2007-08-31 17:20:07 +0000633 }
Chris Lattner4b009652007-07-25 00:24:17 +0000634 }
635 }
636 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000637 }
Chris Lattner4b009652007-07-25 00:24:17 +0000638 // Handle attributes prior to checking for duplicates in MergeVarDecl
639 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
640 D.getAttributes());
641
642 // Merge the decl with the existing one if appropriate.
643 if (PrevDecl) {
644 NewVD = MergeVarDecl(NewVD, PrevDecl);
645 if (NewVD == 0) return 0;
646 }
Steve Naroffe14e5542007-09-02 02:04:30 +0000647 if (Init) { // FIXME: This will likely move up above...for now, it stays.
Steve Naroff0f32f432007-08-24 22:33:52 +0000648 NewVD->setInit(Init);
649 }
Chris Lattner4b009652007-07-25 00:24:17 +0000650 New = NewVD;
651 }
652
653 // If this has an identifier, add it to the scope stack.
654 if (II) {
655 New->setNext(II->getFETokenInfo<Decl>());
656 II->setFETokenInfo(New);
657 S->AddDecl(New);
658 }
659
660 if (S->getParent() == 0)
661 AddTopLevelDecl(New, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000662
663 // If any semantic error occurred, mark the decl as invalid.
664 if (D.getInvalidType() || InvalidDecl)
665 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000666
667 return New;
668}
669
670/// The declarators are chained together backwards, reverse the list.
671Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
672 // Often we have single declarators, handle them quickly.
673 Decl *Group = static_cast<Decl*>(group);
674 if (Group == 0 || Group->getNextDeclarator() == 0) return Group;
675
676 Decl *NewGroup = 0;
677 while (Group) {
678 Decl *Next = Group->getNextDeclarator();
679 Group->setNextDeclarator(NewGroup);
680 NewGroup = Group;
681 Group = Next;
682 }
683 return NewGroup;
684}
Steve Naroff91b03f72007-08-28 03:03:08 +0000685
686// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000687ParmVarDecl *
688Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
689 Scope *FnScope) {
690 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
691
692 IdentifierInfo *II = PI.Ident;
693 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
694 // Can this happen for params? We already checked that they don't conflict
695 // among each other. Here they can only shadow globals, which is ok.
696 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
697 PI.IdentLoc, FnScope)) {
698
699 }
700
701 // FIXME: Handle storage class (auto, register). No declarator?
702 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000703
704 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
705 // Doing the promotion here has a win and a loss. The win is the type for
706 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
707 // code generator). The loss is the orginal type isn't preserved. For example:
708 //
709 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
710 // int blockvardecl[5];
711 // sizeof(parmvardecl); // size == 4
712 // sizeof(blockvardecl); // size == 20
713 // }
714 //
715 // For expressions, all implicit conversions are captured using the
716 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
717 //
718 // FIXME: If a source translation tool needs to see the original type, then
719 // we need to consider storing both types (in ParmVarDecl)...
720 //
721 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
722 if (const ArrayType *AT = parmDeclType->getAsArrayType())
723 parmDeclType = Context.getPointerType(AT->getElementType());
724 else if (parmDeclType->isFunctionType())
725 parmDeclType = Context.getPointerType(parmDeclType);
726
727 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffcae537d2007-08-28 18:45:29 +0000728 VarDecl::None, 0);
729 if (PI.InvalidType)
730 New->setInvalidDecl();
731
Chris Lattner4b009652007-07-25 00:24:17 +0000732 // If this has an identifier, add it to the scope stack.
733 if (II) {
734 New->setNext(II->getFETokenInfo<Decl>());
735 II->setFETokenInfo(New);
736 FnScope->AddDecl(New);
737 }
738
739 return New;
740}
741
742
743Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
744 assert(CurFunctionDecl == 0 && "Function parsing confused");
745 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
746 "Not a function declarator!");
747 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
748
749 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
750 // for a K&R function.
751 if (!FTI.hasPrototype) {
752 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
753 if (FTI.ArgInfo[i].TypeInfo == 0) {
754 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
755 FTI.ArgInfo[i].Ident->getName());
756 // Implicitly declare the argument as type 'int' for lack of a better
757 // type.
758 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
759 }
760 }
761
762 // Since this is a function definition, act as though we have information
763 // about the arguments.
764 FTI.hasPrototype = true;
765 } else {
766 // FIXME: Diagnose arguments without names in C.
767
768 }
769
770 Scope *GlobalScope = FnBodyScope->getParent();
771
772 FunctionDecl *FD =
773 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0, 0));
774 CurFunctionDecl = FD;
775
776 // Create Decl objects for each parameter, adding them to the FunctionDecl.
777 llvm::SmallVector<ParmVarDecl*, 16> Params;
778
779 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
780 // no arguments, not a function that takes a single void argument.
781 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
782 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
783 // empty arg list, don't push any params.
784 } else {
785 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
786 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
787 }
788
789 FD->setParams(&Params[0], Params.size());
790
791 return FD;
792}
793
794Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
795 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
796 FD->setBody((Stmt*)Body);
797
798 assert(FD == CurFunctionDecl && "Function parsing confused");
799 CurFunctionDecl = 0;
800
801 // Verify and clean out per-function state.
802
803 // Check goto/label use.
804 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
805 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
806 // Verify that we have no forward references left. If so, there was a goto
807 // or address of a label taken, but no definition of it. Label fwd
808 // definitions are indicated with a null substmt.
809 if (I->second->getSubStmt() == 0) {
810 LabelStmt *L = I->second;
811 // Emit error.
812 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
813
814 // At this point, we have gotos that use the bogus label. Stitch it into
815 // the function body so that they aren't leaked and that the AST is well
816 // formed.
817 L->setSubStmt(new NullStmt(L->getIdentLoc()));
818 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
819 }
820 }
821 LabelMap.clear();
822
823 return FD;
824}
825
826
827/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
828/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
829Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
830 Scope *S) {
831 if (getLangOptions().C99) // Extension in C99.
832 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
833 else // Legal in C90, but warn about it.
834 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
835
836 // FIXME: handle stuff like:
837 // void foo() { extern float X(); }
838 // void bar() { X(); } <-- implicit decl for X in another scope.
839
840 // Set a Declarator for the implicit definition: int foo();
841 const char *Dummy;
842 DeclSpec DS;
843 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
844 Error = Error; // Silence warning.
845 assert(!Error && "Error setting up implicit decl!");
846 Declarator D(DS, Declarator::BlockContext);
847 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
848 D.SetIdentifier(&II, Loc);
849
850 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000851 if (Scope *FnS = S->getFnParent())
852 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000853 while (S->getParent())
854 S = S->getParent();
855
856 return static_cast<Decl*>(ParseDeclarator(S, D, 0, 0));
857}
858
859
860TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
861 Decl *LastDeclarator) {
862 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
863
864 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000865 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000866
867 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000868 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
869 T, LastDeclarator);
870 if (D.getInvalidType())
871 NewTD->setInvalidDecl();
872 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +0000873}
874
875
876/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
877/// former case, Name will be non-null. In the later case, Name will be null.
878/// TagType indicates what kind of tag this is. TK indicates whether this is a
879/// reference/declaration/definition of a tag.
880Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
881 SourceLocation KWLoc, IdentifierInfo *Name,
882 SourceLocation NameLoc, AttributeList *Attr) {
883 // If this is a use of an existing tag, it must have a name.
884 assert((Name != 0 || TK == TK_Definition) &&
885 "Nameless record must be a definition!");
886
887 Decl::Kind Kind;
888 switch (TagType) {
889 default: assert(0 && "Unknown tag type!");
890 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
891 case DeclSpec::TST_union: Kind = Decl::Union; break;
892//case DeclSpec::TST_class: Kind = Decl::Class; break;
893 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
894 }
895
896 // If this is a named struct, check to see if there was a previous forward
897 // declaration or definition.
898 if (TagDecl *PrevDecl =
899 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
900 NameLoc, S))) {
901
902 // If this is a use of a previous tag, or if the tag is already declared in
903 // the same scope (so that the definition/declaration completes or
904 // rementions the tag), reuse the decl.
905 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
906 // Make sure that this wasn't declared as an enum and now used as a struct
907 // or something similar.
908 if (PrevDecl->getKind() != Kind) {
909 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
910 Diag(PrevDecl->getLocation(), diag::err_previous_use);
911 }
912
913 // If this is a use or a forward declaration, we're good.
914 if (TK != TK_Definition)
915 return PrevDecl;
916
917 // Diagnose attempts to redefine a tag.
918 if (PrevDecl->isDefinition()) {
919 Diag(NameLoc, diag::err_redefinition, Name->getName());
920 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
921 // If this is a redefinition, recover by making this struct be
922 // anonymous, which will make any later references get the previous
923 // definition.
924 Name = 0;
925 } else {
926 // Okay, this is definition of a previously declared or referenced tag.
927 // Move the location of the decl to be the definition site.
928 PrevDecl->setLocation(NameLoc);
929 return PrevDecl;
930 }
931 }
932 // If we get here, this is a definition of a new struct type in a nested
933 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
934 // type.
935 }
936
937 // If there is an identifier, use the location of the identifier as the
938 // location of the decl, otherwise use the location of the struct/union
939 // keyword.
940 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
941
942 // Otherwise, if this is the first time we've seen this tag, create the decl.
943 TagDecl *New;
944 switch (Kind) {
945 default: assert(0 && "Unknown tag kind!");
946 case Decl::Enum:
947 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
948 // enum X { A, B, C } D; D should chain to X.
949 New = new EnumDecl(Loc, Name, 0);
950 // If this is an undefined enum, warn.
951 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
952 break;
953 case Decl::Union:
954 case Decl::Struct:
955 case Decl::Class:
956 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
957 // struct X { int A; } D; D should chain to X.
958 New = new RecordDecl(Kind, Loc, Name, 0);
959 break;
960 }
961
962 // If this has an identifier, add it to the scope stack.
963 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +0000964 // The scope passed in may not be a decl scope. Zip up the scope tree until
965 // we find one that is.
966 while ((S->getFlags() & Scope::DeclScope) == 0)
967 S = S->getParent();
968
969 // Add it to the decl chain.
Chris Lattner4b009652007-07-25 00:24:17 +0000970 New->setNext(Name->getFETokenInfo<Decl>());
971 Name->setFETokenInfo(New);
972 S->AddDecl(New);
973 }
974
975 return New;
976}
977
978/// ParseField - Each field of a struct/union/class is passed into this in order
979/// to create a FieldDecl object for it.
980Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
981 SourceLocation DeclStart,
982 Declarator &D, ExprTy *BitfieldWidth) {
983 IdentifierInfo *II = D.getIdentifier();
984 Expr *BitWidth = (Expr*)BitfieldWidth;
985
986 SourceLocation Loc = DeclStart;
987 if (II) Loc = D.getIdentifierLoc();
988
989 // FIXME: Unnamed fields can be handled in various different ways, for
990 // example, unnamed unions inject all members into the struct namespace!
991
992
993 if (BitWidth) {
994 // TODO: Validate.
995 //printf("WARNING: BITFIELDS IGNORED!\n");
996
997 // 6.7.2.1p3
998 // 6.7.2.1p4
999
1000 } else {
1001 // Not a bitfield.
1002
1003 // validate II.
1004
1005 }
1006
1007 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001008 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1009 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001010
Chris Lattner4b009652007-07-25 00:24:17 +00001011 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1012 // than a variably modified type.
Steve Naroff5eb879b2007-08-31 17:20:07 +00001013 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1014 Diag(Loc, diag::err_typecheck_illegal_vla,
1015 VAT->getSizeExpr()->getSourceRange());
1016 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001017 }
Chris Lattner4b009652007-07-25 00:24:17 +00001018 // FIXME: Chain fielddecls together.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001019 FieldDecl *NewFD = new FieldDecl(Loc, II, T, 0);
1020 if (D.getInvalidType() || InvalidDecl)
1021 NewFD->setInvalidDecl();
1022 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001023}
1024
1025void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
1026 DeclTy **Fields, unsigned NumFields) {
1027 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
1028 if (Record->isDefinition()) {
1029 // Diagnose code like:
1030 // struct S { struct S {} X; };
1031 // We discover this when we complete the outer S. Reject and ignore the
1032 // outer S.
1033 Diag(Record->getLocation(), diag::err_nested_redefinition,
1034 Record->getKindName());
1035 Diag(RecLoc, diag::err_previous_definition);
1036 return;
1037 }
1038
1039 // Verify that all the fields are okay.
1040 unsigned NumNamedMembers = 0;
1041 llvm::SmallVector<FieldDecl*, 32> RecFields;
1042 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
1043
1044 for (unsigned i = 0; i != NumFields; ++i) {
1045 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1046 if (!FD) continue; // Already issued a diagnostic.
1047
1048 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001049 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +00001050
1051 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001052 if (FDTy->isFunctionType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001053 Diag(FD->getLocation(), diag::err_field_declared_as_function,
1054 FD->getName());
1055 delete FD;
1056 continue;
1057 }
1058
1059 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1060 if (FDTy->isIncompleteType()) {
1061 if (i != NumFields-1 || // ... that the last member ...
1062 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001063 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001064 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1065 delete FD;
1066 continue;
1067 }
1068 if (NumNamedMembers < 1) { //... must have more than named member ...
1069 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1070 FD->getName());
1071 delete FD;
1072 continue;
1073 }
1074
1075 // Okay, we have a legal flexible array member at the end of the struct.
1076 Record->setHasFlexibleArrayMember(true);
1077 }
1078
1079
1080 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1081 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001082 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001083 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1084 // If this is a member of a union, then entire union becomes "flexible".
1085 if (Record->getKind() == Decl::Union) {
1086 Record->setHasFlexibleArrayMember(true);
1087 } else {
1088 // If this is a struct/class and this is not the last element, reject
1089 // it. Note that GCC supports variable sized arrays in the middle of
1090 // structures.
1091 if (i != NumFields-1) {
1092 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1093 FD->getName());
1094 delete FD;
1095 continue;
1096 }
1097
1098 // We support flexible arrays at the end of structs in other structs
1099 // as an extension.
1100 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1101 FD->getName());
1102 Record->setHasFlexibleArrayMember(true);
1103 }
1104 }
1105 }
1106
1107 // Keep track of the number of named members.
1108 if (IdentifierInfo *II = FD->getIdentifier()) {
1109 // Detect duplicate member names.
1110 if (!FieldIDs.insert(II)) {
1111 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1112 // Find the previous decl.
1113 SourceLocation PrevLoc;
1114 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1115 assert(i != e && "Didn't find previous def!");
1116 if (RecFields[i]->getIdentifier() == II) {
1117 PrevLoc = RecFields[i]->getLocation();
1118 break;
1119 }
1120 }
1121 Diag(PrevLoc, diag::err_previous_definition);
1122 delete FD;
1123 continue;
1124 }
1125 ++NumNamedMembers;
1126 }
1127
1128 // Remember good fields.
1129 RecFields.push_back(FD);
1130 }
1131
1132
1133 // Okay, we successfully defined 'Record'.
1134 Record->defineBody(&RecFields[0], RecFields.size());
1135}
1136
1137Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
1138 DeclTy *lastEnumConst,
1139 SourceLocation IdLoc, IdentifierInfo *Id,
1140 SourceLocation EqualLoc, ExprTy *val) {
1141 theEnumDecl = theEnumDecl; // silence unused warning.
1142 EnumConstantDecl *LastEnumConst =
1143 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1144 Expr *Val = static_cast<Expr*>(val);
1145
Chris Lattnera7549902007-08-26 06:24:45 +00001146 // The scope passed in may not be a decl scope. Zip up the scope tree until
1147 // we find one that is.
1148 while ((S->getFlags() & Scope::DeclScope) == 0)
1149 S = S->getParent();
1150
Chris Lattner4b009652007-07-25 00:24:17 +00001151 // Verify that there isn't already something declared with this name in this
1152 // scope.
1153 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
1154 if (S->isDeclScope(PrevDecl)) {
1155 if (isa<EnumConstantDecl>(PrevDecl))
1156 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1157 else
1158 Diag(IdLoc, diag::err_redefinition, Id->getName());
1159 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1160 // FIXME: Don't leak memory: delete Val;
1161 return 0;
1162 }
1163 }
1164
1165 llvm::APSInt EnumVal(32);
1166 QualType EltTy;
1167 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001168 // Make sure to promote the operand type to int.
1169 UsualUnaryConversions(Val);
1170
Chris Lattner4b009652007-07-25 00:24:17 +00001171 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1172 SourceLocation ExpLoc;
1173 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1174 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1175 Id->getName());
1176 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001177 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001178 } else {
1179 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001180 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001181 }
1182
1183 if (!Val) {
1184 if (LastEnumConst) {
1185 // Assign the last value + 1.
1186 EnumVal = LastEnumConst->getInitVal();
1187 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001188
1189 // Check for overflow on increment.
1190 if (EnumVal < LastEnumConst->getInitVal())
1191 Diag(IdLoc, diag::warn_enum_value_overflow);
1192
Chris Lattnere7f53a42007-08-27 17:37:24 +00001193 EltTy = LastEnumConst->getType();
1194 } else {
1195 // First value, set to zero.
1196 EltTy = Context.IntTy;
Chris Lattner3496d522007-09-04 02:45:27 +00001197 EnumVal.zextOrTrunc(
1198 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001199 }
Chris Lattner4b009652007-07-25 00:24:17 +00001200 }
1201
Chris Lattner4b009652007-07-25 00:24:17 +00001202 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1203 LastEnumConst);
1204
1205 // Register this decl in the current scope stack.
1206 New->setNext(Id->getFETokenInfo<Decl>());
1207 Id->setFETokenInfo(New);
1208 S->AddDecl(New);
1209 return New;
1210}
1211
1212void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1213 DeclTy **Elements, unsigned NumElements) {
1214 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1215 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1216
Chris Lattner435c3fd2007-08-28 05:10:31 +00001217 // TODO: If the result value doesn't fit in an int, it must be a long or long
1218 // long value. ISO C does not support this, but GCC does as an extension,
1219 // emit a warning.
Chris Lattner206754a2007-08-28 06:15:15 +00001220 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner435c3fd2007-08-28 05:10:31 +00001221
1222
Chris Lattner206754a2007-08-28 06:15:15 +00001223 // Verify that all the values are okay, compute the size of the values, and
1224 // reverse the list.
1225 unsigned NumNegativeBits = 0;
1226 unsigned NumPositiveBits = 0;
1227
1228 // Keep track of whether all elements have type int.
1229 bool AllElementsInt = true;
1230
Chris Lattner4b009652007-07-25 00:24:17 +00001231 EnumConstantDecl *EltList = 0;
1232 for (unsigned i = 0; i != NumElements; ++i) {
1233 EnumConstantDecl *ECD =
1234 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1235 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001236
1237 // If the enum value doesn't fit in an int, emit an extension warning.
1238 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1239 "Should have promoted value to int");
1240 const llvm::APSInt &InitVal = ECD->getInitVal();
1241 if (InitVal.getBitWidth() > IntWidth) {
1242 llvm::APSInt V(InitVal);
1243 V.trunc(IntWidth);
1244 V.extend(InitVal.getBitWidth());
1245 if (V != InitVal)
1246 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1247 InitVal.toString());
1248 }
Chris Lattner206754a2007-08-28 06:15:15 +00001249
1250 // Keep track of the size of positive and negative values.
1251 if (InitVal.isUnsigned() || !InitVal.isNegative())
1252 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1253 else
1254 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001255
Chris Lattner206754a2007-08-28 06:15:15 +00001256 // Keep track of whether every enum element has type int (very commmon).
1257 if (AllElementsInt)
1258 AllElementsInt = ECD->getType() == Context.IntTy;
1259
Chris Lattner4b009652007-07-25 00:24:17 +00001260 ECD->setNextDeclarator(EltList);
1261 EltList = ECD;
1262 }
1263
Chris Lattner206754a2007-08-28 06:15:15 +00001264 // Figure out the type that should be used for this enum.
1265 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1266 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001267 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001268
1269 if (NumNegativeBits) {
1270 // If there is a negative value, figure out the smallest integer type (of
1271 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001272 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001273 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001274 BestWidth = IntWidth;
1275 } else {
1276 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1277 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001278 BestType = Context.LongTy;
1279 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001280 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1281 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001282 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1283 BestType = Context.LongLongTy;
1284 }
1285 }
1286 } else {
1287 // If there is no negative value, figure out which of uint, ulong, ulonglong
1288 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001289 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001290 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001291 BestWidth = IntWidth;
1292 } else if (NumPositiveBits <=
1293 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattner206754a2007-08-28 06:15:15 +00001294 BestType = Context.UnsignedLongTy;
1295 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001296 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1297 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001298 "How could an initializer get larger than ULL?");
1299 BestType = Context.UnsignedLongLongTy;
1300 }
1301 }
1302
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001303 // Loop over all of the enumerator constants, changing their types to match
1304 // the type of the enum if needed.
1305 for (unsigned i = 0; i != NumElements; ++i) {
1306 EnumConstantDecl *ECD =
1307 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1308 if (!ECD) continue; // Already issued a diagnostic.
1309
1310 // Standard C says the enumerators have int type, but we allow, as an
1311 // extension, the enumerators to be larger than int size. If each
1312 // enumerator value fits in an int, type it as an int, otherwise type it the
1313 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1314 // that X has type 'int', not 'unsigned'.
1315 if (ECD->getType() == Context.IntTy)
1316 continue; // Already int type.
1317
1318 // Determine whether the value fits into an int.
1319 llvm::APSInt InitVal = ECD->getInitVal();
1320 bool FitsInInt;
1321 if (InitVal.isUnsigned() || !InitVal.isNegative())
1322 FitsInInt = InitVal.getActiveBits() < IntWidth;
1323 else
1324 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1325
1326 // If it fits into an integer type, force it. Otherwise force it to match
1327 // the enum decl type.
1328 QualType NewTy;
1329 unsigned NewWidth;
1330 bool NewSign;
1331 if (FitsInInt) {
1332 NewTy = Context.IntTy;
1333 NewWidth = IntWidth;
1334 NewSign = true;
1335 } else if (ECD->getType() == BestType) {
1336 // Already the right type!
1337 continue;
1338 } else {
1339 NewTy = BestType;
1340 NewWidth = BestWidth;
1341 NewSign = BestType->isSignedIntegerType();
1342 }
1343
1344 // Adjust the APSInt value.
1345 InitVal.extOrTrunc(NewWidth);
1346 InitVal.setIsSigned(NewSign);
1347 ECD->setInitVal(InitVal);
1348
1349 // Adjust the Expr initializer and type.
1350 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1351 ECD->setType(NewTy);
1352 }
Chris Lattner206754a2007-08-28 06:15:15 +00001353
Chris Lattner90a018d2007-08-28 18:24:31 +00001354 Enum->defineElements(EltList, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00001355}
1356
1357void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1358 if (!current) return;
1359
1360 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1361 // remember this in the LastInGroupList list.
1362 if (last)
1363 LastInGroupList.push_back((Decl*)last);
1364}
1365
1366void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1367 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1368 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1369 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1370 if (!newType.isNull()) // install the new vector type into the decl
1371 vDecl->setType(newType);
1372 }
1373 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1374 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1375 rawAttr);
1376 if (!newType.isNull()) // install the new vector type into the decl
1377 tDecl->setUnderlyingType(newType);
1378 }
1379 }
1380 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroff82113e32007-07-29 16:33:31 +00001381 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1382 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1383 else
Chris Lattner4b009652007-07-25 00:24:17 +00001384 Diag(rawAttr->getAttributeLoc(),
1385 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner4b009652007-07-25 00:24:17 +00001386 }
1387 // FIXME: add other attributes...
1388}
1389
1390void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1391 AttributeList *declarator_postfix) {
1392 while (declspec_prefix) {
1393 HandleDeclAttribute(New, declspec_prefix);
1394 declspec_prefix = declspec_prefix->getNext();
1395 }
1396 while (declarator_postfix) {
1397 HandleDeclAttribute(New, declarator_postfix);
1398 declarator_postfix = declarator_postfix->getNext();
1399 }
1400}
1401
Steve Naroff82113e32007-07-29 16:33:31 +00001402void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1403 AttributeList *rawAttr) {
1404 QualType curType = tDecl->getUnderlyingType();
Chris Lattner4b009652007-07-25 00:24:17 +00001405 // check the attribute arugments.
1406 if (rawAttr->getNumArgs() != 1) {
1407 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1408 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001409 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001410 }
1411 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1412 llvm::APSInt vecSize(32);
1413 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1414 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1415 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001416 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001417 }
1418 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1419 // in conjunction with complex types (pointers, arrays, functions, etc.).
1420 Type *canonType = curType.getCanonicalType().getTypePtr();
1421 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1422 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1423 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001424 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001425 }
1426 // unlike gcc's vector_size attribute, the size is specified as the
1427 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00001428 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00001429
1430 if (vectorSize == 0) {
1431 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1432 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001433 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001434 }
Steve Naroff82113e32007-07-29 16:33:31 +00001435 // Instantiate/Install the vector type, the number of elements is > 0.
1436 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1437 // Remember this typedef decl, we will need it later for diagnostics.
1438 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001439}
1440
1441QualType Sema::HandleVectorTypeAttribute(QualType curType,
1442 AttributeList *rawAttr) {
1443 // check the attribute arugments.
1444 if (rawAttr->getNumArgs() != 1) {
1445 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1446 std::string("1"));
1447 return QualType();
1448 }
1449 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1450 llvm::APSInt vecSize(32);
1451 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1452 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1453 sizeExpr->getSourceRange());
1454 return QualType();
1455 }
1456 // navigate to the base type - we need to provide for vector pointers,
1457 // vector arrays, and functions returning vectors.
1458 Type *canonType = curType.getCanonicalType().getTypePtr();
1459
1460 if (canonType->isPointerType() || canonType->isArrayType() ||
1461 canonType->isFunctionType()) {
1462 assert(1 && "HandleVector(): Complex type construction unimplemented");
1463 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1464 do {
1465 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1466 canonType = PT->getPointeeType().getTypePtr();
1467 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1468 canonType = AT->getElementType().getTypePtr();
1469 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1470 canonType = FT->getResultType().getTypePtr();
1471 } while (canonType->isPointerType() || canonType->isArrayType() ||
1472 canonType->isFunctionType());
1473 */
1474 }
1475 // the base type must be integer or float.
1476 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1477 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1478 curType.getCanonicalType().getAsString());
1479 return QualType();
1480 }
Chris Lattner3496d522007-09-04 02:45:27 +00001481 unsigned typeSize = static_cast<unsigned>(
1482 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Chris Lattner4b009652007-07-25 00:24:17 +00001483 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00001484 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00001485
1486 // the vector size needs to be an integral multiple of the type size.
1487 if (vectorSize % typeSize) {
1488 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1489 sizeExpr->getSourceRange());
1490 return QualType();
1491 }
1492 if (vectorSize == 0) {
1493 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1494 sizeExpr->getSourceRange());
1495 return QualType();
1496 }
1497 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1498 // the number of elements to be a power of two (unlike GCC).
1499 // Instantiate the vector type, the number of elements is > 0.
1500 return Context.getVectorType(curType, vectorSize/typeSize);
1501}
1502