blob: 5eac645727775dec09d68f8676a3e742504351d9 [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 {
29 return dyn_cast_or_null<TypedefDecl>(II.getFETokenInfo<Decl>());
30}
31
32void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000033 if (S->decl_empty()) return;
34 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
35
Reid Spencer5f016e22007-07-11 17:01:13 +000036 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
37 I != E; ++I) {
38 Decl *D = static_cast<Decl*>(*I);
39 assert(D && "This decl didn't get pushed??");
40 IdentifierInfo *II = D->getIdentifier();
41 if (!II) continue;
42
43 // Unlink this decl from the identifier. Because the scope contains decls
44 // in an unordered collection, and because we have multiple identifier
45 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
46 if (II->getFETokenInfo<Decl>() == D) {
47 // Normal case, no multiple decls in different namespaces.
48 II->setFETokenInfo(D->getNext());
49 } else {
50 // Scan ahead. There are only three namespaces in C, so this loop can
51 // never execute more than 3 times.
52 Decl *SomeDecl = II->getFETokenInfo<Decl>();
53 while (SomeDecl->getNext() != D) {
54 SomeDecl = SomeDecl->getNext();
55 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
56 }
57 SomeDecl->setNext(D->getNext());
58 }
59
60 // This will have to be revisited for C++: there we want to nest stuff in
61 // namespace decls etc. Even for C, we might want a top-level translation
62 // unit decl or something.
63 if (!CurFunctionDecl)
64 continue;
65
66 // Chain this decl to the containing function, it now owns the memory for
67 // the decl.
68 D->setNext(CurFunctionDecl->getDeclChain());
69 CurFunctionDecl->setDeclChain(D);
70 }
71}
72
73/// LookupScopedDecl - Look up the inner-most declaration in the specified
74/// namespace.
75Decl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
76 SourceLocation IdLoc, Scope *S) {
77 if (II == 0) return 0;
78 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
79
80 // Scan up the scope chain looking for a decl that matches this identifier
81 // that is in the appropriate namespace. This search should not take long, as
82 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
83 for (Decl *D = II->getFETokenInfo<Decl>(); D; D = D->getNext())
84 if (D->getIdentifierNamespace() == NS)
85 return D;
86
87 // If we didn't find a use of this identifier, and if the identifier
88 // corresponds to a compiler builtin, create the decl object for the builtin
89 // now, injecting it into translation unit scope, and return it.
90 if (NS == Decl::IDNS_Ordinary) {
91 // If this is a builtin on some other target, or if this builtin varies
92 // across targets (e.g. in type), emit a diagnostic and mark the translation
93 // unit non-portable for using it.
94 if (II->isNonPortableBuiltin()) {
95 // Only emit this diagnostic once for this builtin.
96 II->setNonPortableBuiltin(false);
97 Context.Target.DiagnoseNonPortability(IdLoc,
98 diag::port_target_builtin_use);
99 }
100 // If this is a builtin on this (or all) targets, create the decl.
101 if (unsigned BuiltinID = II->getBuiltinID())
102 return LazilyCreateBuiltin(II, BuiltinID, S);
103 }
104 return 0;
105}
106
107/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
108/// lazily create a decl for it.
109Decl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
110 Builtin::ID BID = (Builtin::ID)bid;
111
112 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
113 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000114 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000115
116 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000117 if (Scope *FnS = S->getFnParent())
118 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 while (S->getParent())
120 S = S->getParent();
121 S->AddDecl(New);
122
123 // Add this decl to the end of the identifier info.
124 if (Decl *LastDecl = II->getFETokenInfo<Decl>()) {
125 // Scan until we find the last (outermost) decl in the id chain.
126 while (LastDecl->getNext())
127 LastDecl = LastDecl->getNext();
128 // Insert before (outside) it.
129 LastDecl->setNext(New);
130 } else {
131 II->setFETokenInfo(New);
132 }
133 // Make sure clients iterating over decls see this.
134 LastInGroupList.push_back(New);
135
136 return New;
137}
138
139/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
140/// and scope as a previous declaration 'Old'. Figure out how to resolve this
141/// situation, merging decls or emitting diagnostics as appropriate.
142///
143TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
144 // Verify the old decl was also a typedef.
145 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
146 if (!Old) {
147 Diag(New->getLocation(), diag::err_redefinition_different_kind,
148 New->getName());
149 Diag(OldD->getLocation(), diag::err_previous_definition);
150 return New;
151 }
152
153 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
154 // TODO: This is totally simplistic. It should handle merging functions
155 // together etc, merging extern int X; int X; ...
156 Diag(New->getLocation(), diag::err_redefinition, New->getName());
157 Diag(Old->getLocation(), diag::err_previous_definition);
158 return New;
159}
160
161/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
162/// and scope as a previous declaration 'Old'. Figure out how to resolve this
163/// situation, merging decls or emitting diagnostics as appropriate.
164///
165FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
166 // Verify the old decl was also a function.
167 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
168 if (!Old) {
169 Diag(New->getLocation(), diag::err_redefinition_different_kind,
170 New->getName());
171 Diag(OldD->getLocation(), diag::err_previous_definition);
172 return New;
173 }
174
175 // This is not right, but it's a start. If 'Old' is a function prototype with
176 // the same type as 'New', silently allow this. FIXME: We should link up decl
177 // objects here.
178 if (Old->getBody() == 0 &&
179 Old->getCanonicalType() == New->getCanonicalType()) {
180 return New;
181 }
182
183 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
184 // TODO: This is totally simplistic. It should handle merging functions
185 // together etc, merging extern int X; int X; ...
186 Diag(New->getLocation(), diag::err_redefinition, New->getName());
187 Diag(Old->getLocation(), diag::err_previous_definition);
188 return New;
189}
190
191/// MergeVarDecl - We just parsed a variable 'New' which has the same name
192/// and scope as a previous declaration 'Old'. Figure out how to resolve this
193/// situation, merging decls or emitting diagnostics as appropriate.
194///
195/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
196/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
197///
198VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
199 // Verify the old decl was also a variable.
200 VarDecl *Old = dyn_cast<VarDecl>(OldD);
201 if (!Old) {
202 Diag(New->getLocation(), diag::err_redefinition_different_kind,
203 New->getName());
204 Diag(OldD->getLocation(), diag::err_previous_definition);
205 return New;
206 }
Steve Narofffb22d962007-08-30 01:06:46 +0000207 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
208 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
209 bool OldIsTentative = false;
210
211 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
212 // Handle C "tentative" external object definitions. FIXME: finish!
213 if (!OldFSDecl->getInit() &&
214 (OldFSDecl->getStorageClass() == VarDecl::None ||
215 OldFSDecl->getStorageClass() == VarDecl::Static))
216 OldIsTentative = true;
217 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000218 // Verify the types match.
219 if (Old->getCanonicalType() != New->getCanonicalType()) {
220 Diag(New->getLocation(), diag::err_redefinition, New->getName());
221 Diag(Old->getLocation(), diag::err_previous_definition);
222 return New;
223 }
224 // We've verified the types match, now check if Old is "extern".
225 if (Old->getStorageClass() != VarDecl::Extern) {
226 Diag(New->getLocation(), diag::err_redefinition, New->getName());
227 Diag(Old->getLocation(), diag::err_previous_definition);
228 }
229 return New;
230}
231
232/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
233/// no declarator (e.g. "struct foo;") is parsed.
234Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
235 // TODO: emit error on 'int;' or 'const enum foo;'.
236 // TODO: emit error on 'typedef int;'
237 // if (!DS.isMissingDeclaratorOk()) Diag(...);
238
239 return 0;
240}
241
Steve Narofff0090632007-09-02 02:04:30 +0000242bool Sema::CheckSingleInitializer(Expr *Init, QualType DeclType) {
243 AssignmentCheckResult result;
244 SourceLocation loc = Init->getLocStart();
245 // Get the type before calling CheckSingleAssignmentConstraints(), since
246 // it can promote the expression.
247 QualType rhsType = Init->getType();
248
249 result = CheckSingleAssignmentConstraints(DeclType, Init);
250
251 // decode the result (notice that extensions still return a type).
252 switch (result) {
253 case Compatible:
254 break;
255 case Incompatible:
Steve Naroff6f9f3072007-09-02 15:34:30 +0000256 // FIXME: tighten up this check which should allow:
257 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
258 if (rhsType == Context.getPointerType(Context.CharTy))
259 break;
Steve Narofff0090632007-09-02 02:04:30 +0000260 Diag(loc, diag::err_typecheck_assign_incompatible,
261 DeclType.getAsString(), rhsType.getAsString(),
262 Init->getSourceRange());
263 return true;
264 case PointerFromInt:
265 // check for null pointer constant (C99 6.3.2.3p3)
266 if (!Init->isNullPointerConstant(Context)) {
267 Diag(loc, diag::ext_typecheck_assign_pointer_int,
268 DeclType.getAsString(), rhsType.getAsString(),
269 Init->getSourceRange());
270 return true;
271 }
272 break;
273 case IntFromPointer:
274 Diag(loc, diag::ext_typecheck_assign_pointer_int,
275 DeclType.getAsString(), rhsType.getAsString(),
276 Init->getSourceRange());
277 break;
278 case IncompatiblePointer:
279 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
280 DeclType.getAsString(), rhsType.getAsString(),
281 Init->getSourceRange());
282 break;
283 case CompatiblePointerDiscardsQualifiers:
284 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
285 DeclType.getAsString(), rhsType.getAsString(),
286 Init->getSourceRange());
287 break;
288 }
289 return false;
290}
291
Steve Naroff6f9f3072007-09-02 15:34:30 +0000292bool Sema::RequireConstantExprs(InitListExpr *IList) {
293 bool hadError = false;
294 for (unsigned i = 0; i < IList->getNumInits(); i++) {
295 Expr *expr = IList->getInit(i);
296
297 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr))
298 RequireConstantExprs(InitList);
299 else {
300 SourceLocation loc;
301 // FIXME: should be isConstantExpr()...
302 if (!expr->isIntegerConstantExpr(Context, &loc)) {
303 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
304 hadError = true;
305 }
306 }
307 }
308 return hadError;
309}
310
311QualType Sema::CheckInitializer(Expr *Init, QualType DeclType, bool isStatic) {
Steve Narofff0090632007-09-02 02:04:30 +0000312 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
313 if (!InitList) {
314 return CheckSingleInitializer(Init, DeclType) ? QualType() : DeclType;
315 }
316 // We have an InitListExpr, make sure we set the type.
317 Init->setType(DeclType);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000318
319 if (isStatic) // C99 6.7.8p4.
320 RequireConstantExprs(InitList);
321
Steve Narofff0090632007-09-02 02:04:30 +0000322 // FIXME: Lot of checking still to do...
323 return DeclType;
324}
325
Reid Spencer5f016e22007-07-11 17:01:13 +0000326Sema::DeclTy *
Chris Lattner24c39902007-07-12 00:36:32 +0000327Sema::ParseDeclarator(Scope *S, Declarator &D, ExprTy *init,
Reid Spencer5f016e22007-07-11 17:01:13 +0000328 DeclTy *lastDeclarator) {
329 Decl *LastDeclarator = (Decl*)lastDeclarator;
Chris Lattner24c39902007-07-12 00:36:32 +0000330 Expr *Init = static_cast<Expr*>(init);
Reid Spencer5f016e22007-07-11 17:01:13 +0000331 IdentifierInfo *II = D.getIdentifier();
332
Chris Lattnere80a59c2007-07-25 00:24:17 +0000333 // All of these full declarators require an identifier. If it doesn't have
334 // one, the ParsedFreeStandingDeclSpec action should be used.
335 if (II == 0) {
Chris Lattner98e08632007-08-28 06:17:15 +0000336 Diag(D.getDeclSpec().getSourceRange().Begin(),
337 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000338 D.getDeclSpec().getSourceRange(), D.getSourceRange());
339 return 0;
340 }
341
Chris Lattner31e05722007-08-26 06:24:45 +0000342 // The scope passed in may not be a decl scope. Zip up the scope tree until
343 // we find one that is.
344 while ((S->getFlags() & Scope::DeclScope) == 0)
345 S = S->getParent();
346
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 // See if this is a redefinition of a variable in the same scope.
348 Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
349 D.getIdentifierLoc(), S);
350 if (PrevDecl && !S->isDeclScope(PrevDecl))
351 PrevDecl = 0; // If in outer scope, it isn't the same thing.
352
353 Decl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000354 bool InvalidDecl = false;
355
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner24c39902007-07-12 00:36:32 +0000357 assert(Init == 0 && "Can't have initializer for a typedef!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
359 if (!NewTD) return 0;
360
361 // Handle attributes prior to checking for duplicates in MergeVarDecl
362 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
363 D.getAttributes());
364 // Merge the decl with the existing one if appropriate.
365 if (PrevDecl) {
366 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
367 if (NewTD == 0) return 0;
368 }
369 New = NewTD;
370 if (S->getParent() == 0) {
371 // C99 6.7.7p2: If a typedef name specifies a variably modified type
372 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000373 if (const VariableArrayType *VAT =
374 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
375 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
376 VAT->getSizeExpr()->getSourceRange());
377 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 }
379 }
380 } else if (D.isFunctionDeclarator()) {
Chris Lattner24c39902007-07-12 00:36:32 +0000381 assert(Init == 0 && "Can't have an initializer for a functiondecl!");
Steve Naroff5912a352007-08-28 20:14:24 +0000382
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000384 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000385
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 FunctionDecl::StorageClass SC;
387 switch (D.getDeclSpec().getStorageClassSpec()) {
388 default: assert(0 && "Unknown storage class!");
389 case DeclSpec::SCS_auto:
390 case DeclSpec::SCS_register:
391 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
392 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000393 InvalidDecl = true;
394 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
396 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
397 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
398 }
399
400 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000401 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 LastDeclarator);
403
404 // Merge the decl with the existing one if appropriate.
405 if (PrevDecl) {
406 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
407 if (NewFD == 0) return 0;
408 }
409 New = NewFD;
410 } else {
411 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff53a32342007-08-28 18:45:29 +0000412 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000413
414 VarDecl *NewVD;
415 VarDecl::StorageClass SC;
416 switch (D.getDeclSpec().getStorageClassSpec()) {
417 default: assert(0 && "Unknown storage class!");
418 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
419 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
420 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
421 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
422 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
423 }
424 if (S->getParent() == 0) {
Steve Naroff6f9f3072007-09-02 15:34:30 +0000425 if (Init) {
426 if (SC == VarDecl::Extern)
427 Diag(D.getIdentifierLoc(), diag::warn_extern_init);
428 CheckInitializer(Init, R, true);
429 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000430 // File scope. C99 6.9.2p2: A declaration of an identifier for and
431 // object that has file scope without an initializer, and without a
432 // storage-class specifier or with the storage-class specifier "static",
433 // constitutes a tentative definition. Note: A tentative definition with
434 // external linkage is valid (C99 6.2.2p5).
435 if (!Init && SC == VarDecl::Static) {
436 // C99 6.9.2p3: If the declaration of an identifier for an object is
437 // a tentative definition and has internal linkage (C99 6.2.2p3), the
438 // declared type shall not be an incomplete type.
439 if (R->isIncompleteType()) {
440 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
441 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000442 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000443 }
444 }
445 // C99 6.9p2: The storage-class specifiers auto and register shall not
446 // appear in the declaration specifiers in an external declaration.
447 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
448 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
449 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000450 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 }
Steve Naroffd7444aa2007-08-31 17:20:07 +0000452 if (SC == VarDecl::Static) {
453 // C99 6.7.5.2p2: If an identifier is declared to be an object with
454 // static storage duration, it shall not have a variable length array.
455 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
456 Expr *Size = VLA->getSizeExpr();
457 if (Size || (!Size && !Init)) {
458 // FIXME: Since we don't support initializers yet, we only emit this
459 // error when we don't have an initializer. Once initializers are
460 // implemented, the VLA will change to a CLA.
461 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
462 InvalidDecl = true;
463 }
464 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000465 }
466 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000467 } else {
468 if (Init) {
Steve Naroff6f9f3072007-09-02 15:34:30 +0000469 if (SC == VarDecl::Extern) { // C99 6.7.8p5
470 Diag(D.getIdentifierLoc(), diag::err_block_extern_cant_init);
471 InvalidDecl = true;
472 } else {
473 CheckInitializer(Init, R, SC == VarDecl::Static);
474 }
Steve Narofff0090632007-09-02 02:04:30 +0000475 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000476 // Block scope. C99 6.7p7: If an identifier for an object is declared with
477 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
478 if (SC != VarDecl::Extern) {
479 if (R->isIncompleteType()) {
480 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
481 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000482 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000483 }
484 }
485 if (SC == VarDecl::Static) {
486 // C99 6.7.5.2p2: If an identifier is declared to be an object with
487 // static storage duration, it shall not have a variable length array.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000488 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
489 Expr *Size = VLA->getSizeExpr();
490 if (Size || (!Size && !Init)) {
491 // FIXME: Since we don't support initializers yet, we only emit this
492 // error when we don't have an initializer. Once initializers are
493 // implemented, the VLA will change to a CLA.
494 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff53a32342007-08-28 18:45:29 +0000495 InvalidDecl = true;
Steve Naroffd7444aa2007-08-31 17:20:07 +0000496 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000497 }
498 }
499 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000500 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 // Handle attributes prior to checking for duplicates in MergeVarDecl
502 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
503 D.getAttributes());
504
505 // Merge the decl with the existing one if appropriate.
506 if (PrevDecl) {
507 NewVD = MergeVarDecl(NewVD, PrevDecl);
508 if (NewVD == 0) return 0;
509 }
Steve Narofff0090632007-09-02 02:04:30 +0000510 if (Init) { // FIXME: This will likely move up above...for now, it stays.
Steve Narofff1120de2007-08-24 22:33:52 +0000511 NewVD->setInit(Init);
512 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000513 New = NewVD;
514 }
515
516 // If this has an identifier, add it to the scope stack.
517 if (II) {
518 New->setNext(II->getFETokenInfo<Decl>());
519 II->setFETokenInfo(New);
520 S->AddDecl(New);
521 }
522
523 if (S->getParent() == 0)
524 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +0000525
526 // If any semantic error occurred, mark the decl as invalid.
527 if (D.getInvalidType() || InvalidDecl)
528 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000529
530 return New;
531}
532
533/// The declarators are chained together backwards, reverse the list.
534Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
535 // Often we have single declarators, handle them quickly.
536 Decl *Group = static_cast<Decl*>(group);
537 if (Group == 0 || Group->getNextDeclarator() == 0) return Group;
538
539 Decl *NewGroup = 0;
540 while (Group) {
541 Decl *Next = Group->getNextDeclarator();
542 Group->setNextDeclarator(NewGroup);
543 NewGroup = Group;
544 Group = Next;
545 }
546 return NewGroup;
547}
Steve Naroffe1223f72007-08-28 03:03:08 +0000548
549// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000550ParmVarDecl *
551Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
552 Scope *FnScope) {
553 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
554
555 IdentifierInfo *II = PI.Ident;
556 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
557 // Can this happen for params? We already checked that they don't conflict
558 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000559 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000560 PI.IdentLoc, FnScope)) {
561
562 }
563
564 // FIXME: Handle storage class (auto, register). No declarator?
565 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000566
567 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
568 // Doing the promotion here has a win and a loss. The win is the type for
569 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
570 // code generator). The loss is the orginal type isn't preserved. For example:
571 //
572 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
573 // int blockvardecl[5];
574 // sizeof(parmvardecl); // size == 4
575 // sizeof(blockvardecl); // size == 20
576 // }
577 //
578 // For expressions, all implicit conversions are captured using the
579 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
580 //
581 // FIXME: If a source translation tool needs to see the original type, then
582 // we need to consider storing both types (in ParmVarDecl)...
583 //
584 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
585 if (const ArrayType *AT = parmDeclType->getAsArrayType())
586 parmDeclType = Context.getPointerType(AT->getElementType());
587 else if (parmDeclType->isFunctionType())
588 parmDeclType = Context.getPointerType(parmDeclType);
589
590 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff53a32342007-08-28 18:45:29 +0000591 VarDecl::None, 0);
592 if (PI.InvalidType)
593 New->setInvalidDecl();
594
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 // If this has an identifier, add it to the scope stack.
596 if (II) {
597 New->setNext(II->getFETokenInfo<Decl>());
598 II->setFETokenInfo(New);
599 FnScope->AddDecl(New);
600 }
601
602 return New;
603}
604
605
606Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
607 assert(CurFunctionDecl == 0 && "Function parsing confused");
608 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
609 "Not a function declarator!");
610 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
611
612 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
613 // for a K&R function.
614 if (!FTI.hasPrototype) {
615 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
616 if (FTI.ArgInfo[i].TypeInfo == 0) {
617 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
618 FTI.ArgInfo[i].Ident->getName());
619 // Implicitly declare the argument as type 'int' for lack of a better
620 // type.
621 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
622 }
623 }
624
625 // Since this is a function definition, act as though we have information
626 // about the arguments.
627 FTI.hasPrototype = true;
628 } else {
629 // FIXME: Diagnose arguments without names in C.
630
631 }
632
633 Scope *GlobalScope = FnBodyScope->getParent();
634
635 FunctionDecl *FD =
636 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0, 0));
637 CurFunctionDecl = FD;
638
639 // Create Decl objects for each parameter, adding them to the FunctionDecl.
640 llvm::SmallVector<ParmVarDecl*, 16> Params;
641
642 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
643 // no arguments, not a function that takes a single void argument.
644 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
645 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
646 // empty arg list, don't push any params.
647 } else {
648 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
649 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
650 }
651
652 FD->setParams(&Params[0], Params.size());
653
654 return FD;
655}
656
657Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
658 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
659 FD->setBody((Stmt*)Body);
660
661 assert(FD == CurFunctionDecl && "Function parsing confused");
662 CurFunctionDecl = 0;
663
664 // Verify and clean out per-function state.
665
666 // Check goto/label use.
667 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
668 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
669 // Verify that we have no forward references left. If so, there was a goto
670 // or address of a label taken, but no definition of it. Label fwd
671 // definitions are indicated with a null substmt.
672 if (I->second->getSubStmt() == 0) {
673 LabelStmt *L = I->second;
674 // Emit error.
675 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
676
677 // At this point, we have gotos that use the bogus label. Stitch it into
678 // the function body so that they aren't leaked and that the AST is well
679 // formed.
680 L->setSubStmt(new NullStmt(L->getIdentLoc()));
681 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
682 }
683 }
684 LabelMap.clear();
685
686 return FD;
687}
688
689
690/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
691/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
692Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
693 Scope *S) {
694 if (getLangOptions().C99) // Extension in C99.
695 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
696 else // Legal in C90, but warn about it.
697 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
698
699 // FIXME: handle stuff like:
700 // void foo() { extern float X(); }
701 // void bar() { X(); } <-- implicit decl for X in another scope.
702
703 // Set a Declarator for the implicit definition: int foo();
704 const char *Dummy;
705 DeclSpec DS;
706 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
707 Error = Error; // Silence warning.
708 assert(!Error && "Error setting up implicit decl!");
709 Declarator D(DS, Declarator::BlockContext);
710 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
711 D.SetIdentifier(&II, Loc);
712
713 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000714 if (Scope *FnS = S->getFnParent())
715 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000716 while (S->getParent())
717 S = S->getParent();
718
719 return static_cast<Decl*>(ParseDeclarator(S, D, 0, 0));
720}
721
722
723TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
724 Decl *LastDeclarator) {
725 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
726
727 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000728 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000729
730 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +0000731 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
732 T, LastDeclarator);
733 if (D.getInvalidType())
734 NewTD->setInvalidDecl();
735 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000736}
737
738
739/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
740/// former case, Name will be non-null. In the later case, Name will be null.
741/// TagType indicates what kind of tag this is. TK indicates whether this is a
742/// reference/declaration/definition of a tag.
743Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
744 SourceLocation KWLoc, IdentifierInfo *Name,
745 SourceLocation NameLoc, AttributeList *Attr) {
746 // If this is a use of an existing tag, it must have a name.
747 assert((Name != 0 || TK == TK_Definition) &&
748 "Nameless record must be a definition!");
749
750 Decl::Kind Kind;
751 switch (TagType) {
752 default: assert(0 && "Unknown tag type!");
753 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
754 case DeclSpec::TST_union: Kind = Decl::Union; break;
755//case DeclSpec::TST_class: Kind = Decl::Class; break;
756 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
757 }
758
759 // If this is a named struct, check to see if there was a previous forward
760 // declaration or definition.
761 if (TagDecl *PrevDecl =
762 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
763 NameLoc, S))) {
764
765 // If this is a use of a previous tag, or if the tag is already declared in
766 // the same scope (so that the definition/declaration completes or
767 // rementions the tag), reuse the decl.
768 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
769 // Make sure that this wasn't declared as an enum and now used as a struct
770 // or something similar.
771 if (PrevDecl->getKind() != Kind) {
772 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
773 Diag(PrevDecl->getLocation(), diag::err_previous_use);
774 }
775
776 // If this is a use or a forward declaration, we're good.
777 if (TK != TK_Definition)
778 return PrevDecl;
779
780 // Diagnose attempts to redefine a tag.
781 if (PrevDecl->isDefinition()) {
782 Diag(NameLoc, diag::err_redefinition, Name->getName());
783 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
784 // If this is a redefinition, recover by making this struct be
785 // anonymous, which will make any later references get the previous
786 // definition.
787 Name = 0;
788 } else {
789 // Okay, this is definition of a previously declared or referenced tag.
790 // Move the location of the decl to be the definition site.
791 PrevDecl->setLocation(NameLoc);
792 return PrevDecl;
793 }
794 }
795 // If we get here, this is a definition of a new struct type in a nested
796 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
797 // type.
798 }
799
800 // If there is an identifier, use the location of the identifier as the
801 // location of the decl, otherwise use the location of the struct/union
802 // keyword.
803 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
804
805 // Otherwise, if this is the first time we've seen this tag, create the decl.
806 TagDecl *New;
807 switch (Kind) {
808 default: assert(0 && "Unknown tag kind!");
809 case Decl::Enum:
810 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
811 // enum X { A, B, C } D; D should chain to X.
812 New = new EnumDecl(Loc, Name, 0);
813 // If this is an undefined enum, warn.
814 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
815 break;
816 case Decl::Union:
817 case Decl::Struct:
818 case Decl::Class:
819 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
820 // struct X { int A; } D; D should chain to X.
821 New = new RecordDecl(Kind, Loc, Name, 0);
822 break;
823 }
824
825 // If this has an identifier, add it to the scope stack.
826 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +0000827 // The scope passed in may not be a decl scope. Zip up the scope tree until
828 // we find one that is.
829 while ((S->getFlags() & Scope::DeclScope) == 0)
830 S = S->getParent();
831
832 // Add it to the decl chain.
Reid Spencer5f016e22007-07-11 17:01:13 +0000833 New->setNext(Name->getFETokenInfo<Decl>());
834 Name->setFETokenInfo(New);
835 S->AddDecl(New);
836 }
837
838 return New;
839}
840
841/// ParseField - Each field of a struct/union/class is passed into this in order
842/// to create a FieldDecl object for it.
843Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
844 SourceLocation DeclStart,
845 Declarator &D, ExprTy *BitfieldWidth) {
846 IdentifierInfo *II = D.getIdentifier();
847 Expr *BitWidth = (Expr*)BitfieldWidth;
848
849 SourceLocation Loc = DeclStart;
850 if (II) Loc = D.getIdentifierLoc();
851
852 // FIXME: Unnamed fields can be handled in various different ways, for
853 // example, unnamed unions inject all members into the struct namespace!
854
855
856 if (BitWidth) {
857 // TODO: Validate.
858 //printf("WARNING: BITFIELDS IGNORED!\n");
859
860 // 6.7.2.1p3
861 // 6.7.2.1p4
862
863 } else {
864 // Not a bitfield.
865
866 // validate II.
867
868 }
869
870 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000871 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
872 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +0000873
Reid Spencer5f016e22007-07-11 17:01:13 +0000874 // C99 6.7.2.1p8: A member of a structure or union may have any type other
875 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000876 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
877 Diag(Loc, diag::err_typecheck_illegal_vla,
878 VAT->getSizeExpr()->getSourceRange());
879 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000880 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000881 // FIXME: Chain fielddecls together.
Steve Naroff5912a352007-08-28 20:14:24 +0000882 FieldDecl *NewFD = new FieldDecl(Loc, II, T, 0);
883 if (D.getInvalidType() || InvalidDecl)
884 NewFD->setInvalidDecl();
885 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000886}
887
888void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
889 DeclTy **Fields, unsigned NumFields) {
890 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
891 if (Record->isDefinition()) {
892 // Diagnose code like:
893 // struct S { struct S {} X; };
894 // We discover this when we complete the outer S. Reject and ignore the
895 // outer S.
896 Diag(Record->getLocation(), diag::err_nested_redefinition,
897 Record->getKindName());
898 Diag(RecLoc, diag::err_previous_definition);
899 return;
900 }
901
902 // Verify that all the fields are okay.
903 unsigned NumNamedMembers = 0;
904 llvm::SmallVector<FieldDecl*, 32> RecFields;
905 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
906
907 for (unsigned i = 0; i != NumFields; ++i) {
908 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
909 if (!FD) continue; // Already issued a diagnostic.
910
911 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +0000912 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +0000913
914 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +0000915 if (FDTy->isFunctionType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000916 Diag(FD->getLocation(), diag::err_field_declared_as_function,
917 FD->getName());
918 delete FD;
919 continue;
920 }
921
922 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
923 if (FDTy->isIncompleteType()) {
924 if (i != NumFields-1 || // ... that the last member ...
925 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +0000926 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000927 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
928 delete FD;
929 continue;
930 }
931 if (NumNamedMembers < 1) { //... must have more than named member ...
932 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
933 FD->getName());
934 delete FD;
935 continue;
936 }
937
938 // Okay, we have a legal flexible array member at the end of the struct.
939 Record->setHasFlexibleArrayMember(true);
940 }
941
942
943 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
944 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +0000945 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000946 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
947 // If this is a member of a union, then entire union becomes "flexible".
948 if (Record->getKind() == Decl::Union) {
949 Record->setHasFlexibleArrayMember(true);
950 } else {
951 // If this is a struct/class and this is not the last element, reject
952 // it. Note that GCC supports variable sized arrays in the middle of
953 // structures.
954 if (i != NumFields-1) {
955 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
956 FD->getName());
957 delete FD;
958 continue;
959 }
960
961 // We support flexible arrays at the end of structs in other structs
962 // as an extension.
963 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
964 FD->getName());
965 Record->setHasFlexibleArrayMember(true);
966 }
967 }
968 }
969
970 // Keep track of the number of named members.
971 if (IdentifierInfo *II = FD->getIdentifier()) {
972 // Detect duplicate member names.
973 if (!FieldIDs.insert(II)) {
974 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
975 // Find the previous decl.
976 SourceLocation PrevLoc;
977 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
978 assert(i != e && "Didn't find previous def!");
979 if (RecFields[i]->getIdentifier() == II) {
980 PrevLoc = RecFields[i]->getLocation();
981 break;
982 }
983 }
984 Diag(PrevLoc, diag::err_previous_definition);
985 delete FD;
986 continue;
987 }
988 ++NumNamedMembers;
989 }
990
991 // Remember good fields.
992 RecFields.push_back(FD);
993 }
994
995
996 // Okay, we successfully defined 'Record'.
997 Record->defineBody(&RecFields[0], RecFields.size());
998}
999
1000Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
1001 DeclTy *lastEnumConst,
1002 SourceLocation IdLoc, IdentifierInfo *Id,
1003 SourceLocation EqualLoc, ExprTy *val) {
1004 theEnumDecl = theEnumDecl; // silence unused warning.
1005 EnumConstantDecl *LastEnumConst =
1006 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1007 Expr *Val = static_cast<Expr*>(val);
1008
Chris Lattner31e05722007-08-26 06:24:45 +00001009 // The scope passed in may not be a decl scope. Zip up the scope tree until
1010 // we find one that is.
1011 while ((S->getFlags() & Scope::DeclScope) == 0)
1012 S = S->getParent();
1013
Reid Spencer5f016e22007-07-11 17:01:13 +00001014 // Verify that there isn't already something declared with this name in this
1015 // scope.
1016 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
1017 if (S->isDeclScope(PrevDecl)) {
1018 if (isa<EnumConstantDecl>(PrevDecl))
1019 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1020 else
1021 Diag(IdLoc, diag::err_redefinition, Id->getName());
1022 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1023 // FIXME: Don't leak memory: delete Val;
1024 return 0;
1025 }
1026 }
1027
1028 llvm::APSInt EnumVal(32);
1029 QualType EltTy;
1030 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001031 // Make sure to promote the operand type to int.
1032 UsualUnaryConversions(Val);
1033
Reid Spencer5f016e22007-07-11 17:01:13 +00001034 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1035 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001036 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001037 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1038 Id->getName());
1039 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001040 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001041 } else {
1042 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001043 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001044 }
1045
1046 if (!Val) {
1047 if (LastEnumConst) {
1048 // Assign the last value + 1.
1049 EnumVal = LastEnumConst->getInitVal();
1050 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001051
1052 // Check for overflow on increment.
1053 if (EnumVal < LastEnumConst->getInitVal())
1054 Diag(IdLoc, diag::warn_enum_value_overflow);
1055
Chris Lattnerb7416f92007-08-27 17:37:24 +00001056 EltTy = LastEnumConst->getType();
1057 } else {
1058 // First value, set to zero.
1059 EltTy = Context.IntTy;
Chris Lattner421a23d2007-08-27 21:16:18 +00001060 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy, IdLoc));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001061 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001062 }
1063
Reid Spencer5f016e22007-07-11 17:01:13 +00001064 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1065 LastEnumConst);
1066
1067 // Register this decl in the current scope stack.
1068 New->setNext(Id->getFETokenInfo<Decl>());
1069 Id->setFETokenInfo(New);
1070 S->AddDecl(New);
1071 return New;
1072}
1073
1074void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1075 DeclTy **Elements, unsigned NumElements) {
1076 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1077 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1078
Chris Lattnere37f0be2007-08-28 05:10:31 +00001079 // TODO: If the result value doesn't fit in an int, it must be a long or long
1080 // long value. ISO C does not support this, but GCC does as an extension,
1081 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001082 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001083
1084
Chris Lattnerac609682007-08-28 06:15:15 +00001085 // Verify that all the values are okay, compute the size of the values, and
1086 // reverse the list.
1087 unsigned NumNegativeBits = 0;
1088 unsigned NumPositiveBits = 0;
1089
1090 // Keep track of whether all elements have type int.
1091 bool AllElementsInt = true;
1092
Reid Spencer5f016e22007-07-11 17:01:13 +00001093 EnumConstantDecl *EltList = 0;
1094 for (unsigned i = 0; i != NumElements; ++i) {
1095 EnumConstantDecl *ECD =
1096 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1097 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001098
1099 // If the enum value doesn't fit in an int, emit an extension warning.
1100 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1101 "Should have promoted value to int");
1102 const llvm::APSInt &InitVal = ECD->getInitVal();
1103 if (InitVal.getBitWidth() > IntWidth) {
1104 llvm::APSInt V(InitVal);
1105 V.trunc(IntWidth);
1106 V.extend(InitVal.getBitWidth());
1107 if (V != InitVal)
1108 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1109 InitVal.toString());
1110 }
Chris Lattnerac609682007-08-28 06:15:15 +00001111
1112 // Keep track of the size of positive and negative values.
1113 if (InitVal.isUnsigned() || !InitVal.isNegative())
1114 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1115 else
1116 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001117
Chris Lattnerac609682007-08-28 06:15:15 +00001118 // Keep track of whether every enum element has type int (very commmon).
1119 if (AllElementsInt)
1120 AllElementsInt = ECD->getType() == Context.IntTy;
1121
Reid Spencer5f016e22007-07-11 17:01:13 +00001122 ECD->setNextDeclarator(EltList);
1123 EltList = ECD;
1124 }
1125
Chris Lattnerac609682007-08-28 06:15:15 +00001126 // Figure out the type that should be used for this enum.
1127 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1128 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001129 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001130
1131 if (NumNegativeBits) {
1132 // If there is a negative value, figure out the smallest integer type (of
1133 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001134 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001135 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001136 BestWidth = IntWidth;
1137 } else {
1138 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1139 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001140 BestType = Context.LongTy;
1141 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001142 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1143 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001144 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1145 BestType = Context.LongLongTy;
1146 }
1147 }
1148 } else {
1149 // If there is no negative value, figure out which of uint, ulong, ulonglong
1150 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001151 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001152 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001153 BestWidth = IntWidth;
1154 } else if (NumPositiveBits <=
1155 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001156 BestType = Context.UnsignedLongTy;
1157 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001158 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1159 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001160 "How could an initializer get larger than ULL?");
1161 BestType = Context.UnsignedLongLongTy;
1162 }
1163 }
1164
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001165 // Loop over all of the enumerator constants, changing their types to match
1166 // the type of the enum if needed.
1167 for (unsigned i = 0; i != NumElements; ++i) {
1168 EnumConstantDecl *ECD =
1169 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1170 if (!ECD) continue; // Already issued a diagnostic.
1171
1172 // Standard C says the enumerators have int type, but we allow, as an
1173 // extension, the enumerators to be larger than int size. If each
1174 // enumerator value fits in an int, type it as an int, otherwise type it the
1175 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1176 // that X has type 'int', not 'unsigned'.
1177 if (ECD->getType() == Context.IntTy)
1178 continue; // Already int type.
1179
1180 // Determine whether the value fits into an int.
1181 llvm::APSInt InitVal = ECD->getInitVal();
1182 bool FitsInInt;
1183 if (InitVal.isUnsigned() || !InitVal.isNegative())
1184 FitsInInt = InitVal.getActiveBits() < IntWidth;
1185 else
1186 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1187
1188 // If it fits into an integer type, force it. Otherwise force it to match
1189 // the enum decl type.
1190 QualType NewTy;
1191 unsigned NewWidth;
1192 bool NewSign;
1193 if (FitsInInt) {
1194 NewTy = Context.IntTy;
1195 NewWidth = IntWidth;
1196 NewSign = true;
1197 } else if (ECD->getType() == BestType) {
1198 // Already the right type!
1199 continue;
1200 } else {
1201 NewTy = BestType;
1202 NewWidth = BestWidth;
1203 NewSign = BestType->isSignedIntegerType();
1204 }
1205
1206 // Adjust the APSInt value.
1207 InitVal.extOrTrunc(NewWidth);
1208 InitVal.setIsSigned(NewSign);
1209 ECD->setInitVal(InitVal);
1210
1211 // Adjust the Expr initializer and type.
1212 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1213 ECD->setType(NewTy);
1214 }
Chris Lattnerac609682007-08-28 06:15:15 +00001215
Chris Lattnere00b18c2007-08-28 18:24:31 +00001216 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001217}
1218
1219void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1220 if (!current) return;
1221
1222 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1223 // remember this in the LastInGroupList list.
1224 if (last)
1225 LastInGroupList.push_back((Decl*)last);
1226}
1227
1228void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1229 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1230 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1231 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1232 if (!newType.isNull()) // install the new vector type into the decl
1233 vDecl->setType(newType);
1234 }
1235 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1236 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1237 rawAttr);
1238 if (!newType.isNull()) // install the new vector type into the decl
1239 tDecl->setUnderlyingType(newType);
1240 }
1241 }
Steve Naroff73322922007-07-18 18:00:27 +00001242 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001243 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1244 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1245 else
Steve Naroff73322922007-07-18 18:00:27 +00001246 Diag(rawAttr->getAttributeLoc(),
1247 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00001248 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 // FIXME: add other attributes...
1250}
1251
1252void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1253 AttributeList *declarator_postfix) {
1254 while (declspec_prefix) {
1255 HandleDeclAttribute(New, declspec_prefix);
1256 declspec_prefix = declspec_prefix->getNext();
1257 }
1258 while (declarator_postfix) {
1259 HandleDeclAttribute(New, declarator_postfix);
1260 declarator_postfix = declarator_postfix->getNext();
1261 }
1262}
1263
Steve Naroffbea0b342007-07-29 16:33:31 +00001264void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1265 AttributeList *rawAttr) {
1266 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00001267 // check the attribute arugments.
1268 if (rawAttr->getNumArgs() != 1) {
1269 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1270 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001271 return;
Steve Naroff73322922007-07-18 18:00:27 +00001272 }
1273 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1274 llvm::APSInt vecSize(32);
1275 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1276 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1277 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001278 return;
Steve Naroff73322922007-07-18 18:00:27 +00001279 }
1280 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1281 // in conjunction with complex types (pointers, arrays, functions, etc.).
1282 Type *canonType = curType.getCanonicalType().getTypePtr();
1283 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1284 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1285 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001286 return;
Steve Naroff73322922007-07-18 18:00:27 +00001287 }
1288 // unlike gcc's vector_size attribute, the size is specified as the
1289 // number of elements, not the number of bytes.
1290 unsigned vectorSize = vecSize.getZExtValue();
1291
1292 if (vectorSize == 0) {
1293 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1294 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001295 return;
Steve Naroff73322922007-07-18 18:00:27 +00001296 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001297 // Instantiate/Install the vector type, the number of elements is > 0.
1298 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1299 // Remember this typedef decl, we will need it later for diagnostics.
1300 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001301}
1302
Reid Spencer5f016e22007-07-11 17:01:13 +00001303QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001304 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001305 // check the attribute arugments.
1306 if (rawAttr->getNumArgs() != 1) {
1307 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1308 std::string("1"));
1309 return QualType();
1310 }
1311 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1312 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001313 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1315 sizeExpr->getSourceRange());
1316 return QualType();
1317 }
1318 // navigate to the base type - we need to provide for vector pointers,
1319 // vector arrays, and functions returning vectors.
1320 Type *canonType = curType.getCanonicalType().getTypePtr();
1321
Steve Naroff73322922007-07-18 18:00:27 +00001322 if (canonType->isPointerType() || canonType->isArrayType() ||
1323 canonType->isFunctionType()) {
1324 assert(1 && "HandleVector(): Complex type construction unimplemented");
1325 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1326 do {
1327 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1328 canonType = PT->getPointeeType().getTypePtr();
1329 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1330 canonType = AT->getElementType().getTypePtr();
1331 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1332 canonType = FT->getResultType().getTypePtr();
1333 } while (canonType->isPointerType() || canonType->isArrayType() ||
1334 canonType->isFunctionType());
1335 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001336 }
1337 // the base type must be integer or float.
1338 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1339 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1340 curType.getCanonicalType().getAsString());
1341 return QualType();
1342 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001343 unsigned typeSize = Context.getTypeSize(curType, rawAttr->getAttributeLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 // vecSize is specified in bytes - convert to bits.
1345 unsigned vectorSize = vecSize.getZExtValue() * 8;
1346
1347 // the vector size needs to be an integral multiple of the type size.
1348 if (vectorSize % typeSize) {
1349 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1350 sizeExpr->getSourceRange());
1351 return QualType();
1352 }
1353 if (vectorSize == 0) {
1354 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1355 sizeExpr->getSourceRange());
1356 return QualType();
1357 }
1358 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1359 // the number of elements to be a power of two (unlike GCC).
1360 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00001361 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001362}
1363