blob: 245e75c3b6016747fe7a021203c5d29ca12b4cf9 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Builtins.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/Type.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Parse/Scope.h"
22#include "clang/Lex/IdentifierTable.h"
23#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
25#include "llvm/ADT/SmallSet.h"
26using namespace clang;
27
Reid Spencer5f016e22007-07-11 17:01:13 +000028Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Steve Naroff3536b442007-09-06 21:24:23 +000029 Decl *IIDecl = II.getFETokenInfo<Decl>();
30 if (dyn_cast_or_null<TypedefDecl>(IIDecl) ||
31 dyn_cast_or_null<ObjcInterfaceDecl>(IIDecl))
32 return IIDecl;
33 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000034}
35
36void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000037 if (S->decl_empty()) return;
38 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
39
Reid Spencer5f016e22007-07-11 17:01:13 +000040 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
41 I != E; ++I) {
42 Decl *D = static_cast<Decl*>(*I);
43 assert(D && "This decl didn't get pushed??");
44 IdentifierInfo *II = D->getIdentifier();
45 if (!II) continue;
46
47 // Unlink this decl from the identifier. Because the scope contains decls
48 // in an unordered collection, and because we have multiple identifier
49 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
50 if (II->getFETokenInfo<Decl>() == D) {
51 // Normal case, no multiple decls in different namespaces.
52 II->setFETokenInfo(D->getNext());
53 } else {
54 // Scan ahead. There are only three namespaces in C, so this loop can
55 // never execute more than 3 times.
56 Decl *SomeDecl = II->getFETokenInfo<Decl>();
57 while (SomeDecl->getNext() != D) {
58 SomeDecl = SomeDecl->getNext();
59 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
60 }
61 SomeDecl->setNext(D->getNext());
62 }
63
64 // This will have to be revisited for C++: there we want to nest stuff in
65 // namespace decls etc. Even for C, we might want a top-level translation
66 // unit decl or something.
67 if (!CurFunctionDecl)
68 continue;
69
70 // Chain this decl to the containing function, it now owns the memory for
71 // the decl.
72 D->setNext(CurFunctionDecl->getDeclChain());
73 CurFunctionDecl->setDeclChain(D);
74 }
75}
76
77/// LookupScopedDecl - Look up the inner-most declaration in the specified
78/// namespace.
79Decl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
80 SourceLocation IdLoc, Scope *S) {
81 if (II == 0) return 0;
82 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
83
84 // Scan up the scope chain looking for a decl that matches this identifier
85 // that is in the appropriate namespace. This search should not take long, as
86 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
87 for (Decl *D = II->getFETokenInfo<Decl>(); D; D = D->getNext())
88 if (D->getIdentifierNamespace() == NS)
89 return D;
90
91 // If we didn't find a use of this identifier, and if the identifier
92 // corresponds to a compiler builtin, create the decl object for the builtin
93 // now, injecting it into translation unit scope, and return it.
94 if (NS == Decl::IDNS_Ordinary) {
95 // If this is a builtin on some other target, or if this builtin varies
96 // across targets (e.g. in type), emit a diagnostic and mark the translation
97 // unit non-portable for using it.
98 if (II->isNonPortableBuiltin()) {
99 // Only emit this diagnostic once for this builtin.
100 II->setNonPortableBuiltin(false);
101 Context.Target.DiagnoseNonPortability(IdLoc,
102 diag::port_target_builtin_use);
103 }
104 // If this is a builtin on this (or all) targets, create the decl.
105 if (unsigned BuiltinID = II->getBuiltinID())
106 return LazilyCreateBuiltin(II, BuiltinID, S);
107 }
108 return 0;
109}
110
111/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
112/// lazily create a decl for it.
113Decl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
114 Builtin::ID BID = (Builtin::ID)bid;
115
116 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
117 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000118 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000119
120 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000121 if (Scope *FnS = S->getFnParent())
122 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 while (S->getParent())
124 S = S->getParent();
125 S->AddDecl(New);
126
127 // Add this decl to the end of the identifier info.
128 if (Decl *LastDecl = II->getFETokenInfo<Decl>()) {
129 // Scan until we find the last (outermost) decl in the id chain.
130 while (LastDecl->getNext())
131 LastDecl = LastDecl->getNext();
132 // Insert before (outside) it.
133 LastDecl->setNext(New);
134 } else {
135 II->setFETokenInfo(New);
136 }
137 // Make sure clients iterating over decls see this.
138 LastInGroupList.push_back(New);
139
140 return New;
141}
142
143/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
144/// and scope as a previous declaration 'Old'. Figure out how to resolve this
145/// situation, merging decls or emitting diagnostics as appropriate.
146///
147TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
148 // Verify the old decl was also a typedef.
149 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
150 if (!Old) {
151 Diag(New->getLocation(), diag::err_redefinition_different_kind,
152 New->getName());
153 Diag(OldD->getLocation(), diag::err_previous_definition);
154 return New;
155 }
156
157 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
158 // TODO: This is totally simplistic. It should handle merging functions
159 // together etc, merging extern int X; int X; ...
160 Diag(New->getLocation(), diag::err_redefinition, New->getName());
161 Diag(Old->getLocation(), diag::err_previous_definition);
162 return New;
163}
164
165/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
166/// and scope as a previous declaration 'Old'. Figure out how to resolve this
167/// situation, merging decls or emitting diagnostics as appropriate.
168///
169FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
170 // Verify the old decl was also a function.
171 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
172 if (!Old) {
173 Diag(New->getLocation(), diag::err_redefinition_different_kind,
174 New->getName());
175 Diag(OldD->getLocation(), diag::err_previous_definition);
176 return New;
177 }
178
179 // This is not right, but it's a start. If 'Old' is a function prototype with
180 // the same type as 'New', silently allow this. FIXME: We should link up decl
181 // objects here.
182 if (Old->getBody() == 0 &&
183 Old->getCanonicalType() == New->getCanonicalType()) {
184 return New;
185 }
186
187 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
188 // TODO: This is totally simplistic. It should handle merging functions
189 // together etc, merging extern int X; int X; ...
190 Diag(New->getLocation(), diag::err_redefinition, New->getName());
191 Diag(Old->getLocation(), diag::err_previous_definition);
192 return New;
193}
194
195/// MergeVarDecl - We just parsed a variable 'New' which has the same name
196/// and scope as a previous declaration 'Old'. Figure out how to resolve this
197/// situation, merging decls or emitting diagnostics as appropriate.
198///
199/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
200/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
201///
202VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
203 // Verify the old decl was also a variable.
204 VarDecl *Old = dyn_cast<VarDecl>(OldD);
205 if (!Old) {
206 Diag(New->getLocation(), diag::err_redefinition_different_kind,
207 New->getName());
208 Diag(OldD->getLocation(), diag::err_previous_definition);
209 return New;
210 }
Steve Narofffb22d962007-08-30 01:06:46 +0000211 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
212 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
213 bool OldIsTentative = false;
214
215 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
216 // Handle C "tentative" external object definitions. FIXME: finish!
217 if (!OldFSDecl->getInit() &&
218 (OldFSDecl->getStorageClass() == VarDecl::None ||
219 OldFSDecl->getStorageClass() == VarDecl::Static))
220 OldIsTentative = true;
221 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000222 // Verify the types match.
223 if (Old->getCanonicalType() != New->getCanonicalType()) {
224 Diag(New->getLocation(), diag::err_redefinition, New->getName());
225 Diag(Old->getLocation(), diag::err_previous_definition);
226 return New;
227 }
228 // We've verified the types match, now check if Old is "extern".
229 if (Old->getStorageClass() != VarDecl::Extern) {
230 Diag(New->getLocation(), diag::err_redefinition, New->getName());
231 Diag(Old->getLocation(), diag::err_previous_definition);
232 }
233 return New;
234}
235
236/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
237/// no declarator (e.g. "struct foo;") is parsed.
238Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
239 // TODO: emit error on 'int;' or 'const enum foo;'.
240 // TODO: emit error on 'typedef int;'
241 // if (!DS.isMissingDeclaratorOk()) Diag(...);
242
243 return 0;
244}
245
Steve Naroff9e8925e2007-09-04 14:36:54 +0000246bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000247 AssignmentCheckResult result;
248 SourceLocation loc = Init->getLocStart();
249 // Get the type before calling CheckSingleAssignmentConstraints(), since
250 // it can promote the expression.
251 QualType rhsType = Init->getType();
252
253 result = CheckSingleAssignmentConstraints(DeclType, Init);
254
255 // decode the result (notice that extensions still return a type).
256 switch (result) {
257 case Compatible:
258 break;
259 case Incompatible:
Steve Naroff6f9f3072007-09-02 15:34:30 +0000260 // FIXME: tighten up this check which should allow:
261 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
262 if (rhsType == Context.getPointerType(Context.CharTy))
263 break;
Steve Narofff0090632007-09-02 02:04:30 +0000264 Diag(loc, diag::err_typecheck_assign_incompatible,
265 DeclType.getAsString(), rhsType.getAsString(),
266 Init->getSourceRange());
267 return true;
268 case PointerFromInt:
269 // check for null pointer constant (C99 6.3.2.3p3)
270 if (!Init->isNullPointerConstant(Context)) {
271 Diag(loc, diag::ext_typecheck_assign_pointer_int,
272 DeclType.getAsString(), rhsType.getAsString(),
273 Init->getSourceRange());
274 return true;
275 }
276 break;
277 case IntFromPointer:
278 Diag(loc, diag::ext_typecheck_assign_pointer_int,
279 DeclType.getAsString(), rhsType.getAsString(),
280 Init->getSourceRange());
281 break;
282 case IncompatiblePointer:
283 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
284 DeclType.getAsString(), rhsType.getAsString(),
285 Init->getSourceRange());
286 break;
287 case CompatiblePointerDiscardsQualifiers:
288 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
289 DeclType.getAsString(), rhsType.getAsString(),
290 Init->getSourceRange());
291 break;
292 }
293 return false;
294}
295
Steve Naroff9e8925e2007-09-04 14:36:54 +0000296bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
297 bool isStatic, QualType ElementType) {
Steve Naroff371227d2007-09-04 02:20:04 +0000298 SourceLocation loc;
Steve Naroff9e8925e2007-09-04 14:36:54 +0000299 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff371227d2007-09-04 02:20:04 +0000300
301 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
302 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
303 return true;
304 } else if (CheckSingleInitializer(expr, ElementType)) {
305 return true; // types weren't compatible.
306 }
Steve Naroff9e8925e2007-09-04 14:36:54 +0000307 if (savExpr != expr) // The type was promoted, update initializer list.
308 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000309 return false;
310}
311
312void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
313 QualType ElementType, bool isStatic,
314 int &nInitializers, bool &hadError) {
Steve Naroff6f9f3072007-09-02 15:34:30 +0000315 for (unsigned i = 0; i < IList->getNumInits(); i++) {
316 Expr *expr = IList->getInit(i);
317
Steve Naroff371227d2007-09-04 02:20:04 +0000318 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
319 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000320 int maxElements = CAT->getMaximumElements();
Steve Naroff371227d2007-09-04 02:20:04 +0000321 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
322 maxElements, hadError);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000323 }
Steve Naroff371227d2007-09-04 02:20:04 +0000324 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000325 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000326 }
Steve Naroff371227d2007-09-04 02:20:04 +0000327 nInitializers++;
328 }
329 return;
330}
331
332// FIXME: Doesn't deal with arrays of structures yet.
333void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
334 QualType ElementType, bool isStatic,
335 int &totalInits, bool &hadError) {
336 int maxElementsAtThisLevel = 0;
337 int nInitsAtLevel = 0;
338
339 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
340 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff7cf8c442007-09-04 21:13:33 +0000341 maxElementsAtThisLevel = CAT->getMaximumElements();
342 // Set DeclType, used below to recurse (for multi-dimensional arrays).
343 DeclType = CAT->getElementType();
Steve Naroff371227d2007-09-04 02:20:04 +0000344 } else if (DeclType->isScalarType()) {
345 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
346 IList->getSourceRange());
347 maxElementsAtThisLevel = 1;
348 }
349 // The empty init list "{ }" is treated specially below.
350 unsigned numInits = IList->getNumInits();
351 if (numInits) {
352 for (unsigned i = 0; i < numInits; i++) {
353 Expr *expr = IList->getInit(i);
354
355 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
356 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
357 totalInits, hadError);
358 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000359 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff371227d2007-09-04 02:20:04 +0000360 nInitsAtLevel++; // increment the number of initializers at this level.
361 totalInits--; // decrement the total number of initializers.
362
363 // Check if we have space for another initializer.
364 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
365 Diag(expr->getLocStart(), diag::warn_excess_initializers,
366 expr->getSourceRange());
367 }
368 }
369 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
370 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
371 } else {
372 // we have an initializer list with no elements.
373 totalInits -= maxElementsAtThisLevel;
374 if (totalInits < 0)
375 Diag(IList->getLocStart(), diag::warn_excess_initializers,
376 IList->getSourceRange());
Steve Naroff6f9f3072007-09-02 15:34:30 +0000377 }
Steve Naroffd35005e2007-09-03 01:24:23 +0000378 return;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000379}
380
Steve Naroff9e8925e2007-09-04 14:36:54 +0000381bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Narofff0090632007-09-02 02:04:30 +0000382 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroffd35005e2007-09-03 01:24:23 +0000383 if (!InitList)
384 return CheckSingleInitializer(Init, DeclType);
385
Steve Narofff0090632007-09-02 02:04:30 +0000386 // We have an InitListExpr, make sure we set the type.
387 Init->setType(DeclType);
Steve Naroffd35005e2007-09-03 01:24:23 +0000388
389 bool hadError = false;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000390
Steve Naroff38374b02007-09-02 20:30:18 +0000391 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
392 // of unknown size ("[]") or an object type that is not a variable array type.
393 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
394 Expr *expr = VAT->getSizeExpr();
Steve Naroffd35005e2007-09-03 01:24:23 +0000395 if (expr)
396 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
397 expr->getSourceRange());
398
Steve Naroff7cf8c442007-09-04 21:13:33 +0000399 // We have a VariableArrayType with unknown size. Note that only the first
400 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff371227d2007-09-04 02:20:04 +0000401 int numInits = 0;
Steve Naroff7cf8c442007-09-04 21:13:33 +0000402 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
403 isStatic, numInits, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000404 if (!hadError) {
405 // Return a new array type from the number of initializers (C99 6.7.8p22).
406 llvm::APSInt ConstVal(32);
Steve Naroff371227d2007-09-04 02:20:04 +0000407 ConstVal = numInits;
408 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroffd35005e2007-09-03 01:24:23 +0000409 ArrayType::Normal, 0);
410 }
411 return hadError;
412 }
413 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000414 int maxElements = CAT->getMaximumElements();
415 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
416 isStatic, maxElements, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000417 return hadError;
418 }
Steve Naroff371227d2007-09-04 02:20:04 +0000419 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
420 int maxElements = 1;
421 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
422 hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000423 return hadError;
Steve Naroff38374b02007-09-02 20:30:18 +0000424 }
425 // FIXME: Handle struct/union types.
Steve Naroffd35005e2007-09-03 01:24:23 +0000426 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +0000427}
428
Reid Spencer5f016e22007-07-11 17:01:13 +0000429Sema::DeclTy *
Steve Naroffbb204692007-09-12 14:07:44 +0000430Sema::ParseDeclarator(Scope *S, Declarator &D, DeclTy *lastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000431 Decl *LastDeclarator = (Decl*)lastDeclarator;
432 IdentifierInfo *II = D.getIdentifier();
433
Chris Lattnere80a59c2007-07-25 00:24:17 +0000434 // All of these full declarators require an identifier. If it doesn't have
435 // one, the ParsedFreeStandingDeclSpec action should be used.
436 if (II == 0) {
Chris Lattner98e08632007-08-28 06:17:15 +0000437 Diag(D.getDeclSpec().getSourceRange().Begin(),
438 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000439 D.getDeclSpec().getSourceRange(), D.getSourceRange());
440 return 0;
441 }
442
Chris Lattner31e05722007-08-26 06:24:45 +0000443 // The scope passed in may not be a decl scope. Zip up the scope tree until
444 // we find one that is.
445 while ((S->getFlags() & Scope::DeclScope) == 0)
446 S = S->getParent();
447
Reid Spencer5f016e22007-07-11 17:01:13 +0000448 // See if this is a redefinition of a variable in the same scope.
449 Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
450 D.getIdentifierLoc(), S);
451 if (PrevDecl && !S->isDeclScope(PrevDecl))
452 PrevDecl = 0; // If in outer scope, it isn't the same thing.
453
454 Decl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000455 bool InvalidDecl = false;
456
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
458 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
459 if (!NewTD) return 0;
460
461 // Handle attributes prior to checking for duplicates in MergeVarDecl
462 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
463 D.getAttributes());
464 // Merge the decl with the existing one if appropriate.
465 if (PrevDecl) {
466 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
467 if (NewTD == 0) return 0;
468 }
469 New = NewTD;
470 if (S->getParent() == 0) {
471 // C99 6.7.7p2: If a typedef name specifies a variably modified type
472 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000473 if (const VariableArrayType *VAT =
474 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
475 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
476 VAT->getSizeExpr()->getSourceRange());
477 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000478 }
479 }
480 } else if (D.isFunctionDeclarator()) {
481 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000482 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000483
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 FunctionDecl::StorageClass SC;
485 switch (D.getDeclSpec().getStorageClassSpec()) {
486 default: assert(0 && "Unknown storage class!");
487 case DeclSpec::SCS_auto:
488 case DeclSpec::SCS_register:
489 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
490 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000491 InvalidDecl = true;
492 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000493 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
494 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
495 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
496 }
497
498 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000499 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 LastDeclarator);
501
502 // Merge the decl with the existing one if appropriate.
503 if (PrevDecl) {
504 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
505 if (NewFD == 0) return 0;
506 }
507 New = NewFD;
508 } else {
509 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff53a32342007-08-28 18:45:29 +0000510 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000511
512 VarDecl *NewVD;
513 VarDecl::StorageClass SC;
514 switch (D.getDeclSpec().getStorageClassSpec()) {
515 default: assert(0 && "Unknown storage class!");
516 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
517 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
518 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
519 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
520 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
521 }
522 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 // C99 6.9p2: The storage-class specifiers auto and register shall not
524 // appear in the declaration specifiers in an external declaration.
525 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
526 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
527 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000528 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000529 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000530 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000531 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000533 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000534 // Handle attributes prior to checking for duplicates in MergeVarDecl
535 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
536 D.getAttributes());
537
538 // Merge the decl with the existing one if appropriate.
539 if (PrevDecl) {
540 NewVD = MergeVarDecl(NewVD, PrevDecl);
541 if (NewVD == 0) return 0;
542 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 New = NewVD;
544 }
545
546 // If this has an identifier, add it to the scope stack.
547 if (II) {
548 New->setNext(II->getFETokenInfo<Decl>());
549 II->setFETokenInfo(New);
550 S->AddDecl(New);
551 }
552
553 if (S->getParent() == 0)
554 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +0000555
556 // If any semantic error occurred, mark the decl as invalid.
557 if (D.getInvalidType() || InvalidDecl)
558 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000559
560 return New;
561}
562
Steve Naroffbb204692007-09-12 14:07:44 +0000563void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000564 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000565 Expr *Init = static_cast<Expr *>(init);
566
Steve Naroff410e3e22007-09-12 20:13:48 +0000567 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000568
Steve Naroff410e3e22007-09-12 20:13:48 +0000569 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
570 if (!VDecl) {
571 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
572 RealDecl->setInvalidDecl();
573 return;
574 }
Steve Naroffbb204692007-09-12 14:07:44 +0000575 // Get the decls type and save a reference for later, since
576 // CheckInitializer may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000577 QualType DclT = VDecl->getType(), SavT = DclT;
578 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000579 VarDecl::StorageClass SC = BVD->getStorageClass();
580 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000581 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000582 BVD->setInvalidDecl();
583 } else if (!BVD->isInvalidDecl()) {
584 CheckInitializer(Init, DclT, SC == VarDecl::Static);
585 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000586 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000587 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000588 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000589 if (!FVD->isInvalidDecl())
590 CheckInitializer(Init, DclT, true);
591 }
592 // If the type changed, it means we had an incomplete type that was
593 // completed by the initializer. For example:
594 // int ary[] = { 1, 3, 5 };
595 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff410e3e22007-09-12 20:13:48 +0000596 if (!VDecl->isInvalidDecl() && (DclT != SavT))
597 VDecl->setType(DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000598
599 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000600 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000601 return;
602}
603
Reid Spencer5f016e22007-07-11 17:01:13 +0000604/// The declarators are chained together backwards, reverse the list.
605Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
606 // Often we have single declarators, handle them quickly.
607 Decl *Group = static_cast<Decl*>(group);
Steve Naroffbb204692007-09-12 14:07:44 +0000608 if (Group == 0)
609 return 0;
610
Reid Spencer5f016e22007-07-11 17:01:13 +0000611 Decl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000612 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000613 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000614 else { // reverse the list.
615 while (Group) {
616 Decl *Next = Group->getNextDeclarator();
617 Group->setNextDeclarator(NewGroup);
618 NewGroup = Group;
619 Group = Next;
620 }
621 }
622 // Perform semantic analysis that depends on having fully processed both
623 // the declarator and initializer.
624 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
625 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
626 if (!IDecl)
627 continue;
628 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
629 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
630 QualType T = IDecl->getType();
631
632 // C99 6.7.5.2p2: If an identifier is declared to be an object with
633 // static storage duration, it shall not have a variable length array.
634 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
635 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
636 if (VLA->getSizeExpr()) {
637 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
638 IDecl->setInvalidDecl();
639 }
640 }
641 }
642 // Block scope. C99 6.7p7: If an identifier for an object is declared with
643 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
644 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
645 if (T->isIncompleteType()) {
646 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
647 T.getAsString());
648 IDecl->setInvalidDecl();
649 }
650 }
651 // File scope. C99 6.9.2p2: A declaration of an identifier for and
652 // object that has file scope without an initializer, and without a
653 // storage-class specifier or with the storage-class specifier "static",
654 // constitutes a tentative definition. Note: A tentative definition with
655 // external linkage is valid (C99 6.2.2p5).
656 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
657 // C99 6.9.2p3: If the declaration of an identifier for an object is
658 // a tentative definition and has internal linkage (C99 6.2.2p3), the
659 // declared type shall not be an incomplete type.
660 if (T->isIncompleteType()) {
661 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
662 T.getAsString());
663 IDecl->setInvalidDecl();
664 }
665 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000666 }
667 return NewGroup;
668}
Steve Naroffe1223f72007-08-28 03:03:08 +0000669
670// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000671ParmVarDecl *
672Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
673 Scope *FnScope) {
674 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
675
676 IdentifierInfo *II = PI.Ident;
677 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
678 // Can this happen for params? We already checked that they don't conflict
679 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000680 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000681 PI.IdentLoc, FnScope)) {
682
683 }
684
685 // FIXME: Handle storage class (auto, register). No declarator?
686 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000687
688 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
689 // Doing the promotion here has a win and a loss. The win is the type for
690 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
691 // code generator). The loss is the orginal type isn't preserved. For example:
692 //
693 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
694 // int blockvardecl[5];
695 // sizeof(parmvardecl); // size == 4
696 // sizeof(blockvardecl); // size == 20
697 // }
698 //
699 // For expressions, all implicit conversions are captured using the
700 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
701 //
702 // FIXME: If a source translation tool needs to see the original type, then
703 // we need to consider storing both types (in ParmVarDecl)...
704 //
705 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
706 if (const ArrayType *AT = parmDeclType->getAsArrayType())
707 parmDeclType = Context.getPointerType(AT->getElementType());
708 else if (parmDeclType->isFunctionType())
709 parmDeclType = Context.getPointerType(parmDeclType);
710
711 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff53a32342007-08-28 18:45:29 +0000712 VarDecl::None, 0);
713 if (PI.InvalidType)
714 New->setInvalidDecl();
715
Reid Spencer5f016e22007-07-11 17:01:13 +0000716 // If this has an identifier, add it to the scope stack.
717 if (II) {
718 New->setNext(II->getFETokenInfo<Decl>());
719 II->setFETokenInfo(New);
720 FnScope->AddDecl(New);
721 }
722
723 return New;
724}
725
726
727Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
728 assert(CurFunctionDecl == 0 && "Function parsing confused");
729 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
730 "Not a function declarator!");
731 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
732
733 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
734 // for a K&R function.
735 if (!FTI.hasPrototype) {
736 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
737 if (FTI.ArgInfo[i].TypeInfo == 0) {
738 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
739 FTI.ArgInfo[i].Ident->getName());
740 // Implicitly declare the argument as type 'int' for lack of a better
741 // type.
742 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
743 }
744 }
745
746 // Since this is a function definition, act as though we have information
747 // about the arguments.
748 FTI.hasPrototype = true;
749 } else {
750 // FIXME: Diagnose arguments without names in C.
751
752 }
753
754 Scope *GlobalScope = FnBodyScope->getParent();
755
756 FunctionDecl *FD =
Steve Naroffbb204692007-09-12 14:07:44 +0000757 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000758 CurFunctionDecl = FD;
759
760 // Create Decl objects for each parameter, adding them to the FunctionDecl.
761 llvm::SmallVector<ParmVarDecl*, 16> Params;
762
763 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
764 // no arguments, not a function that takes a single void argument.
765 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
766 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
767 // empty arg list, don't push any params.
768 } else {
769 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
770 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
771 }
772
773 FD->setParams(&Params[0], Params.size());
774
775 return FD;
776}
777
778Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
779 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
780 FD->setBody((Stmt*)Body);
781
782 assert(FD == CurFunctionDecl && "Function parsing confused");
783 CurFunctionDecl = 0;
784
785 // Verify and clean out per-function state.
786
787 // Check goto/label use.
788 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
789 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
790 // Verify that we have no forward references left. If so, there was a goto
791 // or address of a label taken, but no definition of it. Label fwd
792 // definitions are indicated with a null substmt.
793 if (I->second->getSubStmt() == 0) {
794 LabelStmt *L = I->second;
795 // Emit error.
796 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
797
798 // At this point, we have gotos that use the bogus label. Stitch it into
799 // the function body so that they aren't leaked and that the AST is well
800 // formed.
801 L->setSubStmt(new NullStmt(L->getIdentLoc()));
802 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
803 }
804 }
805 LabelMap.clear();
806
807 return FD;
808}
809
810
811/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
812/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
813Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
814 Scope *S) {
815 if (getLangOptions().C99) // Extension in C99.
816 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
817 else // Legal in C90, but warn about it.
818 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
819
820 // FIXME: handle stuff like:
821 // void foo() { extern float X(); }
822 // void bar() { X(); } <-- implicit decl for X in another scope.
823
824 // Set a Declarator for the implicit definition: int foo();
825 const char *Dummy;
826 DeclSpec DS;
827 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
828 Error = Error; // Silence warning.
829 assert(!Error && "Error setting up implicit decl!");
830 Declarator D(DS, Declarator::BlockContext);
831 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
832 D.SetIdentifier(&II, Loc);
833
834 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000835 if (Scope *FnS = S->getFnParent())
836 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000837 while (S->getParent())
838 S = S->getParent();
839
Steve Naroffbb204692007-09-12 14:07:44 +0000840 return static_cast<Decl*>(ParseDeclarator(S, D, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000841}
842
843
844TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
845 Decl *LastDeclarator) {
846 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
847
848 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000849 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000850
851 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +0000852 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
853 T, LastDeclarator);
854 if (D.getInvalidType())
855 NewTD->setInvalidDecl();
856 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000857}
858
Steve Naroff3536b442007-09-06 21:24:23 +0000859Sema::DeclTy *Sema::ObjcStartClassInterface(SourceLocation AtInterfaceLoc,
860 IdentifierInfo *ClassName, SourceLocation ClassLoc,
861 IdentifierInfo *SuperName, SourceLocation SuperLoc,
862 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
863 AttributeList *AttrList) {
864 assert(ClassName && "Missing class identifier");
865 ObjcInterfaceDecl *IDecl;
866
867 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, ClassName);
868
869 // Chain & install the interface decl into the identifier.
870 IDecl->setNext(ClassName->getFETokenInfo<Decl>());
871 ClassName->setFETokenInfo(IDecl);
872 return IDecl;
873}
874
Steve Naroff44739212007-09-11 21:17:26 +0000875void Sema::ObjcAddInstanceVariable(DeclTy *ClassDecl, DeclTy *Ivar,
876 tok::ObjCKeywordKind visibility) {
877 assert((ClassDecl && Ivar) && "missing class or instance variable");
878 ObjcInterfaceDecl *OInterface = dyn_cast<ObjcInterfaceDecl>(
879 static_cast<Decl *>(ClassDecl));
880 ObjcIvarDecl *OIvar = dyn_cast<ObjcIvarDecl>(static_cast<Decl *>(Ivar));
881
882 assert((OInterface && OIvar) && "mistyped class or instance variable");
883
884 switch (visibility) {
885 case tok::objc_private:
886 OIvar->setAccessControl(ObjcIvarDecl::Private);
887 break;
888 case tok::objc_public:
889 OIvar->setAccessControl(ObjcIvarDecl::Public);
890 break;
891 case tok::objc_protected:
892 OIvar->setAccessControl(ObjcIvarDecl::Protected);
893 break;
894 case tok::objc_package:
895 OIvar->setAccessControl(ObjcIvarDecl::Package);
896 break;
897 default:
898 OIvar->setAccessControl(ObjcIvarDecl::None);
899 break;
900 }
901 // FIXME: add to the class...
902}
903
Steve Naroff3536b442007-09-06 21:24:23 +0000904/// ObjcClassDeclaration -
905/// Scope will always be top level file scope.
906Action::DeclTy *
907Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
908 IdentifierInfo **IdentList, unsigned NumElts) {
909 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
910
911 for (unsigned i = 0; i != NumElts; ++i) {
912 ObjcInterfaceDecl *IDecl;
913
Steve Naroff2bd42fa2007-09-10 20:51:04 +0000914 // FIXME: before we create one, look up the interface decl in a hash table.
Steve Naroff3536b442007-09-06 21:24:23 +0000915 IDecl = new ObjcInterfaceDecl(SourceLocation(), IdentList[i], true);
916 // Chain & install the interface decl into the identifier.
917 IDecl->setNext(IdentList[i]->getFETokenInfo<Decl>());
918 IdentList[i]->setFETokenInfo(IDecl);
919
920 // Remember that this needs to be removed when the scope is popped.
921 S->AddDecl(IdentList[i]);
922
923 CDecl->setInterfaceDecl((int)i, IDecl);
924 }
925 return CDecl;
926}
927
Reid Spencer5f016e22007-07-11 17:01:13 +0000928
929/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
930/// former case, Name will be non-null. In the later case, Name will be null.
931/// TagType indicates what kind of tag this is. TK indicates whether this is a
932/// reference/declaration/definition of a tag.
933Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
934 SourceLocation KWLoc, IdentifierInfo *Name,
935 SourceLocation NameLoc, AttributeList *Attr) {
936 // If this is a use of an existing tag, it must have a name.
937 assert((Name != 0 || TK == TK_Definition) &&
938 "Nameless record must be a definition!");
939
940 Decl::Kind Kind;
941 switch (TagType) {
942 default: assert(0 && "Unknown tag type!");
943 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
944 case DeclSpec::TST_union: Kind = Decl::Union; break;
945//case DeclSpec::TST_class: Kind = Decl::Class; break;
946 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
947 }
948
949 // If this is a named struct, check to see if there was a previous forward
950 // declaration or definition.
951 if (TagDecl *PrevDecl =
952 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
953 NameLoc, S))) {
954
955 // If this is a use of a previous tag, or if the tag is already declared in
956 // the same scope (so that the definition/declaration completes or
957 // rementions the tag), reuse the decl.
958 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
959 // Make sure that this wasn't declared as an enum and now used as a struct
960 // or something similar.
961 if (PrevDecl->getKind() != Kind) {
962 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
963 Diag(PrevDecl->getLocation(), diag::err_previous_use);
964 }
965
966 // If this is a use or a forward declaration, we're good.
967 if (TK != TK_Definition)
968 return PrevDecl;
969
970 // Diagnose attempts to redefine a tag.
971 if (PrevDecl->isDefinition()) {
972 Diag(NameLoc, diag::err_redefinition, Name->getName());
973 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
974 // If this is a redefinition, recover by making this struct be
975 // anonymous, which will make any later references get the previous
976 // definition.
977 Name = 0;
978 } else {
979 // Okay, this is definition of a previously declared or referenced tag.
980 // Move the location of the decl to be the definition site.
981 PrevDecl->setLocation(NameLoc);
982 return PrevDecl;
983 }
984 }
985 // If we get here, this is a definition of a new struct type in a nested
986 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
987 // type.
988 }
989
990 // If there is an identifier, use the location of the identifier as the
991 // location of the decl, otherwise use the location of the struct/union
992 // keyword.
993 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
994
995 // Otherwise, if this is the first time we've seen this tag, create the decl.
996 TagDecl *New;
997 switch (Kind) {
998 default: assert(0 && "Unknown tag kind!");
999 case Decl::Enum:
1000 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1001 // enum X { A, B, C } D; D should chain to X.
1002 New = new EnumDecl(Loc, Name, 0);
1003 // If this is an undefined enum, warn.
1004 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1005 break;
1006 case Decl::Union:
1007 case Decl::Struct:
1008 case Decl::Class:
1009 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1010 // struct X { int A; } D; D should chain to X.
1011 New = new RecordDecl(Kind, Loc, Name, 0);
1012 break;
1013 }
1014
1015 // If this has an identifier, add it to the scope stack.
1016 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001017 // The scope passed in may not be a decl scope. Zip up the scope tree until
1018 // we find one that is.
1019 while ((S->getFlags() & Scope::DeclScope) == 0)
1020 S = S->getParent();
1021
1022 // Add it to the decl chain.
Reid Spencer5f016e22007-07-11 17:01:13 +00001023 New->setNext(Name->getFETokenInfo<Decl>());
1024 Name->setFETokenInfo(New);
1025 S->AddDecl(New);
1026 }
1027
1028 return New;
1029}
1030
1031/// ParseField - Each field of a struct/union/class is passed into this in order
1032/// to create a FieldDecl object for it.
1033Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
1034 SourceLocation DeclStart,
1035 Declarator &D, ExprTy *BitfieldWidth) {
1036 IdentifierInfo *II = D.getIdentifier();
1037 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001038 SourceLocation Loc = DeclStart;
1039 if (II) Loc = D.getIdentifierLoc();
1040
1041 // FIXME: Unnamed fields can be handled in various different ways, for
1042 // example, unnamed unions inject all members into the struct namespace!
1043
1044
1045 if (BitWidth) {
1046 // TODO: Validate.
1047 //printf("WARNING: BITFIELDS IGNORED!\n");
1048
1049 // 6.7.2.1p3
1050 // 6.7.2.1p4
1051
1052 } else {
1053 // Not a bitfield.
1054
1055 // validate II.
1056
1057 }
1058
1059 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001060 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1061 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001062
Reid Spencer5f016e22007-07-11 17:01:13 +00001063 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1064 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001065 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1066 Diag(Loc, diag::err_typecheck_illegal_vla,
1067 VAT->getSizeExpr()->getSourceRange());
1068 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001069 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001071 FieldDecl *NewFD;
1072
1073 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
1074 NewFD = new FieldDecl(Loc, II, T, 0);
1075 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl)))
1076 NewFD = new ObjcIvarDecl(Loc, II, T, 0);
1077 else
1078 assert(0 && "Sema::ParseField(): Unknown TagDecl");
1079
Steve Naroff5912a352007-08-28 20:14:24 +00001080 if (D.getInvalidType() || InvalidDecl)
1081 NewFD->setInvalidDecl();
1082 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001083}
1084
1085void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
1086 DeclTy **Fields, unsigned NumFields) {
1087 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
1088 if (Record->isDefinition()) {
1089 // Diagnose code like:
1090 // struct S { struct S {} X; };
1091 // We discover this when we complete the outer S. Reject and ignore the
1092 // outer S.
1093 Diag(Record->getLocation(), diag::err_nested_redefinition,
1094 Record->getKindName());
1095 Diag(RecLoc, diag::err_previous_definition);
1096 return;
1097 }
1098
1099 // Verify that all the fields are okay.
1100 unsigned NumNamedMembers = 0;
1101 llvm::SmallVector<FieldDecl*, 32> RecFields;
1102 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
1103
1104 for (unsigned i = 0; i != NumFields; ++i) {
1105 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1106 if (!FD) continue; // Already issued a diagnostic.
1107
1108 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001109 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001110
1111 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001112 if (FDTy->isFunctionType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001113 Diag(FD->getLocation(), diag::err_field_declared_as_function,
1114 FD->getName());
1115 delete FD;
1116 continue;
1117 }
1118
1119 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1120 if (FDTy->isIncompleteType()) {
1121 if (i != NumFields-1 || // ... that the last member ...
1122 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001123 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001124 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1125 delete FD;
1126 continue;
1127 }
1128 if (NumNamedMembers < 1) { //... must have more than named member ...
1129 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1130 FD->getName());
1131 delete FD;
1132 continue;
1133 }
1134
1135 // Okay, we have a legal flexible array member at the end of the struct.
1136 Record->setHasFlexibleArrayMember(true);
1137 }
1138
1139
1140 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1141 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001142 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1144 // If this is a member of a union, then entire union becomes "flexible".
1145 if (Record->getKind() == Decl::Union) {
1146 Record->setHasFlexibleArrayMember(true);
1147 } else {
1148 // If this is a struct/class and this is not the last element, reject
1149 // it. Note that GCC supports variable sized arrays in the middle of
1150 // structures.
1151 if (i != NumFields-1) {
1152 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1153 FD->getName());
1154 delete FD;
1155 continue;
1156 }
1157
1158 // We support flexible arrays at the end of structs in other structs
1159 // as an extension.
1160 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1161 FD->getName());
1162 Record->setHasFlexibleArrayMember(true);
1163 }
1164 }
1165 }
1166
1167 // Keep track of the number of named members.
1168 if (IdentifierInfo *II = FD->getIdentifier()) {
1169 // Detect duplicate member names.
1170 if (!FieldIDs.insert(II)) {
1171 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1172 // Find the previous decl.
1173 SourceLocation PrevLoc;
1174 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1175 assert(i != e && "Didn't find previous def!");
1176 if (RecFields[i]->getIdentifier() == II) {
1177 PrevLoc = RecFields[i]->getLocation();
1178 break;
1179 }
1180 }
1181 Diag(PrevLoc, diag::err_previous_definition);
1182 delete FD;
1183 continue;
1184 }
1185 ++NumNamedMembers;
1186 }
1187
1188 // Remember good fields.
1189 RecFields.push_back(FD);
1190 }
1191
1192
1193 // Okay, we successfully defined 'Record'.
1194 Record->defineBody(&RecFields[0], RecFields.size());
1195}
1196
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001197void Sema::ObjcAddMethodsToClass(DeclTy *ClassDecl,
1198 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001199 // FIXME: Fix this when we can handle methods declared in protocols.
1200 // See Parser::ParseObjCAtProtocolDeclaration
1201 if (!ClassDecl)
1202 return;
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001203 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1204 static_cast<Decl*>(ClassDecl));
1205 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1206 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1207
1208 for (unsigned i = 0; i < allNum; i++ ) {
1209 ObjcMethodDecl *Method =
1210 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1211 if (!Method) continue; // Already issued a diagnostic.
1212 if (Method->isInstance())
1213 insMethods.push_back(Method);
1214 else
1215 clsMethods.push_back(Method);
1216 }
1217 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1218 &clsMethods[0], clsMethods.size());
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001219 return;
1220}
1221
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001222Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
1223 tok::TokenKind MethodType, TypeTy *ReturnType,
1224 ObjcKeywordInfo *Keywords, unsigned NumKeywords,
1225 AttributeList *AttrList) {
1226 assert(NumKeywords && "Selector must be specified");
1227 // FIXME: SelectorName to be changed to comform to objc's abi for method names
1228 IdentifierInfo *SelectorName = Keywords[0].SelectorName;
1229 llvm::SmallVector<ParmVarDecl*, 16> Params;
1230
1231 for (unsigned i = 0; i < NumKeywords; i++) {
1232 ObjcKeywordInfo *arg = &Keywords[i];
1233 // FIXME: arg->AttrList must be stored too!
1234 ParmVarDecl* Param = new ParmVarDecl(arg->ColonLoc, arg->ArgumentName,
1235 QualType::getFromOpaquePtr(arg->TypeInfo),
1236 VarDecl::None, 0);
1237 // FIXME: 'InvalidType' does not get set by caller yet.
1238 if (arg->InvalidType)
1239 Param->setInvalidDecl();
1240 Params.push_back(Param);
1241 }
1242 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
1243 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc,
1244 SelectorName, resultDeclType,
1245 0, -1, AttrList, MethodType == tok::minus);
1246 ObjcMethod->setMethodParams(&Params[0], NumKeywords);
1247 return ObjcMethod;
1248}
1249
1250Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
1251 tok::TokenKind MethodType, TypeTy *ReturnType,
1252 IdentifierInfo *SelectorName, AttributeList *AttrList) {
1253 // FIXME: SelectorName to be changed to comform to objc's abi for method names
1254 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
1255 return new ObjcMethodDecl(MethodLoc, SelectorName, resultDeclType, 0, -1,
1256 AttrList, MethodType == tok::minus);
1257}
1258
Reid Spencer5f016e22007-07-11 17:01:13 +00001259Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
1260 DeclTy *lastEnumConst,
1261 SourceLocation IdLoc, IdentifierInfo *Id,
1262 SourceLocation EqualLoc, ExprTy *val) {
1263 theEnumDecl = theEnumDecl; // silence unused warning.
1264 EnumConstantDecl *LastEnumConst =
1265 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1266 Expr *Val = static_cast<Expr*>(val);
1267
Chris Lattner31e05722007-08-26 06:24:45 +00001268 // The scope passed in may not be a decl scope. Zip up the scope tree until
1269 // we find one that is.
1270 while ((S->getFlags() & Scope::DeclScope) == 0)
1271 S = S->getParent();
1272
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 // Verify that there isn't already something declared with this name in this
1274 // scope.
1275 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
1276 if (S->isDeclScope(PrevDecl)) {
1277 if (isa<EnumConstantDecl>(PrevDecl))
1278 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1279 else
1280 Diag(IdLoc, diag::err_redefinition, Id->getName());
1281 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1282 // FIXME: Don't leak memory: delete Val;
1283 return 0;
1284 }
1285 }
1286
1287 llvm::APSInt EnumVal(32);
1288 QualType EltTy;
1289 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001290 // Make sure to promote the operand type to int.
1291 UsualUnaryConversions(Val);
1292
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1294 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001295 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1297 Id->getName());
1298 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001299 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001300 } else {
1301 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001303 }
1304
1305 if (!Val) {
1306 if (LastEnumConst) {
1307 // Assign the last value + 1.
1308 EnumVal = LastEnumConst->getInitVal();
1309 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001310
1311 // Check for overflow on increment.
1312 if (EnumVal < LastEnumConst->getInitVal())
1313 Diag(IdLoc, diag::warn_enum_value_overflow);
1314
Chris Lattnerb7416f92007-08-27 17:37:24 +00001315 EltTy = LastEnumConst->getType();
1316 } else {
1317 // First value, set to zero.
1318 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001319 EnumVal.zextOrTrunc(
1320 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001321 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001322 }
1323
Reid Spencer5f016e22007-07-11 17:01:13 +00001324 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1325 LastEnumConst);
1326
1327 // Register this decl in the current scope stack.
1328 New->setNext(Id->getFETokenInfo<Decl>());
1329 Id->setFETokenInfo(New);
1330 S->AddDecl(New);
1331 return New;
1332}
1333
1334void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1335 DeclTy **Elements, unsigned NumElements) {
1336 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1337 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1338
Chris Lattnere37f0be2007-08-28 05:10:31 +00001339 // TODO: If the result value doesn't fit in an int, it must be a long or long
1340 // long value. ISO C does not support this, but GCC does as an extension,
1341 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001342 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001343
1344
Chris Lattnerac609682007-08-28 06:15:15 +00001345 // Verify that all the values are okay, compute the size of the values, and
1346 // reverse the list.
1347 unsigned NumNegativeBits = 0;
1348 unsigned NumPositiveBits = 0;
1349
1350 // Keep track of whether all elements have type int.
1351 bool AllElementsInt = true;
1352
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 EnumConstantDecl *EltList = 0;
1354 for (unsigned i = 0; i != NumElements; ++i) {
1355 EnumConstantDecl *ECD =
1356 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1357 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001358
1359 // If the enum value doesn't fit in an int, emit an extension warning.
1360 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1361 "Should have promoted value to int");
1362 const llvm::APSInt &InitVal = ECD->getInitVal();
1363 if (InitVal.getBitWidth() > IntWidth) {
1364 llvm::APSInt V(InitVal);
1365 V.trunc(IntWidth);
1366 V.extend(InitVal.getBitWidth());
1367 if (V != InitVal)
1368 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1369 InitVal.toString());
1370 }
Chris Lattnerac609682007-08-28 06:15:15 +00001371
1372 // Keep track of the size of positive and negative values.
1373 if (InitVal.isUnsigned() || !InitVal.isNegative())
1374 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1375 else
1376 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001377
Chris Lattnerac609682007-08-28 06:15:15 +00001378 // Keep track of whether every enum element has type int (very commmon).
1379 if (AllElementsInt)
1380 AllElementsInt = ECD->getType() == Context.IntTy;
1381
Reid Spencer5f016e22007-07-11 17:01:13 +00001382 ECD->setNextDeclarator(EltList);
1383 EltList = ECD;
1384 }
1385
Chris Lattnerac609682007-08-28 06:15:15 +00001386 // Figure out the type that should be used for this enum.
1387 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1388 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001389 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001390
1391 if (NumNegativeBits) {
1392 // If there is a negative value, figure out the smallest integer type (of
1393 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001394 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001395 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001396 BestWidth = IntWidth;
1397 } else {
1398 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1399 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001400 BestType = Context.LongTy;
1401 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001402 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1403 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001404 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1405 BestType = Context.LongLongTy;
1406 }
1407 }
1408 } else {
1409 // If there is no negative value, figure out which of uint, ulong, ulonglong
1410 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001411 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001412 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001413 BestWidth = IntWidth;
1414 } else if (NumPositiveBits <=
1415 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001416 BestType = Context.UnsignedLongTy;
1417 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001418 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1419 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001420 "How could an initializer get larger than ULL?");
1421 BestType = Context.UnsignedLongLongTy;
1422 }
1423 }
1424
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001425 // Loop over all of the enumerator constants, changing their types to match
1426 // the type of the enum if needed.
1427 for (unsigned i = 0; i != NumElements; ++i) {
1428 EnumConstantDecl *ECD =
1429 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1430 if (!ECD) continue; // Already issued a diagnostic.
1431
1432 // Standard C says the enumerators have int type, but we allow, as an
1433 // extension, the enumerators to be larger than int size. If each
1434 // enumerator value fits in an int, type it as an int, otherwise type it the
1435 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1436 // that X has type 'int', not 'unsigned'.
1437 if (ECD->getType() == Context.IntTy)
1438 continue; // Already int type.
1439
1440 // Determine whether the value fits into an int.
1441 llvm::APSInt InitVal = ECD->getInitVal();
1442 bool FitsInInt;
1443 if (InitVal.isUnsigned() || !InitVal.isNegative())
1444 FitsInInt = InitVal.getActiveBits() < IntWidth;
1445 else
1446 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1447
1448 // If it fits into an integer type, force it. Otherwise force it to match
1449 // the enum decl type.
1450 QualType NewTy;
1451 unsigned NewWidth;
1452 bool NewSign;
1453 if (FitsInInt) {
1454 NewTy = Context.IntTy;
1455 NewWidth = IntWidth;
1456 NewSign = true;
1457 } else if (ECD->getType() == BestType) {
1458 // Already the right type!
1459 continue;
1460 } else {
1461 NewTy = BestType;
1462 NewWidth = BestWidth;
1463 NewSign = BestType->isSignedIntegerType();
1464 }
1465
1466 // Adjust the APSInt value.
1467 InitVal.extOrTrunc(NewWidth);
1468 InitVal.setIsSigned(NewSign);
1469 ECD->setInitVal(InitVal);
1470
1471 // Adjust the Expr initializer and type.
1472 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1473 ECD->setType(NewTy);
1474 }
Chris Lattnerac609682007-08-28 06:15:15 +00001475
Chris Lattnere00b18c2007-08-28 18:24:31 +00001476 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001477}
1478
1479void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1480 if (!current) return;
1481
1482 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1483 // remember this in the LastInGroupList list.
1484 if (last)
1485 LastInGroupList.push_back((Decl*)last);
1486}
1487
1488void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1489 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1490 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1491 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1492 if (!newType.isNull()) // install the new vector type into the decl
1493 vDecl->setType(newType);
1494 }
1495 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1496 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1497 rawAttr);
1498 if (!newType.isNull()) // install the new vector type into the decl
1499 tDecl->setUnderlyingType(newType);
1500 }
1501 }
Steve Naroff73322922007-07-18 18:00:27 +00001502 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001503 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1504 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1505 else
Steve Naroff73322922007-07-18 18:00:27 +00001506 Diag(rawAttr->getAttributeLoc(),
1507 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00001508 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 // FIXME: add other attributes...
1510}
1511
1512void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1513 AttributeList *declarator_postfix) {
1514 while (declspec_prefix) {
1515 HandleDeclAttribute(New, declspec_prefix);
1516 declspec_prefix = declspec_prefix->getNext();
1517 }
1518 while (declarator_postfix) {
1519 HandleDeclAttribute(New, declarator_postfix);
1520 declarator_postfix = declarator_postfix->getNext();
1521 }
1522}
1523
Steve Naroffbea0b342007-07-29 16:33:31 +00001524void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1525 AttributeList *rawAttr) {
1526 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00001527 // check the attribute arugments.
1528 if (rawAttr->getNumArgs() != 1) {
1529 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1530 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001531 return;
Steve Naroff73322922007-07-18 18:00:27 +00001532 }
1533 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1534 llvm::APSInt vecSize(32);
1535 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1536 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1537 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001538 return;
Steve Naroff73322922007-07-18 18:00:27 +00001539 }
1540 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1541 // in conjunction with complex types (pointers, arrays, functions, etc.).
1542 Type *canonType = curType.getCanonicalType().getTypePtr();
1543 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1544 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1545 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001546 return;
Steve Naroff73322922007-07-18 18:00:27 +00001547 }
1548 // unlike gcc's vector_size attribute, the size is specified as the
1549 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001550 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001551
1552 if (vectorSize == 0) {
1553 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1554 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001555 return;
Steve Naroff73322922007-07-18 18:00:27 +00001556 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001557 // Instantiate/Install the vector type, the number of elements is > 0.
1558 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1559 // Remember this typedef decl, we will need it later for diagnostics.
1560 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001561}
1562
Reid Spencer5f016e22007-07-11 17:01:13 +00001563QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001564 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 // check the attribute arugments.
1566 if (rawAttr->getNumArgs() != 1) {
1567 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1568 std::string("1"));
1569 return QualType();
1570 }
1571 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1572 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001573 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1575 sizeExpr->getSourceRange());
1576 return QualType();
1577 }
1578 // navigate to the base type - we need to provide for vector pointers,
1579 // vector arrays, and functions returning vectors.
1580 Type *canonType = curType.getCanonicalType().getTypePtr();
1581
Steve Naroff73322922007-07-18 18:00:27 +00001582 if (canonType->isPointerType() || canonType->isArrayType() ||
1583 canonType->isFunctionType()) {
1584 assert(1 && "HandleVector(): Complex type construction unimplemented");
1585 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1586 do {
1587 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1588 canonType = PT->getPointeeType().getTypePtr();
1589 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1590 canonType = AT->getElementType().getTypePtr();
1591 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1592 canonType = FT->getResultType().getTypePtr();
1593 } while (canonType->isPointerType() || canonType->isArrayType() ||
1594 canonType->isFunctionType());
1595 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 }
1597 // the base type must be integer or float.
1598 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1599 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1600 curType.getCanonicalType().getAsString());
1601 return QualType();
1602 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00001603 unsigned typeSize = static_cast<unsigned>(
1604 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001605 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001606 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00001607
1608 // the vector size needs to be an integral multiple of the type size.
1609 if (vectorSize % typeSize) {
1610 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1611 sizeExpr->getSourceRange());
1612 return QualType();
1613 }
1614 if (vectorSize == 0) {
1615 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1616 sizeExpr->getSourceRange());
1617 return QualType();
1618 }
1619 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1620 // the number of elements to be a power of two (unlike GCC).
1621 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00001622 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001623}
1624