blob: 6bfae197e3c12117cee1f1ffce0115b4427b2642 [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 *
Steve Naroffbb204692007-09-12 14:07:44 +0000430Sema::ParseDeclarator(Scope *S, Declarator &D, DeclTy *lastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000431 Decl *LastDeclarator = (Decl*)lastDeclarator;
432 IdentifierInfo *II = D.getIdentifier();
433
Chris Lattnere80a59c2007-07-25 00:24:17 +0000434 // All of these full declarators require an identifier. If it doesn't have
435 // one, the ParsedFreeStandingDeclSpec action should be used.
436 if (II == 0) {
Chris Lattner98e08632007-08-28 06:17:15 +0000437 Diag(D.getDeclSpec().getSourceRange().Begin(),
438 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000439 D.getDeclSpec().getSourceRange(), D.getSourceRange());
440 return 0;
441 }
442
Chris Lattner31e05722007-08-26 06:24:45 +0000443 // The scope passed in may not be a decl scope. Zip up the scope tree until
444 // we find one that is.
445 while ((S->getFlags() & Scope::DeclScope) == 0)
446 S = S->getParent();
447
Reid Spencer5f016e22007-07-11 17:01:13 +0000448 // See if this is a redefinition of a variable in the same scope.
449 Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
450 D.getIdentifierLoc(), S);
451 if (PrevDecl && !S->isDeclScope(PrevDecl))
452 PrevDecl = 0; // If in outer scope, it isn't the same thing.
453
454 Decl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000455 bool InvalidDecl = false;
456
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
458 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
459 if (!NewTD) return 0;
460
461 // Handle attributes prior to checking for duplicates in MergeVarDecl
462 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
463 D.getAttributes());
464 // Merge the decl with the existing one if appropriate.
465 if (PrevDecl) {
466 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
467 if (NewTD == 0) return 0;
468 }
469 New = NewTD;
470 if (S->getParent() == 0) {
471 // C99 6.7.7p2: If a typedef name specifies a variably modified type
472 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000473 if (const VariableArrayType *VAT =
474 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
475 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
476 VAT->getSizeExpr()->getSourceRange());
477 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000478 }
479 }
480 } else if (D.isFunctionDeclarator()) {
481 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000482 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000483
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 FunctionDecl::StorageClass SC;
485 switch (D.getDeclSpec().getStorageClassSpec()) {
486 default: assert(0 && "Unknown storage class!");
487 case DeclSpec::SCS_auto:
488 case DeclSpec::SCS_register:
489 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
490 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000491 InvalidDecl = true;
492 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000493 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
494 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
495 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
496 }
497
498 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000499 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 LastDeclarator);
501
502 // Merge the decl with the existing one if appropriate.
503 if (PrevDecl) {
504 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
505 if (NewFD == 0) return 0;
506 }
507 New = NewFD;
508 } else {
509 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff53a32342007-08-28 18:45:29 +0000510 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000511
512 VarDecl *NewVD;
513 VarDecl::StorageClass SC;
514 switch (D.getDeclSpec().getStorageClassSpec()) {
515 default: assert(0 && "Unknown storage class!");
516 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
517 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
518 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
519 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
520 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
521 }
522 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 // C99 6.9p2: The storage-class specifiers auto and register shall not
524 // appear in the declaration specifiers in an external declaration.
525 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
526 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
527 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000528 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000529 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000530 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000531 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000533 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000534 // Handle attributes prior to checking for duplicates in MergeVarDecl
535 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
536 D.getAttributes());
537
538 // Merge the decl with the existing one if appropriate.
539 if (PrevDecl) {
540 NewVD = MergeVarDecl(NewVD, PrevDecl);
541 if (NewVD == 0) return 0;
542 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 New = NewVD;
544 }
545
546 // If this has an identifier, add it to the scope stack.
547 if (II) {
548 New->setNext(II->getFETokenInfo<Decl>());
549 II->setFETokenInfo(New);
550 S->AddDecl(New);
551 }
552
553 if (S->getParent() == 0)
554 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +0000555
556 // If any semantic error occurred, mark the decl as invalid.
557 if (D.getInvalidType() || InvalidDecl)
558 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000559
560 return New;
561}
562
Steve Naroffbb204692007-09-12 14:07:44 +0000563void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
564 VarDecl *Dcl = dyn_cast<VarDecl>(static_cast<Decl *>(dcl));
565 Expr *Init = static_cast<Expr *>(init);
566
567 assert((Dcl && Init) && "missing decl or initializer");
568
569 // FIXME: moved these directly from ParseDeclarator(). Need to convert
570 // asserts to actual error diagnostics!
571 if (isa<FunctionDecl>(Dcl))
572 assert(0 && "Can't have an initializer for a functiondecl!");
573 if (isa<TypedefDecl>(Dcl))
574 assert(0 && "Can't have an initializer for a typedef!");
575
576 // Get the decls type and save a reference for later, since
577 // CheckInitializer may change it.
578 QualType DclT = Dcl->getType(), SavT = DclT;
579 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(Dcl)) {
580 VarDecl::StorageClass SC = BVD->getStorageClass();
581 if (SC == VarDecl::Extern) { // C99 6.7.8p5
582 Diag(Dcl->getLocation(), diag::err_block_extern_cant_init);
583 BVD->setInvalidDecl();
584 } else if (!BVD->isInvalidDecl()) {
585 CheckInitializer(Init, DclT, SC == VarDecl::Static);
586 }
587 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(Dcl)) {
588 if (FVD->getStorageClass() == VarDecl::Extern)
589 Diag(Dcl->getLocation(), diag::warn_extern_init);
590 if (!FVD->isInvalidDecl())
591 CheckInitializer(Init, DclT, true);
592 }
593 // If the type changed, it means we had an incomplete type that was
594 // completed by the initializer. For example:
595 // int ary[] = { 1, 3, 5 };
596 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
597 if (!Dcl->isInvalidDecl() && (DclT != SavT))
598 Dcl->setType(DclT);
599
600 // Attach the initializer to the decl.
601 Dcl->setInit(Init);
602 return;
603}
604
Reid Spencer5f016e22007-07-11 17:01:13 +0000605/// The declarators are chained together backwards, reverse the list.
606Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
607 // Often we have single declarators, handle them quickly.
608 Decl *Group = static_cast<Decl*>(group);
Steve Naroffbb204692007-09-12 14:07:44 +0000609 if (Group == 0)
610 return 0;
611
Reid Spencer5f016e22007-07-11 17:01:13 +0000612 Decl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000613 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000614 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000615 else { // reverse the list.
616 while (Group) {
617 Decl *Next = Group->getNextDeclarator();
618 Group->setNextDeclarator(NewGroup);
619 NewGroup = Group;
620 Group = Next;
621 }
622 }
623 // Perform semantic analysis that depends on having fully processed both
624 // the declarator and initializer.
625 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
626 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
627 if (!IDecl)
628 continue;
629 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
630 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
631 QualType T = IDecl->getType();
632
633 // C99 6.7.5.2p2: If an identifier is declared to be an object with
634 // static storage duration, it shall not have a variable length array.
635 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
636 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
637 if (VLA->getSizeExpr()) {
638 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
639 IDecl->setInvalidDecl();
640 }
641 }
642 }
643 // Block scope. C99 6.7p7: If an identifier for an object is declared with
644 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
645 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
646 if (T->isIncompleteType()) {
647 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
648 T.getAsString());
649 IDecl->setInvalidDecl();
650 }
651 }
652 // File scope. C99 6.9.2p2: A declaration of an identifier for and
653 // object that has file scope without an initializer, and without a
654 // storage-class specifier or with the storage-class specifier "static",
655 // constitutes a tentative definition. Note: A tentative definition with
656 // external linkage is valid (C99 6.2.2p5).
657 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
658 // C99 6.9.2p3: If the declaration of an identifier for an object is
659 // a tentative definition and has internal linkage (C99 6.2.2p3), the
660 // declared type shall not be an incomplete type.
661 if (T->isIncompleteType()) {
662 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
663 T.getAsString());
664 IDecl->setInvalidDecl();
665 }
666 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000667 }
668 return NewGroup;
669}
Steve Naroffe1223f72007-08-28 03:03:08 +0000670
671// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000672ParmVarDecl *
673Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
674 Scope *FnScope) {
675 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
676
677 IdentifierInfo *II = PI.Ident;
678 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
679 // Can this happen for params? We already checked that they don't conflict
680 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000681 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000682 PI.IdentLoc, FnScope)) {
683
684 }
685
686 // FIXME: Handle storage class (auto, register). No declarator?
687 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000688
689 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
690 // Doing the promotion here has a win and a loss. The win is the type for
691 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
692 // code generator). The loss is the orginal type isn't preserved. For example:
693 //
694 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
695 // int blockvardecl[5];
696 // sizeof(parmvardecl); // size == 4
697 // sizeof(blockvardecl); // size == 20
698 // }
699 //
700 // For expressions, all implicit conversions are captured using the
701 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
702 //
703 // FIXME: If a source translation tool needs to see the original type, then
704 // we need to consider storing both types (in ParmVarDecl)...
705 //
706 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
707 if (const ArrayType *AT = parmDeclType->getAsArrayType())
708 parmDeclType = Context.getPointerType(AT->getElementType());
709 else if (parmDeclType->isFunctionType())
710 parmDeclType = Context.getPointerType(parmDeclType);
711
712 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff53a32342007-08-28 18:45:29 +0000713 VarDecl::None, 0);
714 if (PI.InvalidType)
715 New->setInvalidDecl();
716
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 // If this has an identifier, add it to the scope stack.
718 if (II) {
719 New->setNext(II->getFETokenInfo<Decl>());
720 II->setFETokenInfo(New);
721 FnScope->AddDecl(New);
722 }
723
724 return New;
725}
726
727
728Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
729 assert(CurFunctionDecl == 0 && "Function parsing confused");
730 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
731 "Not a function declarator!");
732 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
733
734 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
735 // for a K&R function.
736 if (!FTI.hasPrototype) {
737 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
738 if (FTI.ArgInfo[i].TypeInfo == 0) {
739 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
740 FTI.ArgInfo[i].Ident->getName());
741 // Implicitly declare the argument as type 'int' for lack of a better
742 // type.
743 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
744 }
745 }
746
747 // Since this is a function definition, act as though we have information
748 // about the arguments.
749 FTI.hasPrototype = true;
750 } else {
751 // FIXME: Diagnose arguments without names in C.
752
753 }
754
755 Scope *GlobalScope = FnBodyScope->getParent();
756
757 FunctionDecl *FD =
Steve Naroffbb204692007-09-12 14:07:44 +0000758 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000759 CurFunctionDecl = FD;
760
761 // Create Decl objects for each parameter, adding them to the FunctionDecl.
762 llvm::SmallVector<ParmVarDecl*, 16> Params;
763
764 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
765 // no arguments, not a function that takes a single void argument.
766 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
767 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
768 // empty arg list, don't push any params.
769 } else {
770 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
771 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
772 }
773
774 FD->setParams(&Params[0], Params.size());
775
776 return FD;
777}
778
779Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
780 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
781 FD->setBody((Stmt*)Body);
782
783 assert(FD == CurFunctionDecl && "Function parsing confused");
784 CurFunctionDecl = 0;
785
786 // Verify and clean out per-function state.
787
788 // Check goto/label use.
789 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
790 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
791 // Verify that we have no forward references left. If so, there was a goto
792 // or address of a label taken, but no definition of it. Label fwd
793 // definitions are indicated with a null substmt.
794 if (I->second->getSubStmt() == 0) {
795 LabelStmt *L = I->second;
796 // Emit error.
797 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
798
799 // At this point, we have gotos that use the bogus label. Stitch it into
800 // the function body so that they aren't leaked and that the AST is well
801 // formed.
802 L->setSubStmt(new NullStmt(L->getIdentLoc()));
803 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
804 }
805 }
806 LabelMap.clear();
807
808 return FD;
809}
810
811
812/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
813/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
814Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
815 Scope *S) {
816 if (getLangOptions().C99) // Extension in C99.
817 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
818 else // Legal in C90, but warn about it.
819 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
820
821 // FIXME: handle stuff like:
822 // void foo() { extern float X(); }
823 // void bar() { X(); } <-- implicit decl for X in another scope.
824
825 // Set a Declarator for the implicit definition: int foo();
826 const char *Dummy;
827 DeclSpec DS;
828 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
829 Error = Error; // Silence warning.
830 assert(!Error && "Error setting up implicit decl!");
831 Declarator D(DS, Declarator::BlockContext);
832 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
833 D.SetIdentifier(&II, Loc);
834
835 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000836 if (Scope *FnS = S->getFnParent())
837 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000838 while (S->getParent())
839 S = S->getParent();
840
Steve Naroffbb204692007-09-12 14:07:44 +0000841 return static_cast<Decl*>(ParseDeclarator(S, D, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000842}
843
844
845TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
846 Decl *LastDeclarator) {
847 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
848
849 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000850 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000851
852 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +0000853 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
854 T, LastDeclarator);
855 if (D.getInvalidType())
856 NewTD->setInvalidDecl();
857 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000858}
859
Steve Naroff3536b442007-09-06 21:24:23 +0000860Sema::DeclTy *Sema::ObjcStartClassInterface(SourceLocation AtInterfaceLoc,
861 IdentifierInfo *ClassName, SourceLocation ClassLoc,
862 IdentifierInfo *SuperName, SourceLocation SuperLoc,
863 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
864 AttributeList *AttrList) {
865 assert(ClassName && "Missing class identifier");
866 ObjcInterfaceDecl *IDecl;
867
868 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, ClassName);
869
870 // Chain & install the interface decl into the identifier.
871 IDecl->setNext(ClassName->getFETokenInfo<Decl>());
872 ClassName->setFETokenInfo(IDecl);
873 return IDecl;
874}
875
Steve Naroff44739212007-09-11 21:17:26 +0000876void Sema::ObjcAddInstanceVariable(DeclTy *ClassDecl, DeclTy *Ivar,
877 tok::ObjCKeywordKind visibility) {
878 assert((ClassDecl && Ivar) && "missing class or instance variable");
879 ObjcInterfaceDecl *OInterface = dyn_cast<ObjcInterfaceDecl>(
880 static_cast<Decl *>(ClassDecl));
881 ObjcIvarDecl *OIvar = dyn_cast<ObjcIvarDecl>(static_cast<Decl *>(Ivar));
882
883 assert((OInterface && OIvar) && "mistyped class or instance variable");
884
885 switch (visibility) {
886 case tok::objc_private:
887 OIvar->setAccessControl(ObjcIvarDecl::Private);
888 break;
889 case tok::objc_public:
890 OIvar->setAccessControl(ObjcIvarDecl::Public);
891 break;
892 case tok::objc_protected:
893 OIvar->setAccessControl(ObjcIvarDecl::Protected);
894 break;
895 case tok::objc_package:
896 OIvar->setAccessControl(ObjcIvarDecl::Package);
897 break;
898 default:
899 OIvar->setAccessControl(ObjcIvarDecl::None);
900 break;
901 }
902 // FIXME: add to the class...
903}
904
Steve Naroff3536b442007-09-06 21:24:23 +0000905/// ObjcClassDeclaration -
906/// Scope will always be top level file scope.
907Action::DeclTy *
908Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
909 IdentifierInfo **IdentList, unsigned NumElts) {
910 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
911
912 for (unsigned i = 0; i != NumElts; ++i) {
913 ObjcInterfaceDecl *IDecl;
914
Steve Naroff2bd42fa2007-09-10 20:51:04 +0000915 // FIXME: before we create one, look up the interface decl in a hash table.
Steve Naroff3536b442007-09-06 21:24:23 +0000916 IDecl = new ObjcInterfaceDecl(SourceLocation(), IdentList[i], true);
917 // Chain & install the interface decl into the identifier.
918 IDecl->setNext(IdentList[i]->getFETokenInfo<Decl>());
919 IdentList[i]->setFETokenInfo(IDecl);
920
921 // Remember that this needs to be removed when the scope is popped.
922 S->AddDecl(IdentList[i]);
923
924 CDecl->setInterfaceDecl((int)i, IDecl);
925 }
926 return CDecl;
927}
928
Reid Spencer5f016e22007-07-11 17:01:13 +0000929
930/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
931/// former case, Name will be non-null. In the later case, Name will be null.
932/// TagType indicates what kind of tag this is. TK indicates whether this is a
933/// reference/declaration/definition of a tag.
934Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
935 SourceLocation KWLoc, IdentifierInfo *Name,
936 SourceLocation NameLoc, AttributeList *Attr) {
937 // If this is a use of an existing tag, it must have a name.
938 assert((Name != 0 || TK == TK_Definition) &&
939 "Nameless record must be a definition!");
940
941 Decl::Kind Kind;
942 switch (TagType) {
943 default: assert(0 && "Unknown tag type!");
944 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
945 case DeclSpec::TST_union: Kind = Decl::Union; break;
946//case DeclSpec::TST_class: Kind = Decl::Class; break;
947 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
948 }
949
950 // If this is a named struct, check to see if there was a previous forward
951 // declaration or definition.
952 if (TagDecl *PrevDecl =
953 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
954 NameLoc, S))) {
955
956 // If this is a use of a previous tag, or if the tag is already declared in
957 // the same scope (so that the definition/declaration completes or
958 // rementions the tag), reuse the decl.
959 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
960 // Make sure that this wasn't declared as an enum and now used as a struct
961 // or something similar.
962 if (PrevDecl->getKind() != Kind) {
963 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
964 Diag(PrevDecl->getLocation(), diag::err_previous_use);
965 }
966
967 // If this is a use or a forward declaration, we're good.
968 if (TK != TK_Definition)
969 return PrevDecl;
970
971 // Diagnose attempts to redefine a tag.
972 if (PrevDecl->isDefinition()) {
973 Diag(NameLoc, diag::err_redefinition, Name->getName());
974 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
975 // If this is a redefinition, recover by making this struct be
976 // anonymous, which will make any later references get the previous
977 // definition.
978 Name = 0;
979 } else {
980 // Okay, this is definition of a previously declared or referenced tag.
981 // Move the location of the decl to be the definition site.
982 PrevDecl->setLocation(NameLoc);
983 return PrevDecl;
984 }
985 }
986 // If we get here, this is a definition of a new struct type in a nested
987 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
988 // type.
989 }
990
991 // If there is an identifier, use the location of the identifier as the
992 // location of the decl, otherwise use the location of the struct/union
993 // keyword.
994 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
995
996 // Otherwise, if this is the first time we've seen this tag, create the decl.
997 TagDecl *New;
998 switch (Kind) {
999 default: assert(0 && "Unknown tag kind!");
1000 case Decl::Enum:
1001 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1002 // enum X { A, B, C } D; D should chain to X.
1003 New = new EnumDecl(Loc, Name, 0);
1004 // If this is an undefined enum, warn.
1005 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1006 break;
1007 case Decl::Union:
1008 case Decl::Struct:
1009 case Decl::Class:
1010 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1011 // struct X { int A; } D; D should chain to X.
1012 New = new RecordDecl(Kind, Loc, Name, 0);
1013 break;
1014 }
1015
1016 // If this has an identifier, add it to the scope stack.
1017 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001018 // The scope passed in may not be a decl scope. Zip up the scope tree until
1019 // we find one that is.
1020 while ((S->getFlags() & Scope::DeclScope) == 0)
1021 S = S->getParent();
1022
1023 // Add it to the decl chain.
Reid Spencer5f016e22007-07-11 17:01:13 +00001024 New->setNext(Name->getFETokenInfo<Decl>());
1025 Name->setFETokenInfo(New);
1026 S->AddDecl(New);
1027 }
1028
1029 return New;
1030}
1031
1032/// ParseField - Each field of a struct/union/class is passed into this in order
1033/// to create a FieldDecl object for it.
1034Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
1035 SourceLocation DeclStart,
1036 Declarator &D, ExprTy *BitfieldWidth) {
1037 IdentifierInfo *II = D.getIdentifier();
1038 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001039 SourceLocation Loc = DeclStart;
1040 if (II) Loc = D.getIdentifierLoc();
1041
1042 // FIXME: Unnamed fields can be handled in various different ways, for
1043 // example, unnamed unions inject all members into the struct namespace!
1044
1045
1046 if (BitWidth) {
1047 // TODO: Validate.
1048 //printf("WARNING: BITFIELDS IGNORED!\n");
1049
1050 // 6.7.2.1p3
1051 // 6.7.2.1p4
1052
1053 } else {
1054 // Not a bitfield.
1055
1056 // validate II.
1057
1058 }
1059
1060 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001061 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1062 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001063
Reid Spencer5f016e22007-07-11 17:01:13 +00001064 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1065 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001066 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1067 Diag(Loc, diag::err_typecheck_illegal_vla,
1068 VAT->getSizeExpr()->getSourceRange());
1069 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001071 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001072 FieldDecl *NewFD;
1073
1074 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
1075 NewFD = new FieldDecl(Loc, II, T, 0);
1076 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl)))
1077 NewFD = new ObjcIvarDecl(Loc, II, T, 0);
1078 else
1079 assert(0 && "Sema::ParseField(): Unknown TagDecl");
1080
Steve Naroff5912a352007-08-28 20:14:24 +00001081 if (D.getInvalidType() || InvalidDecl)
1082 NewFD->setInvalidDecl();
1083 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001084}
1085
1086void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
1087 DeclTy **Fields, unsigned NumFields) {
1088 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
1089 if (Record->isDefinition()) {
1090 // Diagnose code like:
1091 // struct S { struct S {} X; };
1092 // We discover this when we complete the outer S. Reject and ignore the
1093 // outer S.
1094 Diag(Record->getLocation(), diag::err_nested_redefinition,
1095 Record->getKindName());
1096 Diag(RecLoc, diag::err_previous_definition);
1097 return;
1098 }
1099
1100 // Verify that all the fields are okay.
1101 unsigned NumNamedMembers = 0;
1102 llvm::SmallVector<FieldDecl*, 32> RecFields;
1103 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
1104
1105 for (unsigned i = 0; i != NumFields; ++i) {
1106 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1107 if (!FD) continue; // Already issued a diagnostic.
1108
1109 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001110 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001111
1112 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001113 if (FDTy->isFunctionType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001114 Diag(FD->getLocation(), diag::err_field_declared_as_function,
1115 FD->getName());
1116 delete FD;
1117 continue;
1118 }
1119
1120 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1121 if (FDTy->isIncompleteType()) {
1122 if (i != NumFields-1 || // ... that the last member ...
1123 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001124 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001125 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1126 delete FD;
1127 continue;
1128 }
1129 if (NumNamedMembers < 1) { //... must have more than named member ...
1130 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1131 FD->getName());
1132 delete FD;
1133 continue;
1134 }
1135
1136 // Okay, we have a legal flexible array member at the end of the struct.
1137 Record->setHasFlexibleArrayMember(true);
1138 }
1139
1140
1141 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1142 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001143 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001144 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1145 // If this is a member of a union, then entire union becomes "flexible".
1146 if (Record->getKind() == Decl::Union) {
1147 Record->setHasFlexibleArrayMember(true);
1148 } else {
1149 // If this is a struct/class and this is not the last element, reject
1150 // it. Note that GCC supports variable sized arrays in the middle of
1151 // structures.
1152 if (i != NumFields-1) {
1153 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1154 FD->getName());
1155 delete FD;
1156 continue;
1157 }
1158
1159 // We support flexible arrays at the end of structs in other structs
1160 // as an extension.
1161 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1162 FD->getName());
1163 Record->setHasFlexibleArrayMember(true);
1164 }
1165 }
1166 }
1167
1168 // Keep track of the number of named members.
1169 if (IdentifierInfo *II = FD->getIdentifier()) {
1170 // Detect duplicate member names.
1171 if (!FieldIDs.insert(II)) {
1172 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1173 // Find the previous decl.
1174 SourceLocation PrevLoc;
1175 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1176 assert(i != e && "Didn't find previous def!");
1177 if (RecFields[i]->getIdentifier() == II) {
1178 PrevLoc = RecFields[i]->getLocation();
1179 break;
1180 }
1181 }
1182 Diag(PrevLoc, diag::err_previous_definition);
1183 delete FD;
1184 continue;
1185 }
1186 ++NumNamedMembers;
1187 }
1188
1189 // Remember good fields.
1190 RecFields.push_back(FD);
1191 }
1192
1193
1194 // Okay, we successfully defined 'Record'.
1195 Record->defineBody(&RecFields[0], RecFields.size());
1196}
1197
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001198void Sema::ObjcAddMethodsToClass(DeclTy *ClassDecl,
1199 DeclTy **allMethods, unsigned allNum) {
1200 // FIXME: Add method insertion code here.
1201#if 0
1202 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1203 static_cast<Decl*>(ClassDecl));
1204 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1205 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1206
1207 for (unsigned i = 0; i < allNum; i++ ) {
1208 ObjcMethodDecl *Method =
1209 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1210 if (!Method) continue; // Already issued a diagnostic.
1211 if (Method->isInstance())
1212 insMethods.push_back(Method);
1213 else
1214 clsMethods.push_back(Method);
1215 }
1216 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1217 &clsMethods[0], clsMethods.size());
1218#endif
1219 return;
1220}
1221
Reid Spencer5f016e22007-07-11 17:01:13 +00001222Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
1223 DeclTy *lastEnumConst,
1224 SourceLocation IdLoc, IdentifierInfo *Id,
1225 SourceLocation EqualLoc, ExprTy *val) {
1226 theEnumDecl = theEnumDecl; // silence unused warning.
1227 EnumConstantDecl *LastEnumConst =
1228 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1229 Expr *Val = static_cast<Expr*>(val);
1230
Chris Lattner31e05722007-08-26 06:24:45 +00001231 // The scope passed in may not be a decl scope. Zip up the scope tree until
1232 // we find one that is.
1233 while ((S->getFlags() & Scope::DeclScope) == 0)
1234 S = S->getParent();
1235
Reid Spencer5f016e22007-07-11 17:01:13 +00001236 // Verify that there isn't already something declared with this name in this
1237 // scope.
1238 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
1239 if (S->isDeclScope(PrevDecl)) {
1240 if (isa<EnumConstantDecl>(PrevDecl))
1241 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1242 else
1243 Diag(IdLoc, diag::err_redefinition, Id->getName());
1244 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1245 // FIXME: Don't leak memory: delete Val;
1246 return 0;
1247 }
1248 }
1249
1250 llvm::APSInt EnumVal(32);
1251 QualType EltTy;
1252 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001253 // Make sure to promote the operand type to int.
1254 UsualUnaryConversions(Val);
1255
Reid Spencer5f016e22007-07-11 17:01:13 +00001256 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1257 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001258 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001259 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1260 Id->getName());
1261 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001262 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001263 } else {
1264 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001265 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001266 }
1267
1268 if (!Val) {
1269 if (LastEnumConst) {
1270 // Assign the last value + 1.
1271 EnumVal = LastEnumConst->getInitVal();
1272 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001273
1274 // Check for overflow on increment.
1275 if (EnumVal < LastEnumConst->getInitVal())
1276 Diag(IdLoc, diag::warn_enum_value_overflow);
1277
Chris Lattnerb7416f92007-08-27 17:37:24 +00001278 EltTy = LastEnumConst->getType();
1279 } else {
1280 // First value, set to zero.
1281 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001282 EnumVal.zextOrTrunc(
1283 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001284 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 }
1286
Reid Spencer5f016e22007-07-11 17:01:13 +00001287 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1288 LastEnumConst);
1289
1290 // Register this decl in the current scope stack.
1291 New->setNext(Id->getFETokenInfo<Decl>());
1292 Id->setFETokenInfo(New);
1293 S->AddDecl(New);
1294 return New;
1295}
1296
1297void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1298 DeclTy **Elements, unsigned NumElements) {
1299 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1300 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1301
Chris Lattnere37f0be2007-08-28 05:10:31 +00001302 // TODO: If the result value doesn't fit in an int, it must be a long or long
1303 // long value. ISO C does not support this, but GCC does as an extension,
1304 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001305 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001306
1307
Chris Lattnerac609682007-08-28 06:15:15 +00001308 // Verify that all the values are okay, compute the size of the values, and
1309 // reverse the list.
1310 unsigned NumNegativeBits = 0;
1311 unsigned NumPositiveBits = 0;
1312
1313 // Keep track of whether all elements have type int.
1314 bool AllElementsInt = true;
1315
Reid Spencer5f016e22007-07-11 17:01:13 +00001316 EnumConstantDecl *EltList = 0;
1317 for (unsigned i = 0; i != NumElements; ++i) {
1318 EnumConstantDecl *ECD =
1319 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1320 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001321
1322 // If the enum value doesn't fit in an int, emit an extension warning.
1323 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1324 "Should have promoted value to int");
1325 const llvm::APSInt &InitVal = ECD->getInitVal();
1326 if (InitVal.getBitWidth() > IntWidth) {
1327 llvm::APSInt V(InitVal);
1328 V.trunc(IntWidth);
1329 V.extend(InitVal.getBitWidth());
1330 if (V != InitVal)
1331 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1332 InitVal.toString());
1333 }
Chris Lattnerac609682007-08-28 06:15:15 +00001334
1335 // Keep track of the size of positive and negative values.
1336 if (InitVal.isUnsigned() || !InitVal.isNegative())
1337 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1338 else
1339 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001340
Chris Lattnerac609682007-08-28 06:15:15 +00001341 // Keep track of whether every enum element has type int (very commmon).
1342 if (AllElementsInt)
1343 AllElementsInt = ECD->getType() == Context.IntTy;
1344
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 ECD->setNextDeclarator(EltList);
1346 EltList = ECD;
1347 }
1348
Chris Lattnerac609682007-08-28 06:15:15 +00001349 // Figure out the type that should be used for this enum.
1350 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1351 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001352 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001353
1354 if (NumNegativeBits) {
1355 // If there is a negative value, figure out the smallest integer type (of
1356 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001357 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001358 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001359 BestWidth = IntWidth;
1360 } else {
1361 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1362 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001363 BestType = Context.LongTy;
1364 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001365 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1366 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001367 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1368 BestType = Context.LongLongTy;
1369 }
1370 }
1371 } else {
1372 // If there is no negative value, figure out which of uint, ulong, ulonglong
1373 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001374 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001375 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001376 BestWidth = IntWidth;
1377 } else if (NumPositiveBits <=
1378 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001379 BestType = Context.UnsignedLongTy;
1380 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001381 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1382 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001383 "How could an initializer get larger than ULL?");
1384 BestType = Context.UnsignedLongLongTy;
1385 }
1386 }
1387
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001388 // Loop over all of the enumerator constants, changing their types to match
1389 // the type of the enum if needed.
1390 for (unsigned i = 0; i != NumElements; ++i) {
1391 EnumConstantDecl *ECD =
1392 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1393 if (!ECD) continue; // Already issued a diagnostic.
1394
1395 // Standard C says the enumerators have int type, but we allow, as an
1396 // extension, the enumerators to be larger than int size. If each
1397 // enumerator value fits in an int, type it as an int, otherwise type it the
1398 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1399 // that X has type 'int', not 'unsigned'.
1400 if (ECD->getType() == Context.IntTy)
1401 continue; // Already int type.
1402
1403 // Determine whether the value fits into an int.
1404 llvm::APSInt InitVal = ECD->getInitVal();
1405 bool FitsInInt;
1406 if (InitVal.isUnsigned() || !InitVal.isNegative())
1407 FitsInInt = InitVal.getActiveBits() < IntWidth;
1408 else
1409 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1410
1411 // If it fits into an integer type, force it. Otherwise force it to match
1412 // the enum decl type.
1413 QualType NewTy;
1414 unsigned NewWidth;
1415 bool NewSign;
1416 if (FitsInInt) {
1417 NewTy = Context.IntTy;
1418 NewWidth = IntWidth;
1419 NewSign = true;
1420 } else if (ECD->getType() == BestType) {
1421 // Already the right type!
1422 continue;
1423 } else {
1424 NewTy = BestType;
1425 NewWidth = BestWidth;
1426 NewSign = BestType->isSignedIntegerType();
1427 }
1428
1429 // Adjust the APSInt value.
1430 InitVal.extOrTrunc(NewWidth);
1431 InitVal.setIsSigned(NewSign);
1432 ECD->setInitVal(InitVal);
1433
1434 // Adjust the Expr initializer and type.
1435 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1436 ECD->setType(NewTy);
1437 }
Chris Lattnerac609682007-08-28 06:15:15 +00001438
Chris Lattnere00b18c2007-08-28 18:24:31 +00001439 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001440}
1441
1442void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1443 if (!current) return;
1444
1445 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1446 // remember this in the LastInGroupList list.
1447 if (last)
1448 LastInGroupList.push_back((Decl*)last);
1449}
1450
1451void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1452 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1453 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1454 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1455 if (!newType.isNull()) // install the new vector type into the decl
1456 vDecl->setType(newType);
1457 }
1458 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1459 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1460 rawAttr);
1461 if (!newType.isNull()) // install the new vector type into the decl
1462 tDecl->setUnderlyingType(newType);
1463 }
1464 }
Steve Naroff73322922007-07-18 18:00:27 +00001465 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001466 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1467 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1468 else
Steve Naroff73322922007-07-18 18:00:27 +00001469 Diag(rawAttr->getAttributeLoc(),
1470 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00001471 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 // FIXME: add other attributes...
1473}
1474
1475void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1476 AttributeList *declarator_postfix) {
1477 while (declspec_prefix) {
1478 HandleDeclAttribute(New, declspec_prefix);
1479 declspec_prefix = declspec_prefix->getNext();
1480 }
1481 while (declarator_postfix) {
1482 HandleDeclAttribute(New, declarator_postfix);
1483 declarator_postfix = declarator_postfix->getNext();
1484 }
1485}
1486
Steve Naroffbea0b342007-07-29 16:33:31 +00001487void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1488 AttributeList *rawAttr) {
1489 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00001490 // check the attribute arugments.
1491 if (rawAttr->getNumArgs() != 1) {
1492 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1493 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001494 return;
Steve Naroff73322922007-07-18 18:00:27 +00001495 }
1496 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1497 llvm::APSInt vecSize(32);
1498 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1499 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1500 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001501 return;
Steve Naroff73322922007-07-18 18:00:27 +00001502 }
1503 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1504 // in conjunction with complex types (pointers, arrays, functions, etc.).
1505 Type *canonType = curType.getCanonicalType().getTypePtr();
1506 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1507 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1508 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001509 return;
Steve Naroff73322922007-07-18 18:00:27 +00001510 }
1511 // unlike gcc's vector_size attribute, the size is specified as the
1512 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001513 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001514
1515 if (vectorSize == 0) {
1516 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1517 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001518 return;
Steve Naroff73322922007-07-18 18:00:27 +00001519 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001520 // Instantiate/Install the vector type, the number of elements is > 0.
1521 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1522 // Remember this typedef decl, we will need it later for diagnostics.
1523 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001524}
1525
Reid Spencer5f016e22007-07-11 17:01:13 +00001526QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001527 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 // check the attribute arugments.
1529 if (rawAttr->getNumArgs() != 1) {
1530 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1531 std::string("1"));
1532 return QualType();
1533 }
1534 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1535 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001536 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1538 sizeExpr->getSourceRange());
1539 return QualType();
1540 }
1541 // navigate to the base type - we need to provide for vector pointers,
1542 // vector arrays, and functions returning vectors.
1543 Type *canonType = curType.getCanonicalType().getTypePtr();
1544
Steve Naroff73322922007-07-18 18:00:27 +00001545 if (canonType->isPointerType() || canonType->isArrayType() ||
1546 canonType->isFunctionType()) {
1547 assert(1 && "HandleVector(): Complex type construction unimplemented");
1548 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1549 do {
1550 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1551 canonType = PT->getPointeeType().getTypePtr();
1552 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1553 canonType = AT->getElementType().getTypePtr();
1554 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1555 canonType = FT->getResultType().getTypePtr();
1556 } while (canonType->isPointerType() || canonType->isArrayType() ||
1557 canonType->isFunctionType());
1558 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 }
1560 // the base type must be integer or float.
1561 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1562 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1563 curType.getCanonicalType().getAsString());
1564 return QualType();
1565 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00001566 unsigned typeSize = static_cast<unsigned>(
1567 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001568 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001569 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00001570
1571 // the vector size needs to be an integral multiple of the type size.
1572 if (vectorSize % typeSize) {
1573 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1574 sizeExpr->getSourceRange());
1575 return QualType();
1576 }
1577 if (vectorSize == 0) {
1578 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1579 sizeExpr->getSourceRange());
1580 return QualType();
1581 }
1582 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1583 // the number of elements to be a power of two (unlike GCC).
1584 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00001585 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001586}
1587