blob: 15fe7c1033e424f5027c00b4b7133f265d95008d [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Builtins.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/Type.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Parse/Scope.h"
22#include "clang/Lex/IdentifierTable.h"
23#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
25#include "llvm/ADT/SmallSet.h"
26using namespace clang;
27
Chris Lattner4b009652007-07-25 00:24:17 +000028Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
29 return dyn_cast_or_null<TypedefDecl>(II.getFETokenInfo<Decl>());
30}
31
32void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000033 if (S->decl_empty()) return;
34 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
35
Chris Lattner4b009652007-07-25 00:24:17 +000036 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
37 I != E; ++I) {
38 Decl *D = static_cast<Decl*>(*I);
39 assert(D && "This decl didn't get pushed??");
40 IdentifierInfo *II = D->getIdentifier();
41 if (!II) continue;
42
43 // Unlink this decl from the identifier. Because the scope contains decls
44 // in an unordered collection, and because we have multiple identifier
45 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
46 if (II->getFETokenInfo<Decl>() == D) {
47 // Normal case, no multiple decls in different namespaces.
48 II->setFETokenInfo(D->getNext());
49 } else {
50 // Scan ahead. There are only three namespaces in C, so this loop can
51 // never execute more than 3 times.
52 Decl *SomeDecl = II->getFETokenInfo<Decl>();
53 while (SomeDecl->getNext() != D) {
54 SomeDecl = SomeDecl->getNext();
55 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
56 }
57 SomeDecl->setNext(D->getNext());
58 }
59
60 // This will have to be revisited for C++: there we want to nest stuff in
61 // namespace decls etc. Even for C, we might want a top-level translation
62 // unit decl or something.
63 if (!CurFunctionDecl)
64 continue;
65
66 // Chain this decl to the containing function, it now owns the memory for
67 // the decl.
68 D->setNext(CurFunctionDecl->getDeclChain());
69 CurFunctionDecl->setDeclChain(D);
70 }
71}
72
73/// LookupScopedDecl - Look up the inner-most declaration in the specified
74/// namespace.
75Decl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
76 SourceLocation IdLoc, Scope *S) {
77 if (II == 0) return 0;
78 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
79
80 // Scan up the scope chain looking for a decl that matches this identifier
81 // that is in the appropriate namespace. This search should not take long, as
82 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
83 for (Decl *D = II->getFETokenInfo<Decl>(); D; D = D->getNext())
84 if (D->getIdentifierNamespace() == NS)
85 return D;
86
87 // If we didn't find a use of this identifier, and if the identifier
88 // corresponds to a compiler builtin, create the decl object for the builtin
89 // now, injecting it into translation unit scope, and return it.
90 if (NS == Decl::IDNS_Ordinary) {
91 // If this is a builtin on some other target, or if this builtin varies
92 // across targets (e.g. in type), emit a diagnostic and mark the translation
93 // unit non-portable for using it.
94 if (II->isNonPortableBuiltin()) {
95 // Only emit this diagnostic once for this builtin.
96 II->setNonPortableBuiltin(false);
97 Context.Target.DiagnoseNonPortability(IdLoc,
98 diag::port_target_builtin_use);
99 }
100 // If this is a builtin on this (or all) targets, create the decl.
101 if (unsigned BuiltinID = II->getBuiltinID())
102 return LazilyCreateBuiltin(II, BuiltinID, S);
103 }
104 return 0;
105}
106
107/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
108/// lazily create a decl for it.
109Decl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
110 Builtin::ID BID = (Builtin::ID)bid;
111
112 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
113 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner987058a2007-08-26 04:02:13 +0000114 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000115
116 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000117 if (Scope *FnS = S->getFnParent())
118 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000119 while (S->getParent())
120 S = S->getParent();
121 S->AddDecl(New);
122
123 // Add this decl to the end of the identifier info.
124 if (Decl *LastDecl = II->getFETokenInfo<Decl>()) {
125 // Scan until we find the last (outermost) decl in the id chain.
126 while (LastDecl->getNext())
127 LastDecl = LastDecl->getNext();
128 // Insert before (outside) it.
129 LastDecl->setNext(New);
130 } else {
131 II->setFETokenInfo(New);
132 }
133 // Make sure clients iterating over decls see this.
134 LastInGroupList.push_back(New);
135
136 return New;
137}
138
139/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
140/// and scope as a previous declaration 'Old'. Figure out how to resolve this
141/// situation, merging decls or emitting diagnostics as appropriate.
142///
143TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
144 // Verify the old decl was also a typedef.
145 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
146 if (!Old) {
147 Diag(New->getLocation(), diag::err_redefinition_different_kind,
148 New->getName());
149 Diag(OldD->getLocation(), diag::err_previous_definition);
150 return New;
151 }
152
153 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
154 // TODO: This is totally simplistic. It should handle merging functions
155 // together etc, merging extern int X; int X; ...
156 Diag(New->getLocation(), diag::err_redefinition, New->getName());
157 Diag(Old->getLocation(), diag::err_previous_definition);
158 return New;
159}
160
161/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
162/// and scope as a previous declaration 'Old'. Figure out how to resolve this
163/// situation, merging decls or emitting diagnostics as appropriate.
164///
165FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
166 // Verify the old decl was also a function.
167 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
168 if (!Old) {
169 Diag(New->getLocation(), diag::err_redefinition_different_kind,
170 New->getName());
171 Diag(OldD->getLocation(), diag::err_previous_definition);
172 return New;
173 }
174
175 // This is not right, but it's a start. If 'Old' is a function prototype with
176 // the same type as 'New', silently allow this. FIXME: We should link up decl
177 // objects here.
178 if (Old->getBody() == 0 &&
179 Old->getCanonicalType() == New->getCanonicalType()) {
180 return New;
181 }
182
183 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
184 // TODO: This is totally simplistic. It should handle merging functions
185 // together etc, merging extern int X; int X; ...
186 Diag(New->getLocation(), diag::err_redefinition, New->getName());
187 Diag(Old->getLocation(), diag::err_previous_definition);
188 return New;
189}
190
191/// MergeVarDecl - We just parsed a variable 'New' which has the same name
192/// and scope as a previous declaration 'Old'. Figure out how to resolve this
193/// situation, merging decls or emitting diagnostics as appropriate.
194///
195/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
196/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
197///
198VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
199 // Verify the old decl was also a variable.
200 VarDecl *Old = dyn_cast<VarDecl>(OldD);
201 if (!Old) {
202 Diag(New->getLocation(), diag::err_redefinition_different_kind,
203 New->getName());
204 Diag(OldD->getLocation(), diag::err_previous_definition);
205 return New;
206 }
Steve Naroff83c13012007-08-30 01:06:46 +0000207 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
208 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
209 bool OldIsTentative = false;
210
211 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
212 // Handle C "tentative" external object definitions. FIXME: finish!
213 if (!OldFSDecl->getInit() &&
214 (OldFSDecl->getStorageClass() == VarDecl::None ||
215 OldFSDecl->getStorageClass() == VarDecl::Static))
216 OldIsTentative = true;
217 }
Chris Lattner4b009652007-07-25 00:24:17 +0000218 // Verify the types match.
219 if (Old->getCanonicalType() != New->getCanonicalType()) {
220 Diag(New->getLocation(), diag::err_redefinition, New->getName());
221 Diag(Old->getLocation(), diag::err_previous_definition);
222 return New;
223 }
224 // We've verified the types match, now check if Old is "extern".
225 if (Old->getStorageClass() != VarDecl::Extern) {
226 Diag(New->getLocation(), diag::err_redefinition, New->getName());
227 Diag(Old->getLocation(), diag::err_previous_definition);
228 }
229 return New;
230}
231
232/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
233/// no declarator (e.g. "struct foo;") is parsed.
234Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
235 // TODO: emit error on 'int;' or 'const enum foo;'.
236 // TODO: emit error on 'typedef int;'
237 // if (!DS.isMissingDeclaratorOk()) Diag(...);
238
239 return 0;
240}
241
Steve Naroffe14e5542007-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 Naroff9091f3f2007-09-02 15:34:30 +0000256 // FIXME: tighten up this check which should allow:
257 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
258 if (rhsType == Context.getPointerType(Context.CharTy))
259 break;
Steve Naroffe14e5542007-09-02 02:04:30 +0000260 Diag(loc, diag::err_typecheck_assign_incompatible,
261 DeclType.getAsString(), rhsType.getAsString(),
262 Init->getSourceRange());
263 return true;
264 case PointerFromInt:
265 // check for null pointer constant (C99 6.3.2.3p3)
266 if (!Init->isNullPointerConstant(Context)) {
267 Diag(loc, diag::ext_typecheck_assign_pointer_int,
268 DeclType.getAsString(), rhsType.getAsString(),
269 Init->getSourceRange());
270 return true;
271 }
272 break;
273 case IntFromPointer:
274 Diag(loc, diag::ext_typecheck_assign_pointer_int,
275 DeclType.getAsString(), rhsType.getAsString(),
276 Init->getSourceRange());
277 break;
278 case IncompatiblePointer:
279 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
280 DeclType.getAsString(), rhsType.getAsString(),
281 Init->getSourceRange());
282 break;
283 case CompatiblePointerDiscardsQualifiers:
284 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
285 DeclType.getAsString(), rhsType.getAsString(),
286 Init->getSourceRange());
287 break;
288 }
289 return false;
290}
291
Steve Naroff1c9de712007-09-03 01:24:23 +0000292void Sema::CheckInitList(InitListExpr *IList, QualType DType,
293 bool isStatic, int &nInitializers, int maxElements,
294 bool &hadError) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000295 for (unsigned i = 0; i < IList->getNumInits(); i++) {
296 Expr *expr = IList->getInit(i);
297
298 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr))
Steve Naroff1c9de712007-09-03 01:24:23 +0000299 CheckInitList(InitList, DType, isStatic, nInitializers, maxElements,
300 hadError);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000301 else {
Steve Naroff1c9de712007-09-03 01:24:23 +0000302 SourceLocation loc = expr->getLocStart();
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000303
304 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
Steve Naroff9091f3f2007-09-02 15:34:30 +0000305 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
306 hadError = true;
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000307 } else if (CheckSingleInitializer(expr, DType)) {
308 hadError = true; // types didn't match.
Steve Naroff9091f3f2007-09-02 15:34:30 +0000309 }
Steve Naroff1c9de712007-09-03 01:24:23 +0000310 // Does the element fit?
311 nInitializers++;
312 if ((maxElements >= 0) && (nInitializers > maxElements))
313 Diag(loc, diag::warn_excess_initializers, expr->getSourceRange());
Steve Naroff9091f3f2007-09-02 15:34:30 +0000314 }
315 }
Steve Naroff1c9de712007-09-03 01:24:23 +0000316 return;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000317}
318
Steve Naroff1c9de712007-09-03 01:24:23 +0000319bool Sema::CheckInitializer(Expr *Init, QualType &DeclType, bool isStatic) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000320 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroff1c9de712007-09-03 01:24:23 +0000321 if (!InitList)
322 return CheckSingleInitializer(Init, DeclType);
323
Steve Naroffe14e5542007-09-02 02:04:30 +0000324 // We have an InitListExpr, make sure we set the type.
325 Init->setType(DeclType);
Steve Naroff1c9de712007-09-03 01:24:23 +0000326
327 bool hadError = false;
328 int nInits = 0;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000329
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000330 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
331 // of unknown size ("[]") or an object type that is not a variable array type.
332 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
333 Expr *expr = VAT->getSizeExpr();
Steve Naroff1c9de712007-09-03 01:24:23 +0000334 if (expr)
335 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
336 expr->getSourceRange());
337
338 // We have a VariableArrayType with unknown size.
339 QualType ElmtType = VAT->getElementType();
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000340
341 // If we have a multi-dimensional array, navigate to the base type.
Steve Naroff1c9de712007-09-03 01:24:23 +0000342 while ((VAT = ElmtType->getAsVariableArrayType())) {
343 ElmtType = VAT->getElementType();
344 }
345 CheckInitList(InitList, ElmtType, isStatic, nInits, -1, hadError);
346
347 if (!hadError) {
348 // Return a new array type from the number of initializers (C99 6.7.8p22).
349 llvm::APSInt ConstVal(32);
350 ConstVal = nInits;
351 DeclType = Context.getConstantArrayType(ElmtType, ConstVal,
352 ArrayType::Normal, 0);
353 }
354 return hadError;
355 }
356 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
357 QualType ElmtType = CAT->getElementType();
358 unsigned numElements = CAT->getSize().getZExtValue();
359
360 // If we have a multi-dimensional array, navigate to the base type. Also
361 // compute the absolute size of the array, so we can detect excess elements.
362 while ((CAT = ElmtType->getAsConstantArrayType())) {
363 ElmtType = CAT->getElementType();
364 numElements *= CAT->getSize().getZExtValue();
365 }
366 CheckInitList(InitList, ElmtType, isStatic, nInits, numElements, hadError);
367 return hadError;
368 }
369 if (DeclType->isScalarType()) { // C99 6.7.8p11
370 CheckInitList(InitList, DeclType, isStatic, nInits, 1, hadError);
371 return hadError;
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000372 }
373 // FIXME: Handle struct/union types.
Steve Naroff1c9de712007-09-03 01:24:23 +0000374 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +0000375}
376
Chris Lattner4b009652007-07-25 00:24:17 +0000377Sema::DeclTy *
378Sema::ParseDeclarator(Scope *S, Declarator &D, ExprTy *init,
379 DeclTy *lastDeclarator) {
380 Decl *LastDeclarator = (Decl*)lastDeclarator;
381 Expr *Init = static_cast<Expr*>(init);
382 IdentifierInfo *II = D.getIdentifier();
383
384 // All of these full declarators require an identifier. If it doesn't have
385 // one, the ParsedFreeStandingDeclSpec action should be used.
386 if (II == 0) {
Chris Lattner87492f42007-08-28 06:17:15 +0000387 Diag(D.getDeclSpec().getSourceRange().Begin(),
388 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000389 D.getDeclSpec().getSourceRange(), D.getSourceRange());
390 return 0;
391 }
392
Chris Lattnera7549902007-08-26 06:24:45 +0000393 // The scope passed in may not be a decl scope. Zip up the scope tree until
394 // we find one that is.
395 while ((S->getFlags() & Scope::DeclScope) == 0)
396 S = S->getParent();
397
Chris Lattner4b009652007-07-25 00:24:17 +0000398 // See if this is a redefinition of a variable in the same scope.
399 Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
400 D.getIdentifierLoc(), S);
401 if (PrevDecl && !S->isDeclScope(PrevDecl))
402 PrevDecl = 0; // If in outer scope, it isn't the same thing.
403
404 Decl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000405 bool InvalidDecl = false;
406
Chris Lattner4b009652007-07-25 00:24:17 +0000407 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
408 assert(Init == 0 && "Can't have initializer for a typedef!");
409 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
410 if (!NewTD) return 0;
411
412 // Handle attributes prior to checking for duplicates in MergeVarDecl
413 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
414 D.getAttributes());
415 // Merge the decl with the existing one if appropriate.
416 if (PrevDecl) {
417 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
418 if (NewTD == 0) return 0;
419 }
420 New = NewTD;
421 if (S->getParent() == 0) {
422 // C99 6.7.7p2: If a typedef name specifies a variably modified type
423 // then it shall have block scope.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000424 if (const VariableArrayType *VAT =
425 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
426 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
427 VAT->getSizeExpr()->getSourceRange());
428 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000429 }
430 }
431 } else if (D.isFunctionDeclarator()) {
432 assert(Init == 0 && "Can't have an initializer for a functiondecl!");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000433
Chris Lattner4b009652007-07-25 00:24:17 +0000434 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000435 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000436
437 FunctionDecl::StorageClass SC;
438 switch (D.getDeclSpec().getStorageClassSpec()) {
439 default: assert(0 && "Unknown storage class!");
440 case DeclSpec::SCS_auto:
441 case DeclSpec::SCS_register:
442 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
443 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000444 InvalidDecl = true;
445 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000446 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
447 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
448 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
449 }
450
451 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000452 D.getDeclSpec().isInlineSpecified(),
Chris Lattner4b009652007-07-25 00:24:17 +0000453 LastDeclarator);
454
455 // Merge the decl with the existing one if appropriate.
456 if (PrevDecl) {
457 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
458 if (NewFD == 0) return 0;
459 }
460 New = NewFD;
461 } else {
462 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffcae537d2007-08-28 18:45:29 +0000463 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000464
465 VarDecl *NewVD;
466 VarDecl::StorageClass SC;
467 switch (D.getDeclSpec().getStorageClassSpec()) {
468 default: assert(0 && "Unknown storage class!");
469 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
470 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
471 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
472 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
473 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
474 }
475 if (S->getParent() == 0) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000476 if (Init) {
477 if (SC == VarDecl::Extern)
478 Diag(D.getIdentifierLoc(), diag::warn_extern_init);
479 CheckInitializer(Init, R, true);
480 }
Chris Lattner4b009652007-07-25 00:24:17 +0000481 // File scope. C99 6.9.2p2: A declaration of an identifier for and
482 // object that has file scope without an initializer, and without a
483 // storage-class specifier or with the storage-class specifier "static",
484 // constitutes a tentative definition. Note: A tentative definition with
485 // external linkage is valid (C99 6.2.2p5).
486 if (!Init && SC == VarDecl::Static) {
487 // C99 6.9.2p3: If the declaration of an identifier for an object is
488 // a tentative definition and has internal linkage (C99 6.2.2p3), the
489 // declared type shall not be an incomplete type.
490 if (R->isIncompleteType()) {
491 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
492 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000493 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000494 }
495 }
496 // C99 6.9p2: The storage-class specifiers auto and register shall not
497 // appear in the declaration specifiers in an external declaration.
498 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
499 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
500 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000501 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000502 }
Steve Naroff5eb879b2007-08-31 17:20:07 +0000503 if (SC == VarDecl::Static) {
504 // C99 6.7.5.2p2: If an identifier is declared to be an object with
505 // static storage duration, it shall not have a variable length array.
506 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
507 Expr *Size = VLA->getSizeExpr();
508 if (Size || (!Size && !Init)) {
509 // FIXME: Since we don't support initializers yet, we only emit this
510 // error when we don't have an initializer. Once initializers are
511 // implemented, the VLA will change to a CLA.
512 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
513 InvalidDecl = true;
514 }
515 }
Chris Lattner4b009652007-07-25 00:24:17 +0000516 }
517 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000518 } else {
519 if (Init) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000520 if (SC == VarDecl::Extern) { // C99 6.7.8p5
521 Diag(D.getIdentifierLoc(), diag::err_block_extern_cant_init);
522 InvalidDecl = true;
523 } else {
524 CheckInitializer(Init, R, SC == VarDecl::Static);
525 }
Steve Naroffe14e5542007-09-02 02:04:30 +0000526 }
Chris Lattner4b009652007-07-25 00:24:17 +0000527 // Block scope. C99 6.7p7: If an identifier for an object is declared with
528 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
529 if (SC != VarDecl::Extern) {
530 if (R->isIncompleteType()) {
531 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
532 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000533 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000534 }
535 }
536 if (SC == VarDecl::Static) {
537 // C99 6.7.5.2p2: If an identifier is declared to be an object with
538 // static storage duration, it shall not have a variable length array.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000539 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
540 Expr *Size = VLA->getSizeExpr();
541 if (Size || (!Size && !Init)) {
542 // FIXME: Since we don't support initializers yet, we only emit this
543 // error when we don't have an initializer. Once initializers are
544 // implemented, the VLA will change to a CLA.
545 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffcae537d2007-08-28 18:45:29 +0000546 InvalidDecl = true;
Steve Naroff5eb879b2007-08-31 17:20:07 +0000547 }
Chris Lattner4b009652007-07-25 00:24:17 +0000548 }
549 }
550 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000551 }
Chris Lattner4b009652007-07-25 00:24:17 +0000552 // Handle attributes prior to checking for duplicates in MergeVarDecl
553 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
554 D.getAttributes());
555
556 // Merge the decl with the existing one if appropriate.
557 if (PrevDecl) {
558 NewVD = MergeVarDecl(NewVD, PrevDecl);
559 if (NewVD == 0) return 0;
560 }
Steve Naroffe14e5542007-09-02 02:04:30 +0000561 if (Init) { // FIXME: This will likely move up above...for now, it stays.
Steve Naroff0f32f432007-08-24 22:33:52 +0000562 NewVD->setInit(Init);
563 }
Chris Lattner4b009652007-07-25 00:24:17 +0000564 New = NewVD;
565 }
566
567 // If this has an identifier, add it to the scope stack.
568 if (II) {
569 New->setNext(II->getFETokenInfo<Decl>());
570 II->setFETokenInfo(New);
571 S->AddDecl(New);
572 }
573
574 if (S->getParent() == 0)
575 AddTopLevelDecl(New, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000576
577 // If any semantic error occurred, mark the decl as invalid.
578 if (D.getInvalidType() || InvalidDecl)
579 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000580
581 return New;
582}
583
584/// The declarators are chained together backwards, reverse the list.
585Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
586 // Often we have single declarators, handle them quickly.
587 Decl *Group = static_cast<Decl*>(group);
588 if (Group == 0 || Group->getNextDeclarator() == 0) return Group;
589
590 Decl *NewGroup = 0;
591 while (Group) {
592 Decl *Next = Group->getNextDeclarator();
593 Group->setNextDeclarator(NewGroup);
594 NewGroup = Group;
595 Group = Next;
596 }
597 return NewGroup;
598}
Steve Naroff91b03f72007-08-28 03:03:08 +0000599
600// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000601ParmVarDecl *
602Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
603 Scope *FnScope) {
604 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
605
606 IdentifierInfo *II = PI.Ident;
607 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
608 // Can this happen for params? We already checked that they don't conflict
609 // among each other. Here they can only shadow globals, which is ok.
610 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
611 PI.IdentLoc, FnScope)) {
612
613 }
614
615 // FIXME: Handle storage class (auto, register). No declarator?
616 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000617
618 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
619 // Doing the promotion here has a win and a loss. The win is the type for
620 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
621 // code generator). The loss is the orginal type isn't preserved. For example:
622 //
623 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
624 // int blockvardecl[5];
625 // sizeof(parmvardecl); // size == 4
626 // sizeof(blockvardecl); // size == 20
627 // }
628 //
629 // For expressions, all implicit conversions are captured using the
630 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
631 //
632 // FIXME: If a source translation tool needs to see the original type, then
633 // we need to consider storing both types (in ParmVarDecl)...
634 //
635 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
636 if (const ArrayType *AT = parmDeclType->getAsArrayType())
637 parmDeclType = Context.getPointerType(AT->getElementType());
638 else if (parmDeclType->isFunctionType())
639 parmDeclType = Context.getPointerType(parmDeclType);
640
641 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffcae537d2007-08-28 18:45:29 +0000642 VarDecl::None, 0);
643 if (PI.InvalidType)
644 New->setInvalidDecl();
645
Chris Lattner4b009652007-07-25 00:24:17 +0000646 // If this has an identifier, add it to the scope stack.
647 if (II) {
648 New->setNext(II->getFETokenInfo<Decl>());
649 II->setFETokenInfo(New);
650 FnScope->AddDecl(New);
651 }
652
653 return New;
654}
655
656
657Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
658 assert(CurFunctionDecl == 0 && "Function parsing confused");
659 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
660 "Not a function declarator!");
661 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
662
663 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
664 // for a K&R function.
665 if (!FTI.hasPrototype) {
666 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
667 if (FTI.ArgInfo[i].TypeInfo == 0) {
668 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
669 FTI.ArgInfo[i].Ident->getName());
670 // Implicitly declare the argument as type 'int' for lack of a better
671 // type.
672 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
673 }
674 }
675
676 // Since this is a function definition, act as though we have information
677 // about the arguments.
678 FTI.hasPrototype = true;
679 } else {
680 // FIXME: Diagnose arguments without names in C.
681
682 }
683
684 Scope *GlobalScope = FnBodyScope->getParent();
685
686 FunctionDecl *FD =
687 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0, 0));
688 CurFunctionDecl = FD;
689
690 // Create Decl objects for each parameter, adding them to the FunctionDecl.
691 llvm::SmallVector<ParmVarDecl*, 16> Params;
692
693 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
694 // no arguments, not a function that takes a single void argument.
695 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
696 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
697 // empty arg list, don't push any params.
698 } else {
699 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
700 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
701 }
702
703 FD->setParams(&Params[0], Params.size());
704
705 return FD;
706}
707
708Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
709 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
710 FD->setBody((Stmt*)Body);
711
712 assert(FD == CurFunctionDecl && "Function parsing confused");
713 CurFunctionDecl = 0;
714
715 // Verify and clean out per-function state.
716
717 // Check goto/label use.
718 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
719 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
720 // Verify that we have no forward references left. If so, there was a goto
721 // or address of a label taken, but no definition of it. Label fwd
722 // definitions are indicated with a null substmt.
723 if (I->second->getSubStmt() == 0) {
724 LabelStmt *L = I->second;
725 // Emit error.
726 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
727
728 // At this point, we have gotos that use the bogus label. Stitch it into
729 // the function body so that they aren't leaked and that the AST is well
730 // formed.
731 L->setSubStmt(new NullStmt(L->getIdentLoc()));
732 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
733 }
734 }
735 LabelMap.clear();
736
737 return FD;
738}
739
740
741/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
742/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
743Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
744 Scope *S) {
745 if (getLangOptions().C99) // Extension in C99.
746 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
747 else // Legal in C90, but warn about it.
748 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
749
750 // FIXME: handle stuff like:
751 // void foo() { extern float X(); }
752 // void bar() { X(); } <-- implicit decl for X in another scope.
753
754 // Set a Declarator for the implicit definition: int foo();
755 const char *Dummy;
756 DeclSpec DS;
757 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
758 Error = Error; // Silence warning.
759 assert(!Error && "Error setting up implicit decl!");
760 Declarator D(DS, Declarator::BlockContext);
761 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
762 D.SetIdentifier(&II, Loc);
763
764 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000765 if (Scope *FnS = S->getFnParent())
766 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000767 while (S->getParent())
768 S = S->getParent();
769
770 return static_cast<Decl*>(ParseDeclarator(S, D, 0, 0));
771}
772
773
774TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
775 Decl *LastDeclarator) {
776 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
777
778 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000779 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000780
781 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000782 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
783 T, LastDeclarator);
784 if (D.getInvalidType())
785 NewTD->setInvalidDecl();
786 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +0000787}
788
789
790/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
791/// former case, Name will be non-null. In the later case, Name will be null.
792/// TagType indicates what kind of tag this is. TK indicates whether this is a
793/// reference/declaration/definition of a tag.
794Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
795 SourceLocation KWLoc, IdentifierInfo *Name,
796 SourceLocation NameLoc, AttributeList *Attr) {
797 // If this is a use of an existing tag, it must have a name.
798 assert((Name != 0 || TK == TK_Definition) &&
799 "Nameless record must be a definition!");
800
801 Decl::Kind Kind;
802 switch (TagType) {
803 default: assert(0 && "Unknown tag type!");
804 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
805 case DeclSpec::TST_union: Kind = Decl::Union; break;
806//case DeclSpec::TST_class: Kind = Decl::Class; break;
807 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
808 }
809
810 // If this is a named struct, check to see if there was a previous forward
811 // declaration or definition.
812 if (TagDecl *PrevDecl =
813 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
814 NameLoc, S))) {
815
816 // If this is a use of a previous tag, or if the tag is already declared in
817 // the same scope (so that the definition/declaration completes or
818 // rementions the tag), reuse the decl.
819 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
820 // Make sure that this wasn't declared as an enum and now used as a struct
821 // or something similar.
822 if (PrevDecl->getKind() != Kind) {
823 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
824 Diag(PrevDecl->getLocation(), diag::err_previous_use);
825 }
826
827 // If this is a use or a forward declaration, we're good.
828 if (TK != TK_Definition)
829 return PrevDecl;
830
831 // Diagnose attempts to redefine a tag.
832 if (PrevDecl->isDefinition()) {
833 Diag(NameLoc, diag::err_redefinition, Name->getName());
834 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
835 // If this is a redefinition, recover by making this struct be
836 // anonymous, which will make any later references get the previous
837 // definition.
838 Name = 0;
839 } else {
840 // Okay, this is definition of a previously declared or referenced tag.
841 // Move the location of the decl to be the definition site.
842 PrevDecl->setLocation(NameLoc);
843 return PrevDecl;
844 }
845 }
846 // If we get here, this is a definition of a new struct type in a nested
847 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
848 // type.
849 }
850
851 // If there is an identifier, use the location of the identifier as the
852 // location of the decl, otherwise use the location of the struct/union
853 // keyword.
854 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
855
856 // Otherwise, if this is the first time we've seen this tag, create the decl.
857 TagDecl *New;
858 switch (Kind) {
859 default: assert(0 && "Unknown tag kind!");
860 case Decl::Enum:
861 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
862 // enum X { A, B, C } D; D should chain to X.
863 New = new EnumDecl(Loc, Name, 0);
864 // If this is an undefined enum, warn.
865 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
866 break;
867 case Decl::Union:
868 case Decl::Struct:
869 case Decl::Class:
870 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
871 // struct X { int A; } D; D should chain to X.
872 New = new RecordDecl(Kind, Loc, Name, 0);
873 break;
874 }
875
876 // If this has an identifier, add it to the scope stack.
877 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +0000878 // The scope passed in may not be a decl scope. Zip up the scope tree until
879 // we find one that is.
880 while ((S->getFlags() & Scope::DeclScope) == 0)
881 S = S->getParent();
882
883 // Add it to the decl chain.
Chris Lattner4b009652007-07-25 00:24:17 +0000884 New->setNext(Name->getFETokenInfo<Decl>());
885 Name->setFETokenInfo(New);
886 S->AddDecl(New);
887 }
888
889 return New;
890}
891
892/// ParseField - Each field of a struct/union/class is passed into this in order
893/// to create a FieldDecl object for it.
894Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
895 SourceLocation DeclStart,
896 Declarator &D, ExprTy *BitfieldWidth) {
897 IdentifierInfo *II = D.getIdentifier();
898 Expr *BitWidth = (Expr*)BitfieldWidth;
899
900 SourceLocation Loc = DeclStart;
901 if (II) Loc = D.getIdentifierLoc();
902
903 // FIXME: Unnamed fields can be handled in various different ways, for
904 // example, unnamed unions inject all members into the struct namespace!
905
906
907 if (BitWidth) {
908 // TODO: Validate.
909 //printf("WARNING: BITFIELDS IGNORED!\n");
910
911 // 6.7.2.1p3
912 // 6.7.2.1p4
913
914 } else {
915 // Not a bitfield.
916
917 // validate II.
918
919 }
920
921 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000922 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
923 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +0000924
Chris Lattner4b009652007-07-25 00:24:17 +0000925 // C99 6.7.2.1p8: A member of a structure or union may have any type other
926 // than a variably modified type.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000927 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
928 Diag(Loc, diag::err_typecheck_illegal_vla,
929 VAT->getSizeExpr()->getSourceRange());
930 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000931 }
Chris Lattner4b009652007-07-25 00:24:17 +0000932 // FIXME: Chain fielddecls together.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000933 FieldDecl *NewFD = new FieldDecl(Loc, II, T, 0);
934 if (D.getInvalidType() || InvalidDecl)
935 NewFD->setInvalidDecl();
936 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +0000937}
938
939void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
940 DeclTy **Fields, unsigned NumFields) {
941 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
942 if (Record->isDefinition()) {
943 // Diagnose code like:
944 // struct S { struct S {} X; };
945 // We discover this when we complete the outer S. Reject and ignore the
946 // outer S.
947 Diag(Record->getLocation(), diag::err_nested_redefinition,
948 Record->getKindName());
949 Diag(RecLoc, diag::err_previous_definition);
950 return;
951 }
952
953 // Verify that all the fields are okay.
954 unsigned NumNamedMembers = 0;
955 llvm::SmallVector<FieldDecl*, 32> RecFields;
956 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
957
958 for (unsigned i = 0; i != NumFields; ++i) {
959 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
960 if (!FD) continue; // Already issued a diagnostic.
961
962 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +0000963 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +0000964
965 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +0000966 if (FDTy->isFunctionType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000967 Diag(FD->getLocation(), diag::err_field_declared_as_function,
968 FD->getName());
969 delete FD;
970 continue;
971 }
972
973 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
974 if (FDTy->isIncompleteType()) {
975 if (i != NumFields-1 || // ... that the last member ...
976 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +0000977 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +0000978 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
979 delete FD;
980 continue;
981 }
982 if (NumNamedMembers < 1) { //... must have more than named member ...
983 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
984 FD->getName());
985 delete FD;
986 continue;
987 }
988
989 // Okay, we have a legal flexible array member at the end of the struct.
990 Record->setHasFlexibleArrayMember(true);
991 }
992
993
994 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
995 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +0000996 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000997 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
998 // If this is a member of a union, then entire union becomes "flexible".
999 if (Record->getKind() == Decl::Union) {
1000 Record->setHasFlexibleArrayMember(true);
1001 } else {
1002 // If this is a struct/class and this is not the last element, reject
1003 // it. Note that GCC supports variable sized arrays in the middle of
1004 // structures.
1005 if (i != NumFields-1) {
1006 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1007 FD->getName());
1008 delete FD;
1009 continue;
1010 }
1011
1012 // We support flexible arrays at the end of structs in other structs
1013 // as an extension.
1014 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1015 FD->getName());
1016 Record->setHasFlexibleArrayMember(true);
1017 }
1018 }
1019 }
1020
1021 // Keep track of the number of named members.
1022 if (IdentifierInfo *II = FD->getIdentifier()) {
1023 // Detect duplicate member names.
1024 if (!FieldIDs.insert(II)) {
1025 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1026 // Find the previous decl.
1027 SourceLocation PrevLoc;
1028 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1029 assert(i != e && "Didn't find previous def!");
1030 if (RecFields[i]->getIdentifier() == II) {
1031 PrevLoc = RecFields[i]->getLocation();
1032 break;
1033 }
1034 }
1035 Diag(PrevLoc, diag::err_previous_definition);
1036 delete FD;
1037 continue;
1038 }
1039 ++NumNamedMembers;
1040 }
1041
1042 // Remember good fields.
1043 RecFields.push_back(FD);
1044 }
1045
1046
1047 // Okay, we successfully defined 'Record'.
1048 Record->defineBody(&RecFields[0], RecFields.size());
1049}
1050
1051Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
1052 DeclTy *lastEnumConst,
1053 SourceLocation IdLoc, IdentifierInfo *Id,
1054 SourceLocation EqualLoc, ExprTy *val) {
1055 theEnumDecl = theEnumDecl; // silence unused warning.
1056 EnumConstantDecl *LastEnumConst =
1057 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1058 Expr *Val = static_cast<Expr*>(val);
1059
Chris Lattnera7549902007-08-26 06:24:45 +00001060 // The scope passed in may not be a decl scope. Zip up the scope tree until
1061 // we find one that is.
1062 while ((S->getFlags() & Scope::DeclScope) == 0)
1063 S = S->getParent();
1064
Chris Lattner4b009652007-07-25 00:24:17 +00001065 // Verify that there isn't already something declared with this name in this
1066 // scope.
1067 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
1068 if (S->isDeclScope(PrevDecl)) {
1069 if (isa<EnumConstantDecl>(PrevDecl))
1070 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1071 else
1072 Diag(IdLoc, diag::err_redefinition, Id->getName());
1073 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1074 // FIXME: Don't leak memory: delete Val;
1075 return 0;
1076 }
1077 }
1078
1079 llvm::APSInt EnumVal(32);
1080 QualType EltTy;
1081 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001082 // Make sure to promote the operand type to int.
1083 UsualUnaryConversions(Val);
1084
Chris Lattner4b009652007-07-25 00:24:17 +00001085 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1086 SourceLocation ExpLoc;
1087 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1088 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1089 Id->getName());
1090 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001091 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001092 } else {
1093 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001094 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001095 }
1096
1097 if (!Val) {
1098 if (LastEnumConst) {
1099 // Assign the last value + 1.
1100 EnumVal = LastEnumConst->getInitVal();
1101 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001102
1103 // Check for overflow on increment.
1104 if (EnumVal < LastEnumConst->getInitVal())
1105 Diag(IdLoc, diag::warn_enum_value_overflow);
1106
Chris Lattnere7f53a42007-08-27 17:37:24 +00001107 EltTy = LastEnumConst->getType();
1108 } else {
1109 // First value, set to zero.
1110 EltTy = Context.IntTy;
Chris Lattner2cda8792007-08-27 21:16:18 +00001111 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy, IdLoc));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001112 }
Chris Lattner4b009652007-07-25 00:24:17 +00001113 }
1114
Chris Lattner4b009652007-07-25 00:24:17 +00001115 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1116 LastEnumConst);
1117
1118 // Register this decl in the current scope stack.
1119 New->setNext(Id->getFETokenInfo<Decl>());
1120 Id->setFETokenInfo(New);
1121 S->AddDecl(New);
1122 return New;
1123}
1124
1125void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1126 DeclTy **Elements, unsigned NumElements) {
1127 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1128 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1129
Chris Lattner435c3fd2007-08-28 05:10:31 +00001130 // TODO: If the result value doesn't fit in an int, it must be a long or long
1131 // long value. ISO C does not support this, but GCC does as an extension,
1132 // emit a warning.
Chris Lattner206754a2007-08-28 06:15:15 +00001133 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner435c3fd2007-08-28 05:10:31 +00001134
1135
Chris Lattner206754a2007-08-28 06:15:15 +00001136 // Verify that all the values are okay, compute the size of the values, and
1137 // reverse the list.
1138 unsigned NumNegativeBits = 0;
1139 unsigned NumPositiveBits = 0;
1140
1141 // Keep track of whether all elements have type int.
1142 bool AllElementsInt = true;
1143
Chris Lattner4b009652007-07-25 00:24:17 +00001144 EnumConstantDecl *EltList = 0;
1145 for (unsigned i = 0; i != NumElements; ++i) {
1146 EnumConstantDecl *ECD =
1147 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1148 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001149
1150 // If the enum value doesn't fit in an int, emit an extension warning.
1151 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1152 "Should have promoted value to int");
1153 const llvm::APSInt &InitVal = ECD->getInitVal();
1154 if (InitVal.getBitWidth() > IntWidth) {
1155 llvm::APSInt V(InitVal);
1156 V.trunc(IntWidth);
1157 V.extend(InitVal.getBitWidth());
1158 if (V != InitVal)
1159 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1160 InitVal.toString());
1161 }
Chris Lattner206754a2007-08-28 06:15:15 +00001162
1163 // Keep track of the size of positive and negative values.
1164 if (InitVal.isUnsigned() || !InitVal.isNegative())
1165 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1166 else
1167 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001168
Chris Lattner206754a2007-08-28 06:15:15 +00001169 // Keep track of whether every enum element has type int (very commmon).
1170 if (AllElementsInt)
1171 AllElementsInt = ECD->getType() == Context.IntTy;
1172
Chris Lattner4b009652007-07-25 00:24:17 +00001173 ECD->setNextDeclarator(EltList);
1174 EltList = ECD;
1175 }
1176
Chris Lattner206754a2007-08-28 06:15:15 +00001177 // Figure out the type that should be used for this enum.
1178 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1179 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001180 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001181
1182 if (NumNegativeBits) {
1183 // If there is a negative value, figure out the smallest integer type (of
1184 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001185 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001186 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001187 BestWidth = IntWidth;
1188 } else {
1189 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1190 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001191 BestType = Context.LongTy;
1192 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001193 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1194 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001195 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1196 BestType = Context.LongLongTy;
1197 }
1198 }
1199 } else {
1200 // If there is no negative value, figure out which of uint, ulong, ulonglong
1201 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001202 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001203 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001204 BestWidth = IntWidth;
1205 } else if (NumPositiveBits <=
1206 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattner206754a2007-08-28 06:15:15 +00001207 BestType = Context.UnsignedLongTy;
1208 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001209 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1210 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001211 "How could an initializer get larger than ULL?");
1212 BestType = Context.UnsignedLongLongTy;
1213 }
1214 }
1215
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001216 // Loop over all of the enumerator constants, changing their types to match
1217 // the type of the enum if needed.
1218 for (unsigned i = 0; i != NumElements; ++i) {
1219 EnumConstantDecl *ECD =
1220 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1221 if (!ECD) continue; // Already issued a diagnostic.
1222
1223 // Standard C says the enumerators have int type, but we allow, as an
1224 // extension, the enumerators to be larger than int size. If each
1225 // enumerator value fits in an int, type it as an int, otherwise type it the
1226 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1227 // that X has type 'int', not 'unsigned'.
1228 if (ECD->getType() == Context.IntTy)
1229 continue; // Already int type.
1230
1231 // Determine whether the value fits into an int.
1232 llvm::APSInt InitVal = ECD->getInitVal();
1233 bool FitsInInt;
1234 if (InitVal.isUnsigned() || !InitVal.isNegative())
1235 FitsInInt = InitVal.getActiveBits() < IntWidth;
1236 else
1237 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1238
1239 // If it fits into an integer type, force it. Otherwise force it to match
1240 // the enum decl type.
1241 QualType NewTy;
1242 unsigned NewWidth;
1243 bool NewSign;
1244 if (FitsInInt) {
1245 NewTy = Context.IntTy;
1246 NewWidth = IntWidth;
1247 NewSign = true;
1248 } else if (ECD->getType() == BestType) {
1249 // Already the right type!
1250 continue;
1251 } else {
1252 NewTy = BestType;
1253 NewWidth = BestWidth;
1254 NewSign = BestType->isSignedIntegerType();
1255 }
1256
1257 // Adjust the APSInt value.
1258 InitVal.extOrTrunc(NewWidth);
1259 InitVal.setIsSigned(NewSign);
1260 ECD->setInitVal(InitVal);
1261
1262 // Adjust the Expr initializer and type.
1263 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1264 ECD->setType(NewTy);
1265 }
Chris Lattner206754a2007-08-28 06:15:15 +00001266
Chris Lattner90a018d2007-08-28 18:24:31 +00001267 Enum->defineElements(EltList, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00001268}
1269
1270void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1271 if (!current) return;
1272
1273 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1274 // remember this in the LastInGroupList list.
1275 if (last)
1276 LastInGroupList.push_back((Decl*)last);
1277}
1278
1279void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1280 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1281 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1282 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1283 if (!newType.isNull()) // install the new vector type into the decl
1284 vDecl->setType(newType);
1285 }
1286 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1287 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1288 rawAttr);
1289 if (!newType.isNull()) // install the new vector type into the decl
1290 tDecl->setUnderlyingType(newType);
1291 }
1292 }
1293 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroff82113e32007-07-29 16:33:31 +00001294 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1295 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1296 else
Chris Lattner4b009652007-07-25 00:24:17 +00001297 Diag(rawAttr->getAttributeLoc(),
1298 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner4b009652007-07-25 00:24:17 +00001299 }
1300 // FIXME: add other attributes...
1301}
1302
1303void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1304 AttributeList *declarator_postfix) {
1305 while (declspec_prefix) {
1306 HandleDeclAttribute(New, declspec_prefix);
1307 declspec_prefix = declspec_prefix->getNext();
1308 }
1309 while (declarator_postfix) {
1310 HandleDeclAttribute(New, declarator_postfix);
1311 declarator_postfix = declarator_postfix->getNext();
1312 }
1313}
1314
Steve Naroff82113e32007-07-29 16:33:31 +00001315void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1316 AttributeList *rawAttr) {
1317 QualType curType = tDecl->getUnderlyingType();
Chris Lattner4b009652007-07-25 00:24:17 +00001318 // check the attribute arugments.
1319 if (rawAttr->getNumArgs() != 1) {
1320 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1321 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001322 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001323 }
1324 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1325 llvm::APSInt vecSize(32);
1326 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1327 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1328 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001329 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001330 }
1331 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1332 // in conjunction with complex types (pointers, arrays, functions, etc.).
1333 Type *canonType = curType.getCanonicalType().getTypePtr();
1334 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1335 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1336 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001337 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001338 }
1339 // unlike gcc's vector_size attribute, the size is specified as the
1340 // number of elements, not the number of bytes.
1341 unsigned vectorSize = vecSize.getZExtValue();
1342
1343 if (vectorSize == 0) {
1344 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1345 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001346 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001347 }
Steve Naroff82113e32007-07-29 16:33:31 +00001348 // Instantiate/Install the vector type, the number of elements is > 0.
1349 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1350 // Remember this typedef decl, we will need it later for diagnostics.
1351 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001352}
1353
1354QualType Sema::HandleVectorTypeAttribute(QualType curType,
1355 AttributeList *rawAttr) {
1356 // check the attribute arugments.
1357 if (rawAttr->getNumArgs() != 1) {
1358 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1359 std::string("1"));
1360 return QualType();
1361 }
1362 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1363 llvm::APSInt vecSize(32);
1364 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1365 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1366 sizeExpr->getSourceRange());
1367 return QualType();
1368 }
1369 // navigate to the base type - we need to provide for vector pointers,
1370 // vector arrays, and functions returning vectors.
1371 Type *canonType = curType.getCanonicalType().getTypePtr();
1372
1373 if (canonType->isPointerType() || canonType->isArrayType() ||
1374 canonType->isFunctionType()) {
1375 assert(1 && "HandleVector(): Complex type construction unimplemented");
1376 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1377 do {
1378 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1379 canonType = PT->getPointeeType().getTypePtr();
1380 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1381 canonType = AT->getElementType().getTypePtr();
1382 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1383 canonType = FT->getResultType().getTypePtr();
1384 } while (canonType->isPointerType() || canonType->isArrayType() ||
1385 canonType->isFunctionType());
1386 */
1387 }
1388 // the base type must be integer or float.
1389 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1390 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1391 curType.getCanonicalType().getAsString());
1392 return QualType();
1393 }
1394 unsigned typeSize = Context.getTypeSize(curType, rawAttr->getAttributeLoc());
1395 // vecSize is specified in bytes - convert to bits.
1396 unsigned vectorSize = vecSize.getZExtValue() * 8;
1397
1398 // the vector size needs to be an integral multiple of the type size.
1399 if (vectorSize % typeSize) {
1400 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1401 sizeExpr->getSourceRange());
1402 return QualType();
1403 }
1404 if (vectorSize == 0) {
1405 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1406 sizeExpr->getSourceRange());
1407 return QualType();
1408 }
1409 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1410 // the number of elements to be a power of two (unlike GCC).
1411 // Instantiate the vector type, the number of elements is > 0.
1412 return Context.getVectorType(curType, vectorSize/typeSize);
1413}
1414