blob: 50cde4e410dc71ee44154994feedd6322f1a9ab0 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Builtins.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/Type.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Parse/Scope.h"
22#include "clang/Lex/IdentifierTable.h"
23#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
25#include "llvm/ADT/SmallSet.h"
26using namespace clang;
27
Reid Spencer5f016e22007-07-11 17:01:13 +000028Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Steve Naroff3536b442007-09-06 21:24:23 +000029 Decl *IIDecl = II.getFETokenInfo<Decl>();
30 if (dyn_cast_or_null<TypedefDecl>(IIDecl) ||
31 dyn_cast_or_null<ObjcInterfaceDecl>(IIDecl))
32 return IIDecl;
33 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000034}
35
36void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000037 if (S->decl_empty()) return;
38 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
39
Reid Spencer5f016e22007-07-11 17:01:13 +000040 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
41 I != E; ++I) {
42 Decl *D = static_cast<Decl*>(*I);
43 assert(D && "This decl didn't get pushed??");
44 IdentifierInfo *II = D->getIdentifier();
45 if (!II) continue;
46
47 // Unlink this decl from the identifier. Because the scope contains decls
48 // in an unordered collection, and because we have multiple identifier
49 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
50 if (II->getFETokenInfo<Decl>() == D) {
51 // Normal case, no multiple decls in different namespaces.
52 II->setFETokenInfo(D->getNext());
53 } else {
54 // Scan ahead. There are only three namespaces in C, so this loop can
55 // never execute more than 3 times.
56 Decl *SomeDecl = II->getFETokenInfo<Decl>();
57 while (SomeDecl->getNext() != D) {
58 SomeDecl = SomeDecl->getNext();
59 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
60 }
61 SomeDecl->setNext(D->getNext());
62 }
63
64 // This will have to be revisited for C++: there we want to nest stuff in
65 // namespace decls etc. Even for C, we might want a top-level translation
66 // unit decl or something.
67 if (!CurFunctionDecl)
68 continue;
69
70 // Chain this decl to the containing function, it now owns the memory for
71 // the decl.
72 D->setNext(CurFunctionDecl->getDeclChain());
73 CurFunctionDecl->setDeclChain(D);
74 }
75}
76
77/// LookupScopedDecl - Look up the inner-most declaration in the specified
78/// namespace.
79Decl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
80 SourceLocation IdLoc, Scope *S) {
81 if (II == 0) return 0;
82 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
83
84 // Scan up the scope chain looking for a decl that matches this identifier
85 // that is in the appropriate namespace. This search should not take long, as
86 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
87 for (Decl *D = II->getFETokenInfo<Decl>(); D; D = D->getNext())
88 if (D->getIdentifierNamespace() == NS)
89 return D;
90
91 // If we didn't find a use of this identifier, and if the identifier
92 // corresponds to a compiler builtin, create the decl object for the builtin
93 // now, injecting it into translation unit scope, and return it.
94 if (NS == Decl::IDNS_Ordinary) {
95 // If this is a builtin on some other target, or if this builtin varies
96 // across targets (e.g. in type), emit a diagnostic and mark the translation
97 // unit non-portable for using it.
98 if (II->isNonPortableBuiltin()) {
99 // Only emit this diagnostic once for this builtin.
100 II->setNonPortableBuiltin(false);
101 Context.Target.DiagnoseNonPortability(IdLoc,
102 diag::port_target_builtin_use);
103 }
104 // If this is a builtin on this (or all) targets, create the decl.
105 if (unsigned BuiltinID = II->getBuiltinID())
106 return LazilyCreateBuiltin(II, BuiltinID, S);
107 }
108 return 0;
109}
110
111/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
112/// lazily create a decl for it.
113Decl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
114 Builtin::ID BID = (Builtin::ID)bid;
115
116 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
117 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000118 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000119
120 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000121 if (Scope *FnS = S->getFnParent())
122 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 while (S->getParent())
124 S = S->getParent();
125 S->AddDecl(New);
126
127 // Add this decl to the end of the identifier info.
128 if (Decl *LastDecl = II->getFETokenInfo<Decl>()) {
129 // Scan until we find the last (outermost) decl in the id chain.
130 while (LastDecl->getNext())
131 LastDecl = LastDecl->getNext();
132 // Insert before (outside) it.
133 LastDecl->setNext(New);
134 } else {
135 II->setFETokenInfo(New);
136 }
137 // Make sure clients iterating over decls see this.
138 LastInGroupList.push_back(New);
139
140 return New;
141}
142
143/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
144/// and scope as a previous declaration 'Old'. Figure out how to resolve this
145/// situation, merging decls or emitting diagnostics as appropriate.
146///
147TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
148 // Verify the old decl was also a typedef.
149 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
150 if (!Old) {
151 Diag(New->getLocation(), diag::err_redefinition_different_kind,
152 New->getName());
153 Diag(OldD->getLocation(), diag::err_previous_definition);
154 return New;
155 }
156
157 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
158 // TODO: This is totally simplistic. It should handle merging functions
159 // together etc, merging extern int X; int X; ...
160 Diag(New->getLocation(), diag::err_redefinition, New->getName());
161 Diag(Old->getLocation(), diag::err_previous_definition);
162 return New;
163}
164
165/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
166/// and scope as a previous declaration 'Old'. Figure out how to resolve this
167/// situation, merging decls or emitting diagnostics as appropriate.
168///
169FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
170 // Verify the old decl was also a function.
171 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
172 if (!Old) {
173 Diag(New->getLocation(), diag::err_redefinition_different_kind,
174 New->getName());
175 Diag(OldD->getLocation(), diag::err_previous_definition);
176 return New;
177 }
178
179 // This is not right, but it's a start. If 'Old' is a function prototype with
180 // the same type as 'New', silently allow this. FIXME: We should link up decl
181 // objects here.
182 if (Old->getBody() == 0 &&
183 Old->getCanonicalType() == New->getCanonicalType()) {
184 return New;
185 }
186
187 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
188 // TODO: This is totally simplistic. It should handle merging functions
189 // together etc, merging extern int X; int X; ...
190 Diag(New->getLocation(), diag::err_redefinition, New->getName());
191 Diag(Old->getLocation(), diag::err_previous_definition);
192 return New;
193}
194
195/// MergeVarDecl - We just parsed a variable 'New' which has the same name
196/// and scope as a previous declaration 'Old'. Figure out how to resolve this
197/// situation, merging decls or emitting diagnostics as appropriate.
198///
199/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
200/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
201///
202VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
203 // Verify the old decl was also a variable.
204 VarDecl *Old = dyn_cast<VarDecl>(OldD);
205 if (!Old) {
206 Diag(New->getLocation(), diag::err_redefinition_different_kind,
207 New->getName());
208 Diag(OldD->getLocation(), diag::err_previous_definition);
209 return New;
210 }
Steve Narofffb22d962007-08-30 01:06:46 +0000211 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
212 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
213 bool OldIsTentative = false;
214
215 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
216 // Handle C "tentative" external object definitions. FIXME: finish!
217 if (!OldFSDecl->getInit() &&
218 (OldFSDecl->getStorageClass() == VarDecl::None ||
219 OldFSDecl->getStorageClass() == VarDecl::Static))
220 OldIsTentative = true;
221 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000222 // Verify the types match.
223 if (Old->getCanonicalType() != New->getCanonicalType()) {
224 Diag(New->getLocation(), diag::err_redefinition, New->getName());
225 Diag(Old->getLocation(), diag::err_previous_definition);
226 return New;
227 }
228 // We've verified the types match, now check if Old is "extern".
229 if (Old->getStorageClass() != VarDecl::Extern) {
230 Diag(New->getLocation(), diag::err_redefinition, New->getName());
231 Diag(Old->getLocation(), diag::err_previous_definition);
232 }
233 return New;
234}
235
236/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
237/// no declarator (e.g. "struct foo;") is parsed.
238Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
239 // TODO: emit error on 'int;' or 'const enum foo;'.
240 // TODO: emit error on 'typedef int;'
241 // if (!DS.isMissingDeclaratorOk()) Diag(...);
242
243 return 0;
244}
245
Steve Naroff9e8925e2007-09-04 14:36:54 +0000246bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000247 AssignmentCheckResult result;
248 SourceLocation loc = Init->getLocStart();
249 // Get the type before calling CheckSingleAssignmentConstraints(), since
250 // it can promote the expression.
251 QualType rhsType = Init->getType();
252
253 result = CheckSingleAssignmentConstraints(DeclType, Init);
254
255 // decode the result (notice that extensions still return a type).
256 switch (result) {
257 case Compatible:
258 break;
259 case Incompatible:
Steve Naroff6f9f3072007-09-02 15:34:30 +0000260 // FIXME: tighten up this check which should allow:
261 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
262 if (rhsType == Context.getPointerType(Context.CharTy))
263 break;
Steve Narofff0090632007-09-02 02:04:30 +0000264 Diag(loc, diag::err_typecheck_assign_incompatible,
265 DeclType.getAsString(), rhsType.getAsString(),
266 Init->getSourceRange());
267 return true;
268 case PointerFromInt:
269 // check for null pointer constant (C99 6.3.2.3p3)
270 if (!Init->isNullPointerConstant(Context)) {
271 Diag(loc, diag::ext_typecheck_assign_pointer_int,
272 DeclType.getAsString(), rhsType.getAsString(),
273 Init->getSourceRange());
274 return true;
275 }
276 break;
277 case IntFromPointer:
278 Diag(loc, diag::ext_typecheck_assign_pointer_int,
279 DeclType.getAsString(), rhsType.getAsString(),
280 Init->getSourceRange());
281 break;
282 case IncompatiblePointer:
283 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
284 DeclType.getAsString(), rhsType.getAsString(),
285 Init->getSourceRange());
286 break;
287 case CompatiblePointerDiscardsQualifiers:
288 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
289 DeclType.getAsString(), rhsType.getAsString(),
290 Init->getSourceRange());
291 break;
292 }
293 return false;
294}
295
Steve Naroff9e8925e2007-09-04 14:36:54 +0000296bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
297 bool isStatic, QualType ElementType) {
Steve Naroff371227d2007-09-04 02:20:04 +0000298 SourceLocation loc;
Steve Naroff9e8925e2007-09-04 14:36:54 +0000299 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff371227d2007-09-04 02:20:04 +0000300
301 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
302 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
303 return true;
304 } else if (CheckSingleInitializer(expr, ElementType)) {
305 return true; // types weren't compatible.
306 }
Steve Naroff9e8925e2007-09-04 14:36:54 +0000307 if (savExpr != expr) // The type was promoted, update initializer list.
308 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000309 return false;
310}
311
312void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
313 QualType ElementType, bool isStatic,
314 int &nInitializers, bool &hadError) {
Steve Naroff6f9f3072007-09-02 15:34:30 +0000315 for (unsigned i = 0; i < IList->getNumInits(); i++) {
316 Expr *expr = IList->getInit(i);
317
Steve Naroff371227d2007-09-04 02:20:04 +0000318 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
319 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000320 int maxElements = CAT->getMaximumElements();
Steve Naroff371227d2007-09-04 02:20:04 +0000321 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
322 maxElements, hadError);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000323 }
Steve Naroff371227d2007-09-04 02:20:04 +0000324 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000325 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000326 }
Steve Naroff371227d2007-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*.
Steve Naroff7cf8c442007-09-04 21:13:33 +0000341 maxElementsAtThisLevel = CAT->getMaximumElements();
342 // Set DeclType, used below to recurse (for multi-dimensional arrays).
343 DeclType = CAT->getElementType();
Steve Naroff371227d2007-09-04 02:20:04 +0000344 } else if (DeclType->isScalarType()) {
345 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
346 IList->getSourceRange());
347 maxElementsAtThisLevel = 1;
348 }
349 // The empty init list "{ }" is treated specially below.
350 unsigned numInits = IList->getNumInits();
351 if (numInits) {
352 for (unsigned i = 0; i < numInits; i++) {
353 Expr *expr = IList->getInit(i);
354
355 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
356 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
357 totalInits, hadError);
358 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000359 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff371227d2007-09-04 02:20:04 +0000360 nInitsAtLevel++; // increment the number of initializers at this level.
361 totalInits--; // decrement the total number of initializers.
362
363 // Check if we have space for another initializer.
364 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
365 Diag(expr->getLocStart(), diag::warn_excess_initializers,
366 expr->getSourceRange());
367 }
368 }
369 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
370 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
371 } else {
372 // we have an initializer list with no elements.
373 totalInits -= maxElementsAtThisLevel;
374 if (totalInits < 0)
375 Diag(IList->getLocStart(), diag::warn_excess_initializers,
376 IList->getSourceRange());
Steve Naroff6f9f3072007-09-02 15:34:30 +0000377 }
Steve Naroffd35005e2007-09-03 01:24:23 +0000378 return;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000379}
380
Steve Naroff9e8925e2007-09-04 14:36:54 +0000381bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Narofff0090632007-09-02 02:04:30 +0000382 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroffd35005e2007-09-03 01:24:23 +0000383 if (!InitList)
384 return CheckSingleInitializer(Init, DeclType);
385
Steve Narofff0090632007-09-02 02:04:30 +0000386 // We have an InitListExpr, make sure we set the type.
387 Init->setType(DeclType);
Steve Naroffd35005e2007-09-03 01:24:23 +0000388
389 bool hadError = false;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000390
Steve Naroff38374b02007-09-02 20:30:18 +0000391 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
392 // of unknown size ("[]") or an object type that is not a variable array type.
393 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
394 Expr *expr = VAT->getSizeExpr();
Steve Naroffd35005e2007-09-03 01:24:23 +0000395 if (expr)
396 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
397 expr->getSourceRange());
398
Steve Naroff7cf8c442007-09-04 21:13:33 +0000399 // We have a VariableArrayType with unknown size. Note that only the first
400 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff371227d2007-09-04 02:20:04 +0000401 int numInits = 0;
Steve Naroff7cf8c442007-09-04 21:13:33 +0000402 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
403 isStatic, numInits, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000404 if (!hadError) {
405 // Return a new array type from the number of initializers (C99 6.7.8p22).
406 llvm::APSInt ConstVal(32);
Steve Naroff371227d2007-09-04 02:20:04 +0000407 ConstVal = numInits;
408 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroffd35005e2007-09-03 01:24:23 +0000409 ArrayType::Normal, 0);
410 }
411 return hadError;
412 }
413 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000414 int maxElements = CAT->getMaximumElements();
415 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
416 isStatic, maxElements, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000417 return hadError;
418 }
Steve Naroff371227d2007-09-04 02:20:04 +0000419 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
420 int maxElements = 1;
421 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
422 hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000423 return hadError;
Steve Naroff38374b02007-09-02 20:30:18 +0000424 }
425 // FIXME: Handle struct/union types.
Steve Naroffd35005e2007-09-03 01:24:23 +0000426 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +0000427}
428
Reid Spencer5f016e22007-07-11 17:01:13 +0000429Sema::DeclTy *
Chris Lattner24c39902007-07-12 00:36:32 +0000430Sema::ParseDeclarator(Scope *S, Declarator &D, ExprTy *init,
Reid Spencer5f016e22007-07-11 17:01:13 +0000431 DeclTy *lastDeclarator) {
432 Decl *LastDeclarator = (Decl*)lastDeclarator;
Chris Lattner24c39902007-07-12 00:36:32 +0000433 Expr *Init = static_cast<Expr*>(init);
Reid Spencer5f016e22007-07-11 17:01:13 +0000434 IdentifierInfo *II = D.getIdentifier();
435
Chris Lattnere80a59c2007-07-25 00:24:17 +0000436 // All of these full declarators require an identifier. If it doesn't have
437 // one, the ParsedFreeStandingDeclSpec action should be used.
438 if (II == 0) {
Chris Lattner98e08632007-08-28 06:17:15 +0000439 Diag(D.getDeclSpec().getSourceRange().Begin(),
440 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000441 D.getDeclSpec().getSourceRange(), D.getSourceRange());
442 return 0;
443 }
444
Chris Lattner31e05722007-08-26 06:24:45 +0000445 // The scope passed in may not be a decl scope. Zip up the scope tree until
446 // we find one that is.
447 while ((S->getFlags() & Scope::DeclScope) == 0)
448 S = S->getParent();
449
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 // See if this is a redefinition of a variable in the same scope.
451 Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
452 D.getIdentifierLoc(), S);
453 if (PrevDecl && !S->isDeclScope(PrevDecl))
454 PrevDecl = 0; // If in outer scope, it isn't the same thing.
455
456 Decl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000457 bool InvalidDecl = false;
458
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner24c39902007-07-12 00:36:32 +0000460 assert(Init == 0 && "Can't have initializer for a typedef!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000461 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
462 if (!NewTD) return 0;
463
464 // Handle attributes prior to checking for duplicates in MergeVarDecl
465 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
466 D.getAttributes());
467 // Merge the decl with the existing one if appropriate.
468 if (PrevDecl) {
469 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
470 if (NewTD == 0) return 0;
471 }
472 New = NewTD;
473 if (S->getParent() == 0) {
474 // C99 6.7.7p2: If a typedef name specifies a variably modified type
475 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000476 if (const VariableArrayType *VAT =
477 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
478 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
479 VAT->getSizeExpr()->getSourceRange());
480 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000481 }
482 }
483 } else if (D.isFunctionDeclarator()) {
Chris Lattner24c39902007-07-12 00:36:32 +0000484 assert(Init == 0 && "Can't have an initializer for a functiondecl!");
Steve Naroff5912a352007-08-28 20:14:24 +0000485
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000487 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000488
Reid Spencer5f016e22007-07-11 17:01:13 +0000489 FunctionDecl::StorageClass SC;
490 switch (D.getDeclSpec().getStorageClassSpec()) {
491 default: assert(0 && "Unknown storage class!");
492 case DeclSpec::SCS_auto:
493 case DeclSpec::SCS_register:
494 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
495 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000496 InvalidDecl = true;
497 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000498 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
499 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
500 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
501 }
502
503 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000504 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 LastDeclarator);
506
507 // Merge the decl with the existing one if appropriate.
508 if (PrevDecl) {
509 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
510 if (NewFD == 0) return 0;
511 }
512 New = NewFD;
513 } else {
514 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff53a32342007-08-28 18:45:29 +0000515 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000516
517 VarDecl *NewVD;
518 VarDecl::StorageClass SC;
519 switch (D.getDeclSpec().getStorageClassSpec()) {
520 default: assert(0 && "Unknown storage class!");
521 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
522 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
523 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
524 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
525 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
526 }
527 if (S->getParent() == 0) {
Steve Naroff6f9f3072007-09-02 15:34:30 +0000528 if (Init) {
529 if (SC == VarDecl::Extern)
530 Diag(D.getIdentifierLoc(), diag::warn_extern_init);
Steve Naroff371227d2007-09-04 02:20:04 +0000531 if (!D.getInvalidType())
532 CheckInitializer(Init, R, true);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000533 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000534 // File scope. C99 6.9.2p2: A declaration of an identifier for and
535 // object that has file scope without an initializer, and without a
536 // storage-class specifier or with the storage-class specifier "static",
537 // constitutes a tentative definition. Note: A tentative definition with
538 // external linkage is valid (C99 6.2.2p5).
539 if (!Init && SC == VarDecl::Static) {
540 // C99 6.9.2p3: If the declaration of an identifier for an object is
541 // a tentative definition and has internal linkage (C99 6.2.2p3), the
542 // declared type shall not be an incomplete type.
543 if (R->isIncompleteType()) {
544 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
545 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000546 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000547 }
548 }
549 // C99 6.9p2: The storage-class specifiers auto and register shall not
550 // appear in the declaration specifiers in an external declaration.
551 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
552 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
553 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000554 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 }
Steve Naroffd7444aa2007-08-31 17:20:07 +0000556 if (SC == VarDecl::Static) {
557 // C99 6.7.5.2p2: If an identifier is declared to be an object with
558 // static storage duration, it shall not have a variable length array.
559 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
560 Expr *Size = VLA->getSizeExpr();
561 if (Size || (!Size && !Init)) {
562 // FIXME: Since we don't support initializers yet, we only emit this
563 // error when we don't have an initializer. Once initializers are
564 // implemented, the VLA will change to a CLA.
565 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
566 InvalidDecl = true;
567 }
568 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 }
570 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000571 } else {
572 if (Init) {
Steve Naroff6f9f3072007-09-02 15:34:30 +0000573 if (SC == VarDecl::Extern) { // C99 6.7.8p5
574 Diag(D.getIdentifierLoc(), diag::err_block_extern_cant_init);
575 InvalidDecl = true;
Steve Naroff371227d2007-09-04 02:20:04 +0000576 } else if (!D.getInvalidType()) {
Steve Naroff6f9f3072007-09-02 15:34:30 +0000577 CheckInitializer(Init, R, SC == VarDecl::Static);
578 }
Steve Narofff0090632007-09-02 02:04:30 +0000579 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000580 // Block scope. C99 6.7p7: If an identifier for an object is declared with
581 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
582 if (SC != VarDecl::Extern) {
583 if (R->isIncompleteType()) {
584 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
585 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000586 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000587 }
588 }
589 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.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000592 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);
Steve Naroff53a32342007-08-28 18:45:29 +0000599 InvalidDecl = true;
Steve Naroffd7444aa2007-08-31 17:20:07 +0000600 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000601 }
602 }
603 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000604 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 // Handle attributes prior to checking for duplicates in MergeVarDecl
606 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
607 D.getAttributes());
608
609 // Merge the decl with the existing one if appropriate.
610 if (PrevDecl) {
611 NewVD = MergeVarDecl(NewVD, PrevDecl);
612 if (NewVD == 0) return 0;
613 }
Steve Narofff0090632007-09-02 02:04:30 +0000614 if (Init) { // FIXME: This will likely move up above...for now, it stays.
Steve Narofff1120de2007-08-24 22:33:52 +0000615 NewVD->setInit(Init);
616 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000617 New = NewVD;
618 }
619
620 // If this has an identifier, add it to the scope stack.
621 if (II) {
622 New->setNext(II->getFETokenInfo<Decl>());
623 II->setFETokenInfo(New);
624 S->AddDecl(New);
625 }
626
627 if (S->getParent() == 0)
628 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +0000629
630 // If any semantic error occurred, mark the decl as invalid.
631 if (D.getInvalidType() || InvalidDecl)
632 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000633
634 return New;
635}
636
637/// The declarators are chained together backwards, reverse the list.
638Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
639 // Often we have single declarators, handle them quickly.
640 Decl *Group = static_cast<Decl*>(group);
641 if (Group == 0 || Group->getNextDeclarator() == 0) return Group;
642
643 Decl *NewGroup = 0;
644 while (Group) {
645 Decl *Next = Group->getNextDeclarator();
646 Group->setNextDeclarator(NewGroup);
647 NewGroup = Group;
648 Group = Next;
649 }
650 return NewGroup;
651}
Steve Naroffe1223f72007-08-28 03:03:08 +0000652
653// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000654ParmVarDecl *
655Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
656 Scope *FnScope) {
657 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
658
659 IdentifierInfo *II = PI.Ident;
660 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
661 // Can this happen for params? We already checked that they don't conflict
662 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000663 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000664 PI.IdentLoc, FnScope)) {
665
666 }
667
668 // FIXME: Handle storage class (auto, register). No declarator?
669 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000670
671 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
672 // Doing the promotion here has a win and a loss. The win is the type for
673 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
674 // code generator). The loss is the orginal type isn't preserved. For example:
675 //
676 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
677 // int blockvardecl[5];
678 // sizeof(parmvardecl); // size == 4
679 // sizeof(blockvardecl); // size == 20
680 // }
681 //
682 // For expressions, all implicit conversions are captured using the
683 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
684 //
685 // FIXME: If a source translation tool needs to see the original type, then
686 // we need to consider storing both types (in ParmVarDecl)...
687 //
688 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
689 if (const ArrayType *AT = parmDeclType->getAsArrayType())
690 parmDeclType = Context.getPointerType(AT->getElementType());
691 else if (parmDeclType->isFunctionType())
692 parmDeclType = Context.getPointerType(parmDeclType);
693
694 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff53a32342007-08-28 18:45:29 +0000695 VarDecl::None, 0);
696 if (PI.InvalidType)
697 New->setInvalidDecl();
698
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 // If this has an identifier, add it to the scope stack.
700 if (II) {
701 New->setNext(II->getFETokenInfo<Decl>());
702 II->setFETokenInfo(New);
703 FnScope->AddDecl(New);
704 }
705
706 return New;
707}
708
709
710Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
711 assert(CurFunctionDecl == 0 && "Function parsing confused");
712 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
713 "Not a function declarator!");
714 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
715
716 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
717 // for a K&R function.
718 if (!FTI.hasPrototype) {
719 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
720 if (FTI.ArgInfo[i].TypeInfo == 0) {
721 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
722 FTI.ArgInfo[i].Ident->getName());
723 // Implicitly declare the argument as type 'int' for lack of a better
724 // type.
725 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
726 }
727 }
728
729 // Since this is a function definition, act as though we have information
730 // about the arguments.
731 FTI.hasPrototype = true;
732 } else {
733 // FIXME: Diagnose arguments without names in C.
734
735 }
736
737 Scope *GlobalScope = FnBodyScope->getParent();
738
739 FunctionDecl *FD =
740 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0, 0));
741 CurFunctionDecl = FD;
742
743 // Create Decl objects for each parameter, adding them to the FunctionDecl.
744 llvm::SmallVector<ParmVarDecl*, 16> Params;
745
746 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
747 // no arguments, not a function that takes a single void argument.
748 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
749 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
750 // empty arg list, don't push any params.
751 } else {
752 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
753 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
754 }
755
756 FD->setParams(&Params[0], Params.size());
757
758 return FD;
759}
760
761Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
762 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
763 FD->setBody((Stmt*)Body);
764
765 assert(FD == CurFunctionDecl && "Function parsing confused");
766 CurFunctionDecl = 0;
767
768 // Verify and clean out per-function state.
769
770 // Check goto/label use.
771 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
772 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
773 // Verify that we have no forward references left. If so, there was a goto
774 // or address of a label taken, but no definition of it. Label fwd
775 // definitions are indicated with a null substmt.
776 if (I->second->getSubStmt() == 0) {
777 LabelStmt *L = I->second;
778 // Emit error.
779 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
780
781 // At this point, we have gotos that use the bogus label. Stitch it into
782 // the function body so that they aren't leaked and that the AST is well
783 // formed.
784 L->setSubStmt(new NullStmt(L->getIdentLoc()));
785 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
786 }
787 }
788 LabelMap.clear();
789
790 return FD;
791}
792
793
794/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
795/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
796Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
797 Scope *S) {
798 if (getLangOptions().C99) // Extension in C99.
799 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
800 else // Legal in C90, but warn about it.
801 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
802
803 // FIXME: handle stuff like:
804 // void foo() { extern float X(); }
805 // void bar() { X(); } <-- implicit decl for X in another scope.
806
807 // Set a Declarator for the implicit definition: int foo();
808 const char *Dummy;
809 DeclSpec DS;
810 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
811 Error = Error; // Silence warning.
812 assert(!Error && "Error setting up implicit decl!");
813 Declarator D(DS, Declarator::BlockContext);
814 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
815 D.SetIdentifier(&II, Loc);
816
817 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000818 if (Scope *FnS = S->getFnParent())
819 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000820 while (S->getParent())
821 S = S->getParent();
822
823 return static_cast<Decl*>(ParseDeclarator(S, D, 0, 0));
824}
825
826
827TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
828 Decl *LastDeclarator) {
829 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
830
831 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000832 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000833
834 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +0000835 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
836 T, LastDeclarator);
837 if (D.getInvalidType())
838 NewTD->setInvalidDecl();
839 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000840}
841
Steve Naroff3536b442007-09-06 21:24:23 +0000842Sema::DeclTy *Sema::ObjcStartClassInterface(SourceLocation AtInterfaceLoc,
843 IdentifierInfo *ClassName, SourceLocation ClassLoc,
844 IdentifierInfo *SuperName, SourceLocation SuperLoc,
845 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
846 AttributeList *AttrList) {
847 assert(ClassName && "Missing class identifier");
848 ObjcInterfaceDecl *IDecl;
849
850 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, ClassName);
851
852 // Chain & install the interface decl into the identifier.
853 IDecl->setNext(ClassName->getFETokenInfo<Decl>());
854 ClassName->setFETokenInfo(IDecl);
855 return IDecl;
856}
857
858/// ObjcClassDeclaration -
859/// Scope will always be top level file scope.
860Action::DeclTy *
861Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
862 IdentifierInfo **IdentList, unsigned NumElts) {
863 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
864
865 for (unsigned i = 0; i != NumElts; ++i) {
866 ObjcInterfaceDecl *IDecl;
867
868 IDecl = new ObjcInterfaceDecl(SourceLocation(), IdentList[i], true);
869 // Chain & install the interface decl into the identifier.
870 IDecl->setNext(IdentList[i]->getFETokenInfo<Decl>());
871 IdentList[i]->setFETokenInfo(IDecl);
872
873 // Remember that this needs to be removed when the scope is popped.
874 S->AddDecl(IdentList[i]);
875
876 CDecl->setInterfaceDecl((int)i, IDecl);
877 }
878 return CDecl;
879}
880
Reid Spencer5f016e22007-07-11 17:01:13 +0000881
882/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
883/// former case, Name will be non-null. In the later case, Name will be null.
884/// TagType indicates what kind of tag this is. TK indicates whether this is a
885/// reference/declaration/definition of a tag.
886Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
887 SourceLocation KWLoc, IdentifierInfo *Name,
888 SourceLocation NameLoc, AttributeList *Attr) {
889 // If this is a use of an existing tag, it must have a name.
890 assert((Name != 0 || TK == TK_Definition) &&
891 "Nameless record must be a definition!");
892
893 Decl::Kind Kind;
894 switch (TagType) {
895 default: assert(0 && "Unknown tag type!");
896 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
897 case DeclSpec::TST_union: Kind = Decl::Union; break;
898//case DeclSpec::TST_class: Kind = Decl::Class; break;
899 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
900 }
901
902 // If this is a named struct, check to see if there was a previous forward
903 // declaration or definition.
904 if (TagDecl *PrevDecl =
905 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
906 NameLoc, S))) {
907
908 // If this is a use of a previous tag, or if the tag is already declared in
909 // the same scope (so that the definition/declaration completes or
910 // rementions the tag), reuse the decl.
911 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
912 // Make sure that this wasn't declared as an enum and now used as a struct
913 // or something similar.
914 if (PrevDecl->getKind() != Kind) {
915 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
916 Diag(PrevDecl->getLocation(), diag::err_previous_use);
917 }
918
919 // If this is a use or a forward declaration, we're good.
920 if (TK != TK_Definition)
921 return PrevDecl;
922
923 // Diagnose attempts to redefine a tag.
924 if (PrevDecl->isDefinition()) {
925 Diag(NameLoc, diag::err_redefinition, Name->getName());
926 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
927 // If this is a redefinition, recover by making this struct be
928 // anonymous, which will make any later references get the previous
929 // definition.
930 Name = 0;
931 } else {
932 // Okay, this is definition of a previously declared or referenced tag.
933 // Move the location of the decl to be the definition site.
934 PrevDecl->setLocation(NameLoc);
935 return PrevDecl;
936 }
937 }
938 // If we get here, this is a definition of a new struct type in a nested
939 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
940 // type.
941 }
942
943 // If there is an identifier, use the location of the identifier as the
944 // location of the decl, otherwise use the location of the struct/union
945 // keyword.
946 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
947
948 // Otherwise, if this is the first time we've seen this tag, create the decl.
949 TagDecl *New;
950 switch (Kind) {
951 default: assert(0 && "Unknown tag kind!");
952 case Decl::Enum:
953 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
954 // enum X { A, B, C } D; D should chain to X.
955 New = new EnumDecl(Loc, Name, 0);
956 // If this is an undefined enum, warn.
957 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
958 break;
959 case Decl::Union:
960 case Decl::Struct:
961 case Decl::Class:
962 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
963 // struct X { int A; } D; D should chain to X.
964 New = new RecordDecl(Kind, Loc, Name, 0);
965 break;
966 }
967
968 // If this has an identifier, add it to the scope stack.
969 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +0000970 // The scope passed in may not be a decl scope. Zip up the scope tree until
971 // we find one that is.
972 while ((S->getFlags() & Scope::DeclScope) == 0)
973 S = S->getParent();
974
975 // Add it to the decl chain.
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 New->setNext(Name->getFETokenInfo<Decl>());
977 Name->setFETokenInfo(New);
978 S->AddDecl(New);
979 }
980
981 return New;
982}
983
984/// ParseField - Each field of a struct/union/class is passed into this in order
985/// to create a FieldDecl object for it.
986Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
987 SourceLocation DeclStart,
988 Declarator &D, ExprTy *BitfieldWidth) {
989 IdentifierInfo *II = D.getIdentifier();
990 Expr *BitWidth = (Expr*)BitfieldWidth;
991
992 SourceLocation Loc = DeclStart;
993 if (II) Loc = D.getIdentifierLoc();
994
995 // FIXME: Unnamed fields can be handled in various different ways, for
996 // example, unnamed unions inject all members into the struct namespace!
997
998
999 if (BitWidth) {
1000 // TODO: Validate.
1001 //printf("WARNING: BITFIELDS IGNORED!\n");
1002
1003 // 6.7.2.1p3
1004 // 6.7.2.1p4
1005
1006 } else {
1007 // Not a bitfield.
1008
1009 // validate II.
1010
1011 }
1012
1013 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001014 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1015 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001016
Reid Spencer5f016e22007-07-11 17:01:13 +00001017 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1018 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001019 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1020 Diag(Loc, diag::err_typecheck_illegal_vla,
1021 VAT->getSizeExpr()->getSourceRange());
1022 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001023 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001024 // FIXME: Chain fielddecls together.
Steve Naroff5912a352007-08-28 20:14:24 +00001025 FieldDecl *NewFD = new FieldDecl(Loc, II, T, 0);
1026 if (D.getInvalidType() || InvalidDecl)
1027 NewFD->setInvalidDecl();
1028 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001029}
1030
1031void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
1032 DeclTy **Fields, unsigned NumFields) {
1033 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
1034 if (Record->isDefinition()) {
1035 // Diagnose code like:
1036 // struct S { struct S {} X; };
1037 // We discover this when we complete the outer S. Reject and ignore the
1038 // outer S.
1039 Diag(Record->getLocation(), diag::err_nested_redefinition,
1040 Record->getKindName());
1041 Diag(RecLoc, diag::err_previous_definition);
1042 return;
1043 }
1044
1045 // Verify that all the fields are okay.
1046 unsigned NumNamedMembers = 0;
1047 llvm::SmallVector<FieldDecl*, 32> RecFields;
1048 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
1049
1050 for (unsigned i = 0; i != NumFields; ++i) {
1051 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1052 if (!FD) continue; // Already issued a diagnostic.
1053
1054 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001055 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001056
1057 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001058 if (FDTy->isFunctionType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001059 Diag(FD->getLocation(), diag::err_field_declared_as_function,
1060 FD->getName());
1061 delete FD;
1062 continue;
1063 }
1064
1065 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1066 if (FDTy->isIncompleteType()) {
1067 if (i != NumFields-1 || // ... that the last member ...
1068 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001069 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1071 delete FD;
1072 continue;
1073 }
1074 if (NumNamedMembers < 1) { //... must have more than named member ...
1075 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1076 FD->getName());
1077 delete FD;
1078 continue;
1079 }
1080
1081 // Okay, we have a legal flexible array member at the end of the struct.
1082 Record->setHasFlexibleArrayMember(true);
1083 }
1084
1085
1086 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1087 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001088 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001089 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1090 // If this is a member of a union, then entire union becomes "flexible".
1091 if (Record->getKind() == Decl::Union) {
1092 Record->setHasFlexibleArrayMember(true);
1093 } else {
1094 // If this is a struct/class and this is not the last element, reject
1095 // it. Note that GCC supports variable sized arrays in the middle of
1096 // structures.
1097 if (i != NumFields-1) {
1098 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1099 FD->getName());
1100 delete FD;
1101 continue;
1102 }
1103
1104 // We support flexible arrays at the end of structs in other structs
1105 // as an extension.
1106 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1107 FD->getName());
1108 Record->setHasFlexibleArrayMember(true);
1109 }
1110 }
1111 }
1112
1113 // Keep track of the number of named members.
1114 if (IdentifierInfo *II = FD->getIdentifier()) {
1115 // Detect duplicate member names.
1116 if (!FieldIDs.insert(II)) {
1117 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1118 // Find the previous decl.
1119 SourceLocation PrevLoc;
1120 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1121 assert(i != e && "Didn't find previous def!");
1122 if (RecFields[i]->getIdentifier() == II) {
1123 PrevLoc = RecFields[i]->getLocation();
1124 break;
1125 }
1126 }
1127 Diag(PrevLoc, diag::err_previous_definition);
1128 delete FD;
1129 continue;
1130 }
1131 ++NumNamedMembers;
1132 }
1133
1134 // Remember good fields.
1135 RecFields.push_back(FD);
1136 }
1137
1138
1139 // Okay, we successfully defined 'Record'.
1140 Record->defineBody(&RecFields[0], RecFields.size());
1141}
1142
1143Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
1144 DeclTy *lastEnumConst,
1145 SourceLocation IdLoc, IdentifierInfo *Id,
1146 SourceLocation EqualLoc, ExprTy *val) {
1147 theEnumDecl = theEnumDecl; // silence unused warning.
1148 EnumConstantDecl *LastEnumConst =
1149 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1150 Expr *Val = static_cast<Expr*>(val);
1151
Chris Lattner31e05722007-08-26 06:24:45 +00001152 // The scope passed in may not be a decl scope. Zip up the scope tree until
1153 // we find one that is.
1154 while ((S->getFlags() & Scope::DeclScope) == 0)
1155 S = S->getParent();
1156
Reid Spencer5f016e22007-07-11 17:01:13 +00001157 // Verify that there isn't already something declared with this name in this
1158 // scope.
1159 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
1160 if (S->isDeclScope(PrevDecl)) {
1161 if (isa<EnumConstantDecl>(PrevDecl))
1162 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1163 else
1164 Diag(IdLoc, diag::err_redefinition, Id->getName());
1165 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1166 // FIXME: Don't leak memory: delete Val;
1167 return 0;
1168 }
1169 }
1170
1171 llvm::APSInt EnumVal(32);
1172 QualType EltTy;
1173 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001174 // Make sure to promote the operand type to int.
1175 UsualUnaryConversions(Val);
1176
Reid Spencer5f016e22007-07-11 17:01:13 +00001177 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1178 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001179 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1181 Id->getName());
1182 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001183 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001184 } else {
1185 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001186 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001187 }
1188
1189 if (!Val) {
1190 if (LastEnumConst) {
1191 // Assign the last value + 1.
1192 EnumVal = LastEnumConst->getInitVal();
1193 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001194
1195 // Check for overflow on increment.
1196 if (EnumVal < LastEnumConst->getInitVal())
1197 Diag(IdLoc, diag::warn_enum_value_overflow);
1198
Chris Lattnerb7416f92007-08-27 17:37:24 +00001199 EltTy = LastEnumConst->getType();
1200 } else {
1201 // First value, set to zero.
1202 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001203 EnumVal.zextOrTrunc(
1204 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001205 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001206 }
1207
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1209 LastEnumConst);
1210
1211 // Register this decl in the current scope stack.
1212 New->setNext(Id->getFETokenInfo<Decl>());
1213 Id->setFETokenInfo(New);
1214 S->AddDecl(New);
1215 return New;
1216}
1217
1218void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1219 DeclTy **Elements, unsigned NumElements) {
1220 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1221 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1222
Chris Lattnere37f0be2007-08-28 05:10:31 +00001223 // TODO: If the result value doesn't fit in an int, it must be a long or long
1224 // long value. ISO C does not support this, but GCC does as an extension,
1225 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001226 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001227
1228
Chris Lattnerac609682007-08-28 06:15:15 +00001229 // Verify that all the values are okay, compute the size of the values, and
1230 // reverse the list.
1231 unsigned NumNegativeBits = 0;
1232 unsigned NumPositiveBits = 0;
1233
1234 // Keep track of whether all elements have type int.
1235 bool AllElementsInt = true;
1236
Reid Spencer5f016e22007-07-11 17:01:13 +00001237 EnumConstantDecl *EltList = 0;
1238 for (unsigned i = 0; i != NumElements; ++i) {
1239 EnumConstantDecl *ECD =
1240 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1241 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001242
1243 // If the enum value doesn't fit in an int, emit an extension warning.
1244 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1245 "Should have promoted value to int");
1246 const llvm::APSInt &InitVal = ECD->getInitVal();
1247 if (InitVal.getBitWidth() > IntWidth) {
1248 llvm::APSInt V(InitVal);
1249 V.trunc(IntWidth);
1250 V.extend(InitVal.getBitWidth());
1251 if (V != InitVal)
1252 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1253 InitVal.toString());
1254 }
Chris Lattnerac609682007-08-28 06:15:15 +00001255
1256 // Keep track of the size of positive and negative values.
1257 if (InitVal.isUnsigned() || !InitVal.isNegative())
1258 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1259 else
1260 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001261
Chris Lattnerac609682007-08-28 06:15:15 +00001262 // Keep track of whether every enum element has type int (very commmon).
1263 if (AllElementsInt)
1264 AllElementsInt = ECD->getType() == Context.IntTy;
1265
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 ECD->setNextDeclarator(EltList);
1267 EltList = ECD;
1268 }
1269
Chris Lattnerac609682007-08-28 06:15:15 +00001270 // Figure out the type that should be used for this enum.
1271 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1272 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001273 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001274
1275 if (NumNegativeBits) {
1276 // If there is a negative value, figure out the smallest integer type (of
1277 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001278 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001279 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001280 BestWidth = IntWidth;
1281 } else {
1282 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1283 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001284 BestType = Context.LongTy;
1285 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001286 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1287 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001288 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1289 BestType = Context.LongLongTy;
1290 }
1291 }
1292 } else {
1293 // If there is no negative value, figure out which of uint, ulong, ulonglong
1294 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001295 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001296 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001297 BestWidth = IntWidth;
1298 } else if (NumPositiveBits <=
1299 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001300 BestType = Context.UnsignedLongTy;
1301 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001302 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1303 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001304 "How could an initializer get larger than ULL?");
1305 BestType = Context.UnsignedLongLongTy;
1306 }
1307 }
1308
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001309 // Loop over all of the enumerator constants, changing their types to match
1310 // the type of the enum if needed.
1311 for (unsigned i = 0; i != NumElements; ++i) {
1312 EnumConstantDecl *ECD =
1313 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1314 if (!ECD) continue; // Already issued a diagnostic.
1315
1316 // Standard C says the enumerators have int type, but we allow, as an
1317 // extension, the enumerators to be larger than int size. If each
1318 // enumerator value fits in an int, type it as an int, otherwise type it the
1319 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1320 // that X has type 'int', not 'unsigned'.
1321 if (ECD->getType() == Context.IntTy)
1322 continue; // Already int type.
1323
1324 // Determine whether the value fits into an int.
1325 llvm::APSInt InitVal = ECD->getInitVal();
1326 bool FitsInInt;
1327 if (InitVal.isUnsigned() || !InitVal.isNegative())
1328 FitsInInt = InitVal.getActiveBits() < IntWidth;
1329 else
1330 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1331
1332 // If it fits into an integer type, force it. Otherwise force it to match
1333 // the enum decl type.
1334 QualType NewTy;
1335 unsigned NewWidth;
1336 bool NewSign;
1337 if (FitsInInt) {
1338 NewTy = Context.IntTy;
1339 NewWidth = IntWidth;
1340 NewSign = true;
1341 } else if (ECD->getType() == BestType) {
1342 // Already the right type!
1343 continue;
1344 } else {
1345 NewTy = BestType;
1346 NewWidth = BestWidth;
1347 NewSign = BestType->isSignedIntegerType();
1348 }
1349
1350 // Adjust the APSInt value.
1351 InitVal.extOrTrunc(NewWidth);
1352 InitVal.setIsSigned(NewSign);
1353 ECD->setInitVal(InitVal);
1354
1355 // Adjust the Expr initializer and type.
1356 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1357 ECD->setType(NewTy);
1358 }
Chris Lattnerac609682007-08-28 06:15:15 +00001359
Chris Lattnere00b18c2007-08-28 18:24:31 +00001360 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001361}
1362
1363void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1364 if (!current) return;
1365
1366 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1367 // remember this in the LastInGroupList list.
1368 if (last)
1369 LastInGroupList.push_back((Decl*)last);
1370}
1371
1372void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1373 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1374 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1375 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1376 if (!newType.isNull()) // install the new vector type into the decl
1377 vDecl->setType(newType);
1378 }
1379 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1380 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1381 rawAttr);
1382 if (!newType.isNull()) // install the new vector type into the decl
1383 tDecl->setUnderlyingType(newType);
1384 }
1385 }
Steve Naroff73322922007-07-18 18:00:27 +00001386 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001387 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1388 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1389 else
Steve Naroff73322922007-07-18 18:00:27 +00001390 Diag(rawAttr->getAttributeLoc(),
1391 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00001392 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 // FIXME: add other attributes...
1394}
1395
1396void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1397 AttributeList *declarator_postfix) {
1398 while (declspec_prefix) {
1399 HandleDeclAttribute(New, declspec_prefix);
1400 declspec_prefix = declspec_prefix->getNext();
1401 }
1402 while (declarator_postfix) {
1403 HandleDeclAttribute(New, declarator_postfix);
1404 declarator_postfix = declarator_postfix->getNext();
1405 }
1406}
1407
Steve Naroffbea0b342007-07-29 16:33:31 +00001408void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1409 AttributeList *rawAttr) {
1410 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00001411 // check the attribute arugments.
1412 if (rawAttr->getNumArgs() != 1) {
1413 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1414 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001415 return;
Steve Naroff73322922007-07-18 18:00:27 +00001416 }
1417 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1418 llvm::APSInt vecSize(32);
1419 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1420 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1421 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001422 return;
Steve Naroff73322922007-07-18 18:00:27 +00001423 }
1424 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1425 // in conjunction with complex types (pointers, arrays, functions, etc.).
1426 Type *canonType = curType.getCanonicalType().getTypePtr();
1427 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1428 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1429 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001430 return;
Steve Naroff73322922007-07-18 18:00:27 +00001431 }
1432 // unlike gcc's vector_size attribute, the size is specified as the
1433 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001434 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001435
1436 if (vectorSize == 0) {
1437 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1438 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001439 return;
Steve Naroff73322922007-07-18 18:00:27 +00001440 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001441 // Instantiate/Install the vector type, the number of elements is > 0.
1442 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1443 // Remember this typedef decl, we will need it later for diagnostics.
1444 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001445}
1446
Reid Spencer5f016e22007-07-11 17:01:13 +00001447QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001448 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 // check the attribute arugments.
1450 if (rawAttr->getNumArgs() != 1) {
1451 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1452 std::string("1"));
1453 return QualType();
1454 }
1455 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1456 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001457 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1459 sizeExpr->getSourceRange());
1460 return QualType();
1461 }
1462 // navigate to the base type - we need to provide for vector pointers,
1463 // vector arrays, and functions returning vectors.
1464 Type *canonType = curType.getCanonicalType().getTypePtr();
1465
Steve Naroff73322922007-07-18 18:00:27 +00001466 if (canonType->isPointerType() || canonType->isArrayType() ||
1467 canonType->isFunctionType()) {
1468 assert(1 && "HandleVector(): Complex type construction unimplemented");
1469 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1470 do {
1471 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1472 canonType = PT->getPointeeType().getTypePtr();
1473 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1474 canonType = AT->getElementType().getTypePtr();
1475 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1476 canonType = FT->getResultType().getTypePtr();
1477 } while (canonType->isPointerType() || canonType->isArrayType() ||
1478 canonType->isFunctionType());
1479 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 }
1481 // the base type must be integer or float.
1482 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1483 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1484 curType.getCanonicalType().getAsString());
1485 return QualType();
1486 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00001487 unsigned typeSize = static_cast<unsigned>(
1488 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001490 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00001491
1492 // the vector size needs to be an integral multiple of the type size.
1493 if (vectorSize % typeSize) {
1494 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1495 sizeExpr->getSourceRange());
1496 return QualType();
1497 }
1498 if (vectorSize == 0) {
1499 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1500 sizeExpr->getSourceRange());
1501 return QualType();
1502 }
1503 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1504 // the number of elements to be a power of two (unlike GCC).
1505 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00001506 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001507}
1508