blob: 86e052b4df3218e0e1b61c54f7c48172851acf4a [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 {
Steve Naroff81f1bba2007-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;
Chris Lattner4b009652007-07-25 00:24:17 +000034}
35
36void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000037 if (S->decl_empty()) return;
38 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
39
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner987058a2007-08-26 04:02:13 +0000118 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000119
120 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000121 if (Scope *FnS = S->getFnParent())
122 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroff83c13012007-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 }
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffe6a8c9b2007-09-04 14:36:54 +0000246bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-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 Naroff9091f3f2007-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 Naroffe14e5542007-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 Naroffe6a8c9b2007-09-04 14:36:54 +0000296bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
297 bool isStatic, QualType ElementType) {
Steve Naroff509d0b52007-09-04 02:20:04 +0000298 SourceLocation loc;
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000299 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff509d0b52007-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 Naroffe6a8c9b2007-09-04 14:36:54 +0000307 if (savExpr != expr) // The type was promoted, update initializer list.
308 IList->setInit(slot, expr);
Steve Naroff509d0b52007-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 Naroff9091f3f2007-09-02 15:34:30 +0000315 for (unsigned i = 0; i < IList->getNumInits(); i++) {
316 Expr *expr = IList->getInit(i);
317
Steve Naroff509d0b52007-09-04 02:20:04 +0000318 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
319 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000320 int maxElements = CAT->getMaximumElements();
Steve Naroff509d0b52007-09-04 02:20:04 +0000321 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
322 maxElements, hadError);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000323 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000324 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000325 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000326 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000327 nInitializers++;
328 }
329 return;
330}
331
332// FIXME: Doesn't deal with arrays of structures yet.
333void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
334 QualType ElementType, bool isStatic,
335 int &totalInits, bool &hadError) {
336 int maxElementsAtThisLevel = 0;
337 int nInitsAtLevel = 0;
338
339 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
340 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff4f910992007-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 Naroff509d0b52007-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 Naroffe6a8c9b2007-09-04 14:36:54 +0000359 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff509d0b52007-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 Naroff9091f3f2007-09-02 15:34:30 +0000377 }
Steve Naroff1c9de712007-09-03 01:24:23 +0000378 return;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000379}
380
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000381bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000382 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroff1c9de712007-09-03 01:24:23 +0000383 if (!InitList)
384 return CheckSingleInitializer(Init, DeclType);
385
Steve Naroffe14e5542007-09-02 02:04:30 +0000386 // We have an InitListExpr, make sure we set the type.
387 Init->setType(DeclType);
Steve Naroff1c9de712007-09-03 01:24:23 +0000388
389 bool hadError = false;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000390
Steve Naroff7c9d72d2007-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 Naroff1c9de712007-09-03 01:24:23 +0000395 if (expr)
396 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
397 expr->getSourceRange());
398
Steve Naroff4f910992007-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 Naroff509d0b52007-09-04 02:20:04 +0000401 int numInits = 0;
Steve Naroff4f910992007-09-04 21:13:33 +0000402 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
403 isStatic, numInits, hadError);
Steve Naroff1c9de712007-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 Naroff509d0b52007-09-04 02:20:04 +0000407 ConstVal = numInits;
408 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroff1c9de712007-09-03 01:24:23 +0000409 ArrayType::Normal, 0);
410 }
411 return hadError;
412 }
413 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000414 int maxElements = CAT->getMaximumElements();
415 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
416 isStatic, maxElements, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000417 return hadError;
418 }
Steve Naroff509d0b52007-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 Naroff1c9de712007-09-03 01:24:23 +0000423 return hadError;
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000424 }
425 // FIXME: Handle struct/union types.
Steve Naroff1c9de712007-09-03 01:24:23 +0000426 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +0000427}
428
Chris Lattner4b009652007-07-25 00:24:17 +0000429Sema::DeclTy *
430Sema::ParseDeclarator(Scope *S, Declarator &D, ExprTy *init,
431 DeclTy *lastDeclarator) {
432 Decl *LastDeclarator = (Decl*)lastDeclarator;
433 Expr *Init = static_cast<Expr*>(init);
434 IdentifierInfo *II = D.getIdentifier();
435
436 // 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 Lattner87492f42007-08-28 06:17:15 +0000439 Diag(D.getDeclSpec().getSourceRange().Begin(),
440 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000441 D.getDeclSpec().getSourceRange(), D.getSourceRange());
442 return 0;
443 }
444
Chris Lattnera7549902007-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
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffd1ad6ae2007-08-28 20:14:24 +0000457 bool InvalidDecl = false;
458
Chris Lattner4b009652007-07-25 00:24:17 +0000459 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
460 assert(Init == 0 && "Can't have initializer for a typedef!");
461 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 Naroff5eb879b2007-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;
Chris Lattner4b009652007-07-25 00:24:17 +0000481 }
482 }
483 } else if (D.isFunctionDeclarator()) {
484 assert(Init == 0 && "Can't have an initializer for a functiondecl!");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000485
Chris Lattner4b009652007-07-25 00:24:17 +0000486 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000487 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000488
489 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 Naroffd1ad6ae2007-08-28 20:14:24 +0000496 InvalidDecl = true;
497 break;
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner987058a2007-08-26 04:02:13 +0000504 D.getDeclSpec().isInlineSpecified(),
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffcae537d2007-08-28 18:45:29 +0000515 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroff9091f3f2007-09-02 15:34:30 +0000528 if (Init) {
529 if (SC == VarDecl::Extern)
530 Diag(D.getIdentifierLoc(), diag::warn_extern_init);
Steve Naroff509d0b52007-09-04 02:20:04 +0000531 if (!D.getInvalidType())
532 CheckInitializer(Init, R, true);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000533 }
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffcae537d2007-08-28 18:45:29 +0000546 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffcae537d2007-08-28 18:45:29 +0000554 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000555 }
Steve Naroff5eb879b2007-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 }
Chris Lattner4b009652007-07-25 00:24:17 +0000569 }
570 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000571 } else {
572 if (Init) {
Steve Naroff9091f3f2007-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 Naroff509d0b52007-09-04 02:20:04 +0000576 } else if (!D.getInvalidType()) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000577 CheckInitializer(Init, R, SC == VarDecl::Static);
578 }
Steve Naroffe14e5542007-09-02 02:04:30 +0000579 }
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffcae537d2007-08-28 18:45:29 +0000586 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroff5eb879b2007-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 Naroffcae537d2007-08-28 18:45:29 +0000599 InvalidDecl = true;
Steve Naroff5eb879b2007-08-31 17:20:07 +0000600 }
Chris Lattner4b009652007-07-25 00:24:17 +0000601 }
602 }
603 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000604 }
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffe14e5542007-09-02 02:04:30 +0000614 if (Init) { // FIXME: This will likely move up above...for now, it stays.
Steve Naroff0f32f432007-08-24 22:33:52 +0000615 NewVD->setInit(Init);
616 }
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffd1ad6ae2007-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();
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroff91b03f72007-08-28 03:03:08 +0000652
653// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +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.
663 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
664 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 Naroff94cd93f2007-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 Naroffcae537d2007-08-28 18:45:29 +0000695 VarDecl::None, 0);
696 if (PI.InvalidType)
697 New->setInvalidDecl();
698
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnera7549902007-08-26 06:24:45 +0000818 if (Scope *FnS = S->getFnParent())
819 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffd1ad6ae2007-08-28 20:14:24 +0000832 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000833
834 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-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;
Chris Lattner4b009652007-07-25 00:24:17 +0000840}
841
Steve Naroff81f1bba2007-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
Steve Naroff75494892007-09-11 21:17:26 +0000858void Sema::ObjcAddInstanceVariable(DeclTy *ClassDecl, DeclTy *Ivar,
859 tok::ObjCKeywordKind visibility) {
860 assert((ClassDecl && Ivar) && "missing class or instance variable");
861 ObjcInterfaceDecl *OInterface = dyn_cast<ObjcInterfaceDecl>(
862 static_cast<Decl *>(ClassDecl));
863 ObjcIvarDecl *OIvar = dyn_cast<ObjcIvarDecl>(static_cast<Decl *>(Ivar));
864
865 assert((OInterface && OIvar) && "mistyped class or instance variable");
866
867 switch (visibility) {
868 case tok::objc_private:
869 OIvar->setAccessControl(ObjcIvarDecl::Private);
870 break;
871 case tok::objc_public:
872 OIvar->setAccessControl(ObjcIvarDecl::Public);
873 break;
874 case tok::objc_protected:
875 OIvar->setAccessControl(ObjcIvarDecl::Protected);
876 break;
877 case tok::objc_package:
878 OIvar->setAccessControl(ObjcIvarDecl::Package);
879 break;
880 default:
881 OIvar->setAccessControl(ObjcIvarDecl::None);
882 break;
883 }
884 // FIXME: add to the class...
885}
886
Steve Naroff81f1bba2007-09-06 21:24:23 +0000887/// ObjcClassDeclaration -
888/// Scope will always be top level file scope.
889Action::DeclTy *
890Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
891 IdentifierInfo **IdentList, unsigned NumElts) {
892 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
893
894 for (unsigned i = 0; i != NumElts; ++i) {
895 ObjcInterfaceDecl *IDecl;
896
Steve Narofffaed3bf2007-09-10 20:51:04 +0000897 // FIXME: before we create one, look up the interface decl in a hash table.
Steve Naroff81f1bba2007-09-06 21:24:23 +0000898 IDecl = new ObjcInterfaceDecl(SourceLocation(), IdentList[i], true);
899 // Chain & install the interface decl into the identifier.
900 IDecl->setNext(IdentList[i]->getFETokenInfo<Decl>());
901 IdentList[i]->setFETokenInfo(IDecl);
902
903 // Remember that this needs to be removed when the scope is popped.
904 S->AddDecl(IdentList[i]);
905
906 CDecl->setInterfaceDecl((int)i, IDecl);
907 }
908 return CDecl;
909}
910
Chris Lattner4b009652007-07-25 00:24:17 +0000911
912/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
913/// former case, Name will be non-null. In the later case, Name will be null.
914/// TagType indicates what kind of tag this is. TK indicates whether this is a
915/// reference/declaration/definition of a tag.
916Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
917 SourceLocation KWLoc, IdentifierInfo *Name,
918 SourceLocation NameLoc, AttributeList *Attr) {
919 // If this is a use of an existing tag, it must have a name.
920 assert((Name != 0 || TK == TK_Definition) &&
921 "Nameless record must be a definition!");
922
923 Decl::Kind Kind;
924 switch (TagType) {
925 default: assert(0 && "Unknown tag type!");
926 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
927 case DeclSpec::TST_union: Kind = Decl::Union; break;
928//case DeclSpec::TST_class: Kind = Decl::Class; break;
929 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
930 }
931
932 // If this is a named struct, check to see if there was a previous forward
933 // declaration or definition.
934 if (TagDecl *PrevDecl =
935 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
936 NameLoc, S))) {
937
938 // If this is a use of a previous tag, or if the tag is already declared in
939 // the same scope (so that the definition/declaration completes or
940 // rementions the tag), reuse the decl.
941 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
942 // Make sure that this wasn't declared as an enum and now used as a struct
943 // or something similar.
944 if (PrevDecl->getKind() != Kind) {
945 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
946 Diag(PrevDecl->getLocation(), diag::err_previous_use);
947 }
948
949 // If this is a use or a forward declaration, we're good.
950 if (TK != TK_Definition)
951 return PrevDecl;
952
953 // Diagnose attempts to redefine a tag.
954 if (PrevDecl->isDefinition()) {
955 Diag(NameLoc, diag::err_redefinition, Name->getName());
956 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
957 // If this is a redefinition, recover by making this struct be
958 // anonymous, which will make any later references get the previous
959 // definition.
960 Name = 0;
961 } else {
962 // Okay, this is definition of a previously declared or referenced tag.
963 // Move the location of the decl to be the definition site.
964 PrevDecl->setLocation(NameLoc);
965 return PrevDecl;
966 }
967 }
968 // If we get here, this is a definition of a new struct type in a nested
969 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
970 // type.
971 }
972
973 // If there is an identifier, use the location of the identifier as the
974 // location of the decl, otherwise use the location of the struct/union
975 // keyword.
976 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
977
978 // Otherwise, if this is the first time we've seen this tag, create the decl.
979 TagDecl *New;
980 switch (Kind) {
981 default: assert(0 && "Unknown tag kind!");
982 case Decl::Enum:
983 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
984 // enum X { A, B, C } D; D should chain to X.
985 New = new EnumDecl(Loc, Name, 0);
986 // If this is an undefined enum, warn.
987 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
988 break;
989 case Decl::Union:
990 case Decl::Struct:
991 case Decl::Class:
992 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
993 // struct X { int A; } D; D should chain to X.
994 New = new RecordDecl(Kind, Loc, Name, 0);
995 break;
996 }
997
998 // If this has an identifier, add it to the scope stack.
999 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001000 // The scope passed in may not be a decl scope. Zip up the scope tree until
1001 // we find one that is.
1002 while ((S->getFlags() & Scope::DeclScope) == 0)
1003 S = S->getParent();
1004
1005 // Add it to the decl chain.
Chris Lattner4b009652007-07-25 00:24:17 +00001006 New->setNext(Name->getFETokenInfo<Decl>());
1007 Name->setFETokenInfo(New);
1008 S->AddDecl(New);
1009 }
1010
1011 return New;
1012}
1013
1014/// ParseField - Each field of a struct/union/class is passed into this in order
1015/// to create a FieldDecl object for it.
1016Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
1017 SourceLocation DeclStart,
1018 Declarator &D, ExprTy *BitfieldWidth) {
1019 IdentifierInfo *II = D.getIdentifier();
1020 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001021 SourceLocation Loc = DeclStart;
1022 if (II) Loc = D.getIdentifierLoc();
1023
1024 // FIXME: Unnamed fields can be handled in various different ways, for
1025 // example, unnamed unions inject all members into the struct namespace!
1026
1027
1028 if (BitWidth) {
1029 // TODO: Validate.
1030 //printf("WARNING: BITFIELDS IGNORED!\n");
1031
1032 // 6.7.2.1p3
1033 // 6.7.2.1p4
1034
1035 } else {
1036 // Not a bitfield.
1037
1038 // validate II.
1039
1040 }
1041
1042 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001043 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1044 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001045
Chris Lattner4b009652007-07-25 00:24:17 +00001046 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1047 // than a variably modified type.
Steve Naroff5eb879b2007-08-31 17:20:07 +00001048 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1049 Diag(Loc, diag::err_typecheck_illegal_vla,
1050 VAT->getSizeExpr()->getSourceRange());
1051 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001052 }
Chris Lattner4b009652007-07-25 00:24:17 +00001053 // FIXME: Chain fielddecls together.
Steve Naroff75494892007-09-11 21:17:26 +00001054 FieldDecl *NewFD;
1055
1056 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
1057 NewFD = new FieldDecl(Loc, II, T, 0);
1058 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl)))
1059 NewFD = new ObjcIvarDecl(Loc, II, T, 0);
1060 else
1061 assert(0 && "Sema::ParseField(): Unknown TagDecl");
1062
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001063 if (D.getInvalidType() || InvalidDecl)
1064 NewFD->setInvalidDecl();
1065 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001066}
1067
1068void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
1069 DeclTy **Fields, unsigned NumFields) {
1070 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
1071 if (Record->isDefinition()) {
1072 // Diagnose code like:
1073 // struct S { struct S {} X; };
1074 // We discover this when we complete the outer S. Reject and ignore the
1075 // outer S.
1076 Diag(Record->getLocation(), diag::err_nested_redefinition,
1077 Record->getKindName());
1078 Diag(RecLoc, diag::err_previous_definition);
1079 return;
1080 }
1081
1082 // Verify that all the fields are okay.
1083 unsigned NumNamedMembers = 0;
1084 llvm::SmallVector<FieldDecl*, 32> RecFields;
1085 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
1086
1087 for (unsigned i = 0; i != NumFields; ++i) {
1088 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1089 if (!FD) continue; // Already issued a diagnostic.
1090
1091 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001092 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +00001093
1094 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001095 if (FDTy->isFunctionType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001096 Diag(FD->getLocation(), diag::err_field_declared_as_function,
1097 FD->getName());
1098 delete FD;
1099 continue;
1100 }
1101
1102 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1103 if (FDTy->isIncompleteType()) {
1104 if (i != NumFields-1 || // ... that the last member ...
1105 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001106 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001107 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1108 delete FD;
1109 continue;
1110 }
1111 if (NumNamedMembers < 1) { //... must have more than named member ...
1112 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1113 FD->getName());
1114 delete FD;
1115 continue;
1116 }
1117
1118 // Okay, we have a legal flexible array member at the end of the struct.
1119 Record->setHasFlexibleArrayMember(true);
1120 }
1121
1122
1123 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1124 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001125 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001126 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1127 // If this is a member of a union, then entire union becomes "flexible".
1128 if (Record->getKind() == Decl::Union) {
1129 Record->setHasFlexibleArrayMember(true);
1130 } else {
1131 // If this is a struct/class and this is not the last element, reject
1132 // it. Note that GCC supports variable sized arrays in the middle of
1133 // structures.
1134 if (i != NumFields-1) {
1135 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1136 FD->getName());
1137 delete FD;
1138 continue;
1139 }
1140
1141 // We support flexible arrays at the end of structs in other structs
1142 // as an extension.
1143 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1144 FD->getName());
1145 Record->setHasFlexibleArrayMember(true);
1146 }
1147 }
1148 }
1149
1150 // Keep track of the number of named members.
1151 if (IdentifierInfo *II = FD->getIdentifier()) {
1152 // Detect duplicate member names.
1153 if (!FieldIDs.insert(II)) {
1154 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1155 // Find the previous decl.
1156 SourceLocation PrevLoc;
1157 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1158 assert(i != e && "Didn't find previous def!");
1159 if (RecFields[i]->getIdentifier() == II) {
1160 PrevLoc = RecFields[i]->getLocation();
1161 break;
1162 }
1163 }
1164 Diag(PrevLoc, diag::err_previous_definition);
1165 delete FD;
1166 continue;
1167 }
1168 ++NumNamedMembers;
1169 }
1170
1171 // Remember good fields.
1172 RecFields.push_back(FD);
1173 }
1174
1175
1176 // Okay, we successfully defined 'Record'.
1177 Record->defineBody(&RecFields[0], RecFields.size());
1178}
1179
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001180void Sema::ObjcAddMethodsToClass(DeclTy *ClassDecl,
1181 DeclTy **allMethods, unsigned allNum) {
1182 // FIXME: Add method insertion code here.
1183#if 0
1184 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1185 static_cast<Decl*>(ClassDecl));
1186 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1187 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1188
1189 for (unsigned i = 0; i < allNum; i++ ) {
1190 ObjcMethodDecl *Method =
1191 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1192 if (!Method) continue; // Already issued a diagnostic.
1193 if (Method->isInstance())
1194 insMethods.push_back(Method);
1195 else
1196 clsMethods.push_back(Method);
1197 }
1198 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1199 &clsMethods[0], clsMethods.size());
1200#endif
1201 return;
1202}
1203
Chris Lattner4b009652007-07-25 00:24:17 +00001204Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
1205 DeclTy *lastEnumConst,
1206 SourceLocation IdLoc, IdentifierInfo *Id,
1207 SourceLocation EqualLoc, ExprTy *val) {
1208 theEnumDecl = theEnumDecl; // silence unused warning.
1209 EnumConstantDecl *LastEnumConst =
1210 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1211 Expr *Val = static_cast<Expr*>(val);
1212
Chris Lattnera7549902007-08-26 06:24:45 +00001213 // The scope passed in may not be a decl scope. Zip up the scope tree until
1214 // we find one that is.
1215 while ((S->getFlags() & Scope::DeclScope) == 0)
1216 S = S->getParent();
1217
Chris Lattner4b009652007-07-25 00:24:17 +00001218 // Verify that there isn't already something declared with this name in this
1219 // scope.
1220 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
1221 if (S->isDeclScope(PrevDecl)) {
1222 if (isa<EnumConstantDecl>(PrevDecl))
1223 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1224 else
1225 Diag(IdLoc, diag::err_redefinition, Id->getName());
1226 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1227 // FIXME: Don't leak memory: delete Val;
1228 return 0;
1229 }
1230 }
1231
1232 llvm::APSInt EnumVal(32);
1233 QualType EltTy;
1234 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001235 // Make sure to promote the operand type to int.
1236 UsualUnaryConversions(Val);
1237
Chris Lattner4b009652007-07-25 00:24:17 +00001238 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1239 SourceLocation ExpLoc;
1240 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1241 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1242 Id->getName());
1243 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001244 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001245 } else {
1246 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001247 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001248 }
1249
1250 if (!Val) {
1251 if (LastEnumConst) {
1252 // Assign the last value + 1.
1253 EnumVal = LastEnumConst->getInitVal();
1254 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001255
1256 // Check for overflow on increment.
1257 if (EnumVal < LastEnumConst->getInitVal())
1258 Diag(IdLoc, diag::warn_enum_value_overflow);
1259
Chris Lattnere7f53a42007-08-27 17:37:24 +00001260 EltTy = LastEnumConst->getType();
1261 } else {
1262 // First value, set to zero.
1263 EltTy = Context.IntTy;
Chris Lattner3496d522007-09-04 02:45:27 +00001264 EnumVal.zextOrTrunc(
1265 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001266 }
Chris Lattner4b009652007-07-25 00:24:17 +00001267 }
1268
Chris Lattner4b009652007-07-25 00:24:17 +00001269 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1270 LastEnumConst);
1271
1272 // Register this decl in the current scope stack.
1273 New->setNext(Id->getFETokenInfo<Decl>());
1274 Id->setFETokenInfo(New);
1275 S->AddDecl(New);
1276 return New;
1277}
1278
1279void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1280 DeclTy **Elements, unsigned NumElements) {
1281 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1282 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1283
Chris Lattner435c3fd2007-08-28 05:10:31 +00001284 // TODO: If the result value doesn't fit in an int, it must be a long or long
1285 // long value. ISO C does not support this, but GCC does as an extension,
1286 // emit a warning.
Chris Lattner206754a2007-08-28 06:15:15 +00001287 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner435c3fd2007-08-28 05:10:31 +00001288
1289
Chris Lattner206754a2007-08-28 06:15:15 +00001290 // Verify that all the values are okay, compute the size of the values, and
1291 // reverse the list.
1292 unsigned NumNegativeBits = 0;
1293 unsigned NumPositiveBits = 0;
1294
1295 // Keep track of whether all elements have type int.
1296 bool AllElementsInt = true;
1297
Chris Lattner4b009652007-07-25 00:24:17 +00001298 EnumConstantDecl *EltList = 0;
1299 for (unsigned i = 0; i != NumElements; ++i) {
1300 EnumConstantDecl *ECD =
1301 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1302 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001303
1304 // If the enum value doesn't fit in an int, emit an extension warning.
1305 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1306 "Should have promoted value to int");
1307 const llvm::APSInt &InitVal = ECD->getInitVal();
1308 if (InitVal.getBitWidth() > IntWidth) {
1309 llvm::APSInt V(InitVal);
1310 V.trunc(IntWidth);
1311 V.extend(InitVal.getBitWidth());
1312 if (V != InitVal)
1313 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1314 InitVal.toString());
1315 }
Chris Lattner206754a2007-08-28 06:15:15 +00001316
1317 // Keep track of the size of positive and negative values.
1318 if (InitVal.isUnsigned() || !InitVal.isNegative())
1319 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1320 else
1321 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001322
Chris Lattner206754a2007-08-28 06:15:15 +00001323 // Keep track of whether every enum element has type int (very commmon).
1324 if (AllElementsInt)
1325 AllElementsInt = ECD->getType() == Context.IntTy;
1326
Chris Lattner4b009652007-07-25 00:24:17 +00001327 ECD->setNextDeclarator(EltList);
1328 EltList = ECD;
1329 }
1330
Chris Lattner206754a2007-08-28 06:15:15 +00001331 // Figure out the type that should be used for this enum.
1332 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1333 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001334 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001335
1336 if (NumNegativeBits) {
1337 // If there is a negative value, figure out the smallest integer type (of
1338 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001339 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001340 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001341 BestWidth = IntWidth;
1342 } else {
1343 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1344 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001345 BestType = Context.LongTy;
1346 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001347 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1348 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001349 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1350 BestType = Context.LongLongTy;
1351 }
1352 }
1353 } else {
1354 // If there is no negative value, figure out which of uint, ulong, ulonglong
1355 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001356 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001357 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001358 BestWidth = IntWidth;
1359 } else if (NumPositiveBits <=
1360 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattner206754a2007-08-28 06:15:15 +00001361 BestType = Context.UnsignedLongTy;
1362 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001363 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1364 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001365 "How could an initializer get larger than ULL?");
1366 BestType = Context.UnsignedLongLongTy;
1367 }
1368 }
1369
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001370 // Loop over all of the enumerator constants, changing their types to match
1371 // the type of the enum if needed.
1372 for (unsigned i = 0; i != NumElements; ++i) {
1373 EnumConstantDecl *ECD =
1374 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1375 if (!ECD) continue; // Already issued a diagnostic.
1376
1377 // Standard C says the enumerators have int type, but we allow, as an
1378 // extension, the enumerators to be larger than int size. If each
1379 // enumerator value fits in an int, type it as an int, otherwise type it the
1380 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1381 // that X has type 'int', not 'unsigned'.
1382 if (ECD->getType() == Context.IntTy)
1383 continue; // Already int type.
1384
1385 // Determine whether the value fits into an int.
1386 llvm::APSInt InitVal = ECD->getInitVal();
1387 bool FitsInInt;
1388 if (InitVal.isUnsigned() || !InitVal.isNegative())
1389 FitsInInt = InitVal.getActiveBits() < IntWidth;
1390 else
1391 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1392
1393 // If it fits into an integer type, force it. Otherwise force it to match
1394 // the enum decl type.
1395 QualType NewTy;
1396 unsigned NewWidth;
1397 bool NewSign;
1398 if (FitsInInt) {
1399 NewTy = Context.IntTy;
1400 NewWidth = IntWidth;
1401 NewSign = true;
1402 } else if (ECD->getType() == BestType) {
1403 // Already the right type!
1404 continue;
1405 } else {
1406 NewTy = BestType;
1407 NewWidth = BestWidth;
1408 NewSign = BestType->isSignedIntegerType();
1409 }
1410
1411 // Adjust the APSInt value.
1412 InitVal.extOrTrunc(NewWidth);
1413 InitVal.setIsSigned(NewSign);
1414 ECD->setInitVal(InitVal);
1415
1416 // Adjust the Expr initializer and type.
1417 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1418 ECD->setType(NewTy);
1419 }
Chris Lattner206754a2007-08-28 06:15:15 +00001420
Chris Lattner90a018d2007-08-28 18:24:31 +00001421 Enum->defineElements(EltList, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00001422}
1423
1424void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1425 if (!current) return;
1426
1427 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1428 // remember this in the LastInGroupList list.
1429 if (last)
1430 LastInGroupList.push_back((Decl*)last);
1431}
1432
1433void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1434 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1435 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1436 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1437 if (!newType.isNull()) // install the new vector type into the decl
1438 vDecl->setType(newType);
1439 }
1440 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1441 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1442 rawAttr);
1443 if (!newType.isNull()) // install the new vector type into the decl
1444 tDecl->setUnderlyingType(newType);
1445 }
1446 }
1447 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroff82113e32007-07-29 16:33:31 +00001448 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1449 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1450 else
Chris Lattner4b009652007-07-25 00:24:17 +00001451 Diag(rawAttr->getAttributeLoc(),
1452 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner4b009652007-07-25 00:24:17 +00001453 }
1454 // FIXME: add other attributes...
1455}
1456
1457void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1458 AttributeList *declarator_postfix) {
1459 while (declspec_prefix) {
1460 HandleDeclAttribute(New, declspec_prefix);
1461 declspec_prefix = declspec_prefix->getNext();
1462 }
1463 while (declarator_postfix) {
1464 HandleDeclAttribute(New, declarator_postfix);
1465 declarator_postfix = declarator_postfix->getNext();
1466 }
1467}
1468
Steve Naroff82113e32007-07-29 16:33:31 +00001469void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1470 AttributeList *rawAttr) {
1471 QualType curType = tDecl->getUnderlyingType();
Chris Lattner4b009652007-07-25 00:24:17 +00001472 // check the attribute arugments.
1473 if (rawAttr->getNumArgs() != 1) {
1474 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1475 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001476 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001477 }
1478 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1479 llvm::APSInt vecSize(32);
1480 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1481 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1482 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001483 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001484 }
1485 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1486 // in conjunction with complex types (pointers, arrays, functions, etc.).
1487 Type *canonType = curType.getCanonicalType().getTypePtr();
1488 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1489 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1490 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001491 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001492 }
1493 // unlike gcc's vector_size attribute, the size is specified as the
1494 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00001495 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00001496
1497 if (vectorSize == 0) {
1498 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1499 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001500 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001501 }
Steve Naroff82113e32007-07-29 16:33:31 +00001502 // Instantiate/Install the vector type, the number of elements is > 0.
1503 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1504 // Remember this typedef decl, we will need it later for diagnostics.
1505 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001506}
1507
1508QualType Sema::HandleVectorTypeAttribute(QualType curType,
1509 AttributeList *rawAttr) {
1510 // check the attribute arugments.
1511 if (rawAttr->getNumArgs() != 1) {
1512 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1513 std::string("1"));
1514 return QualType();
1515 }
1516 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1517 llvm::APSInt vecSize(32);
1518 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1519 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1520 sizeExpr->getSourceRange());
1521 return QualType();
1522 }
1523 // navigate to the base type - we need to provide for vector pointers,
1524 // vector arrays, and functions returning vectors.
1525 Type *canonType = curType.getCanonicalType().getTypePtr();
1526
1527 if (canonType->isPointerType() || canonType->isArrayType() ||
1528 canonType->isFunctionType()) {
1529 assert(1 && "HandleVector(): Complex type construction unimplemented");
1530 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1531 do {
1532 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1533 canonType = PT->getPointeeType().getTypePtr();
1534 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1535 canonType = AT->getElementType().getTypePtr();
1536 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1537 canonType = FT->getResultType().getTypePtr();
1538 } while (canonType->isPointerType() || canonType->isArrayType() ||
1539 canonType->isFunctionType());
1540 */
1541 }
1542 // the base type must be integer or float.
1543 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1544 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1545 curType.getCanonicalType().getAsString());
1546 return QualType();
1547 }
Chris Lattner3496d522007-09-04 02:45:27 +00001548 unsigned typeSize = static_cast<unsigned>(
1549 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Chris Lattner4b009652007-07-25 00:24:17 +00001550 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00001551 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00001552
1553 // the vector size needs to be an integral multiple of the type size.
1554 if (vectorSize % typeSize) {
1555 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1556 sizeExpr->getSourceRange());
1557 return QualType();
1558 }
1559 if (vectorSize == 0) {
1560 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1561 sizeExpr->getSourceRange());
1562 return QualType();
1563 }
1564 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1565 // the number of elements to be a power of two (unlike GCC).
1566 // Instantiate the vector type, the number of elements is > 0.
1567 return Context.getVectorType(curType, vectorSize/typeSize);
1568}
1569