blob: 71fc0b44710678ebb9366d9da5b7560a35fcc546 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Builtins.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/Type.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Parse/Scope.h"
22#include "clang/Lex/IdentifierTable.h"
23#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
25#include "llvm/ADT/SmallSet.h"
26using namespace clang;
27
Chris Lattner4b009652007-07-25 00:24:17 +000028Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Steve Naroff81f1bba2007-09-06 21:24:23 +000029 Decl *IIDecl = II.getFETokenInfo<Decl>();
30 if (dyn_cast_or_null<TypedefDecl>(IIDecl) ||
31 dyn_cast_or_null<ObjcInterfaceDecl>(IIDecl))
32 return IIDecl;
33 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000034}
35
36void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000037 if (S->decl_empty()) return;
38 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
39
Chris Lattner4b009652007-07-25 00:24:17 +000040 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
41 I != E; ++I) {
42 Decl *D = static_cast<Decl*>(*I);
43 assert(D && "This decl didn't get pushed??");
44 IdentifierInfo *II = D->getIdentifier();
45 if (!II) continue;
46
47 // Unlink this decl from the identifier. Because the scope contains decls
48 // in an unordered collection, and because we have multiple identifier
49 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
50 if (II->getFETokenInfo<Decl>() == D) {
51 // Normal case, no multiple decls in different namespaces.
52 II->setFETokenInfo(D->getNext());
53 } else {
54 // Scan ahead. There are only three namespaces in C, so this loop can
55 // never execute more than 3 times.
56 Decl *SomeDecl = II->getFETokenInfo<Decl>();
57 while (SomeDecl->getNext() != D) {
58 SomeDecl = SomeDecl->getNext();
59 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
60 }
61 SomeDecl->setNext(D->getNext());
62 }
63
64 // This will have to be revisited for C++: there we want to nest stuff in
65 // namespace decls etc. Even for C, we might want a top-level translation
66 // unit decl or something.
67 if (!CurFunctionDecl)
68 continue;
69
70 // Chain this decl to the containing function, it now owns the memory for
71 // the decl.
72 D->setNext(CurFunctionDecl->getDeclChain());
73 CurFunctionDecl->setDeclChain(D);
74 }
75}
76
77/// LookupScopedDecl - Look up the inner-most declaration in the specified
78/// namespace.
79Decl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
80 SourceLocation IdLoc, Scope *S) {
81 if (II == 0) return 0;
82 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
83
84 // Scan up the scope chain looking for a decl that matches this identifier
85 // that is in the appropriate namespace. This search should not take long, as
86 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
87 for (Decl *D = II->getFETokenInfo<Decl>(); D; D = D->getNext())
88 if (D->getIdentifierNamespace() == NS)
89 return D;
90
91 // If we didn't find a use of this identifier, and if the identifier
92 // corresponds to a compiler builtin, create the decl object for the builtin
93 // now, injecting it into translation unit scope, and return it.
94 if (NS == Decl::IDNS_Ordinary) {
95 // If this is a builtin on some other target, or if this builtin varies
96 // across targets (e.g. in type), emit a diagnostic and mark the translation
97 // unit non-portable for using it.
98 if (II->isNonPortableBuiltin()) {
99 // Only emit this diagnostic once for this builtin.
100 II->setNonPortableBuiltin(false);
101 Context.Target.DiagnoseNonPortability(IdLoc,
102 diag::port_target_builtin_use);
103 }
104 // If this is a builtin on this (or all) targets, create the decl.
105 if (unsigned BuiltinID = II->getBuiltinID())
106 return LazilyCreateBuiltin(II, BuiltinID, S);
107 }
108 return 0;
109}
110
111/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
112/// lazily create a decl for it.
113Decl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
114 Builtin::ID BID = (Builtin::ID)bid;
115
116 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
117 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner987058a2007-08-26 04:02:13 +0000118 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000119
120 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000121 if (Scope *FnS = S->getFnParent())
122 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000123 while (S->getParent())
124 S = S->getParent();
125 S->AddDecl(New);
126
127 // Add this decl to the end of the identifier info.
128 if (Decl *LastDecl = II->getFETokenInfo<Decl>()) {
129 // Scan until we find the last (outermost) decl in the id chain.
130 while (LastDecl->getNext())
131 LastDecl = LastDecl->getNext();
132 // Insert before (outside) it.
133 LastDecl->setNext(New);
134 } else {
135 II->setFETokenInfo(New);
136 }
137 // Make sure clients iterating over decls see this.
138 LastInGroupList.push_back(New);
139
140 return New;
141}
142
143/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
144/// and scope as a previous declaration 'Old'. Figure out how to resolve this
145/// situation, merging decls or emitting diagnostics as appropriate.
146///
147TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
148 // Verify the old decl was also a typedef.
149 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
150 if (!Old) {
151 Diag(New->getLocation(), diag::err_redefinition_different_kind,
152 New->getName());
153 Diag(OldD->getLocation(), diag::err_previous_definition);
154 return New;
155 }
156
157 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
158 // TODO: This is totally simplistic. It should handle merging functions
159 // together etc, merging extern int X; int X; ...
160 Diag(New->getLocation(), diag::err_redefinition, New->getName());
161 Diag(Old->getLocation(), diag::err_previous_definition);
162 return New;
163}
164
165/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
166/// and scope as a previous declaration 'Old'. Figure out how to resolve this
167/// situation, merging decls or emitting diagnostics as appropriate.
168///
169FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
170 // Verify the old decl was also a function.
171 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
172 if (!Old) {
173 Diag(New->getLocation(), diag::err_redefinition_different_kind,
174 New->getName());
175 Diag(OldD->getLocation(), diag::err_previous_definition);
176 return New;
177 }
178
179 // This is not right, but it's a start. If 'Old' is a function prototype with
180 // the same type as 'New', silently allow this. FIXME: We should link up decl
181 // objects here.
182 if (Old->getBody() == 0 &&
183 Old->getCanonicalType() == New->getCanonicalType()) {
184 return New;
185 }
186
187 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
188 // TODO: This is totally simplistic. It should handle merging functions
189 // together etc, merging extern int X; int X; ...
190 Diag(New->getLocation(), diag::err_redefinition, New->getName());
191 Diag(Old->getLocation(), diag::err_previous_definition);
192 return New;
193}
194
195/// MergeVarDecl - We just parsed a variable 'New' which has the same name
196/// and scope as a previous declaration 'Old'. Figure out how to resolve this
197/// situation, merging decls or emitting diagnostics as appropriate.
198///
199/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
200/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
201///
202VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
203 // Verify the old decl was also a variable.
204 VarDecl *Old = dyn_cast<VarDecl>(OldD);
205 if (!Old) {
206 Diag(New->getLocation(), diag::err_redefinition_different_kind,
207 New->getName());
208 Diag(OldD->getLocation(), diag::err_previous_definition);
209 return New;
210 }
Steve Naroff83c13012007-08-30 01:06:46 +0000211 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
212 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
213 bool OldIsTentative = false;
214
215 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
216 // Handle C "tentative" external object definitions. FIXME: finish!
217 if (!OldFSDecl->getInit() &&
218 (OldFSDecl->getStorageClass() == VarDecl::None ||
219 OldFSDecl->getStorageClass() == VarDecl::Static))
220 OldIsTentative = true;
221 }
Chris Lattner4b009652007-07-25 00:24:17 +0000222 // Verify the types match.
223 if (Old->getCanonicalType() != New->getCanonicalType()) {
224 Diag(New->getLocation(), diag::err_redefinition, New->getName());
225 Diag(Old->getLocation(), diag::err_previous_definition);
226 return New;
227 }
228 // We've verified the types match, now check if Old is "extern".
229 if (Old->getStorageClass() != VarDecl::Extern) {
230 Diag(New->getLocation(), diag::err_redefinition, New->getName());
231 Diag(Old->getLocation(), diag::err_previous_definition);
232 }
233 return New;
234}
235
236/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
237/// no declarator (e.g. "struct foo;") is parsed.
238Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
239 // TODO: emit error on 'int;' or 'const enum foo;'.
240 // TODO: emit error on 'typedef int;'
241 // if (!DS.isMissingDeclaratorOk()) Diag(...);
242
243 return 0;
244}
245
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000246bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000247 AssignmentCheckResult result;
248 SourceLocation loc = Init->getLocStart();
249 // Get the type before calling CheckSingleAssignmentConstraints(), since
250 // it can promote the expression.
251 QualType rhsType = Init->getType();
252
253 result = CheckSingleAssignmentConstraints(DeclType, Init);
254
255 // decode the result (notice that extensions still return a type).
256 switch (result) {
257 case Compatible:
258 break;
259 case Incompatible:
Steve Naroff9091f3f2007-09-02 15:34:30 +0000260 // FIXME: tighten up this check which should allow:
261 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
262 if (rhsType == Context.getPointerType(Context.CharTy))
263 break;
Steve Naroffe14e5542007-09-02 02:04:30 +0000264 Diag(loc, diag::err_typecheck_assign_incompatible,
265 DeclType.getAsString(), rhsType.getAsString(),
266 Init->getSourceRange());
267 return true;
268 case PointerFromInt:
269 // check for null pointer constant (C99 6.3.2.3p3)
270 if (!Init->isNullPointerConstant(Context)) {
271 Diag(loc, diag::ext_typecheck_assign_pointer_int,
272 DeclType.getAsString(), rhsType.getAsString(),
273 Init->getSourceRange());
274 return true;
275 }
276 break;
277 case IntFromPointer:
278 Diag(loc, diag::ext_typecheck_assign_pointer_int,
279 DeclType.getAsString(), rhsType.getAsString(),
280 Init->getSourceRange());
281 break;
282 case IncompatiblePointer:
283 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
284 DeclType.getAsString(), rhsType.getAsString(),
285 Init->getSourceRange());
286 break;
287 case CompatiblePointerDiscardsQualifiers:
288 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
289 DeclType.getAsString(), rhsType.getAsString(),
290 Init->getSourceRange());
291 break;
292 }
293 return false;
294}
295
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000296bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
297 bool isStatic, QualType ElementType) {
Steve Naroff509d0b52007-09-04 02:20:04 +0000298 SourceLocation loc;
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000299 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff509d0b52007-09-04 02:20:04 +0000300
301 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
302 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
303 return true;
304 } else if (CheckSingleInitializer(expr, ElementType)) {
305 return true; // types weren't compatible.
306 }
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000307 if (savExpr != expr) // The type was promoted, update initializer list.
308 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000309 return false;
310}
311
312void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
313 QualType ElementType, bool isStatic,
314 int &nInitializers, bool &hadError) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000315 for (unsigned i = 0; i < IList->getNumInits(); i++) {
316 Expr *expr = IList->getInit(i);
317
Steve Naroff509d0b52007-09-04 02:20:04 +0000318 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
319 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000320 int maxElements = CAT->getMaximumElements();
Steve Naroff509d0b52007-09-04 02:20:04 +0000321 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
322 maxElements, hadError);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000323 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000324 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000325 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000326 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000327 nInitializers++;
328 }
329 return;
330}
331
332// FIXME: Doesn't deal with arrays of structures yet.
333void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
334 QualType ElementType, bool isStatic,
335 int &totalInits, bool &hadError) {
336 int maxElementsAtThisLevel = 0;
337 int nInitsAtLevel = 0;
338
339 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
340 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff4f910992007-09-04 21:13:33 +0000341 maxElementsAtThisLevel = CAT->getMaximumElements();
342 // Set DeclType, used below to recurse (for multi-dimensional arrays).
343 DeclType = CAT->getElementType();
Steve Naroff509d0b52007-09-04 02:20:04 +0000344 } else if (DeclType->isScalarType()) {
345 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
346 IList->getSourceRange());
347 maxElementsAtThisLevel = 1;
348 }
349 // The empty init list "{ }" is treated specially below.
350 unsigned numInits = IList->getNumInits();
351 if (numInits) {
352 for (unsigned i = 0; i < numInits; i++) {
353 Expr *expr = IList->getInit(i);
354
355 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
356 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
357 totalInits, hadError);
358 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000359 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff509d0b52007-09-04 02:20:04 +0000360 nInitsAtLevel++; // increment the number of initializers at this level.
361 totalInits--; // decrement the total number of initializers.
362
363 // Check if we have space for another initializer.
364 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
365 Diag(expr->getLocStart(), diag::warn_excess_initializers,
366 expr->getSourceRange());
367 }
368 }
369 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
370 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
371 } else {
372 // we have an initializer list with no elements.
373 totalInits -= maxElementsAtThisLevel;
374 if (totalInits < 0)
375 Diag(IList->getLocStart(), diag::warn_excess_initializers,
376 IList->getSourceRange());
Steve Naroff9091f3f2007-09-02 15:34:30 +0000377 }
Steve Naroff1c9de712007-09-03 01:24:23 +0000378 return;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000379}
380
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000381bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000382 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroff1c9de712007-09-03 01:24:23 +0000383 if (!InitList)
384 return CheckSingleInitializer(Init, DeclType);
385
Steve Naroffe14e5542007-09-02 02:04:30 +0000386 // We have an InitListExpr, make sure we set the type.
387 Init->setType(DeclType);
Steve Naroff1c9de712007-09-03 01:24:23 +0000388
389 bool hadError = false;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000390
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000391 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
392 // of unknown size ("[]") or an object type that is not a variable array type.
393 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
394 Expr *expr = VAT->getSizeExpr();
Steve Naroff1c9de712007-09-03 01:24:23 +0000395 if (expr)
396 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
397 expr->getSourceRange());
398
Steve Naroff4f910992007-09-04 21:13:33 +0000399 // We have a VariableArrayType with unknown size. Note that only the first
400 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff509d0b52007-09-04 02:20:04 +0000401 int numInits = 0;
Steve Naroff4f910992007-09-04 21:13:33 +0000402 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
403 isStatic, numInits, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000404 if (!hadError) {
405 // Return a new array type from the number of initializers (C99 6.7.8p22).
406 llvm::APSInt ConstVal(32);
Steve Naroff509d0b52007-09-04 02:20:04 +0000407 ConstVal = numInits;
408 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroff1c9de712007-09-03 01:24:23 +0000409 ArrayType::Normal, 0);
410 }
411 return hadError;
412 }
413 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000414 int maxElements = CAT->getMaximumElements();
415 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
416 isStatic, maxElements, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000417 return hadError;
418 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000419 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
420 int maxElements = 1;
421 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
422 hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000423 return hadError;
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000424 }
425 // FIXME: Handle struct/union types.
Steve Naroff1c9de712007-09-03 01:24:23 +0000426 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +0000427}
428
Chris Lattner4b009652007-07-25 00:24:17 +0000429Sema::DeclTy *
430Sema::ParseDeclarator(Scope *S, Declarator &D, ExprTy *init,
431 DeclTy *lastDeclarator) {
432 Decl *LastDeclarator = (Decl*)lastDeclarator;
433 Expr *Init = static_cast<Expr*>(init);
434 IdentifierInfo *II = D.getIdentifier();
435
436 // All of these full declarators require an identifier. If it doesn't have
437 // one, the ParsedFreeStandingDeclSpec action should be used.
438 if (II == 0) {
Chris Lattner87492f42007-08-28 06:17:15 +0000439 Diag(D.getDeclSpec().getSourceRange().Begin(),
440 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000441 D.getDeclSpec().getSourceRange(), D.getSourceRange());
442 return 0;
443 }
444
Chris Lattnera7549902007-08-26 06:24:45 +0000445 // The scope passed in may not be a decl scope. Zip up the scope tree until
446 // we find one that is.
447 while ((S->getFlags() & Scope::DeclScope) == 0)
448 S = S->getParent();
449
Chris Lattner4b009652007-07-25 00:24:17 +0000450 // See if this is a redefinition of a variable in the same scope.
451 Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
452 D.getIdentifierLoc(), S);
453 if (PrevDecl && !S->isDeclScope(PrevDecl))
454 PrevDecl = 0; // If in outer scope, it isn't the same thing.
455
456 Decl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000457 bool InvalidDecl = false;
458
Chris Lattner4b009652007-07-25 00:24:17 +0000459 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
460 assert(Init == 0 && "Can't have initializer for a typedef!");
461 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
462 if (!NewTD) return 0;
463
464 // Handle attributes prior to checking for duplicates in MergeVarDecl
465 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
466 D.getAttributes());
467 // Merge the decl with the existing one if appropriate.
468 if (PrevDecl) {
469 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
470 if (NewTD == 0) return 0;
471 }
472 New = NewTD;
473 if (S->getParent() == 0) {
474 // C99 6.7.7p2: If a typedef name specifies a variably modified type
475 // then it shall have block scope.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000476 if (const VariableArrayType *VAT =
477 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
478 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
479 VAT->getSizeExpr()->getSourceRange());
480 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000481 }
482 }
483 } else if (D.isFunctionDeclarator()) {
484 assert(Init == 0 && "Can't have an initializer for a functiondecl!");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000485
Chris Lattner4b009652007-07-25 00:24:17 +0000486 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000487 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000488
489 FunctionDecl::StorageClass SC;
490 switch (D.getDeclSpec().getStorageClassSpec()) {
491 default: assert(0 && "Unknown storage class!");
492 case DeclSpec::SCS_auto:
493 case DeclSpec::SCS_register:
494 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
495 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000496 InvalidDecl = true;
497 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000498 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
499 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
500 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
501 }
502
503 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000504 D.getDeclSpec().isInlineSpecified(),
Chris Lattner4b009652007-07-25 00:24:17 +0000505 LastDeclarator);
506
507 // Merge the decl with the existing one if appropriate.
508 if (PrevDecl) {
509 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
510 if (NewFD == 0) return 0;
511 }
512 New = NewFD;
513 } else {
514 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffcae537d2007-08-28 18:45:29 +0000515 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000516
517 VarDecl *NewVD;
518 VarDecl::StorageClass SC;
519 switch (D.getDeclSpec().getStorageClassSpec()) {
520 default: assert(0 && "Unknown storage class!");
521 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
522 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
523 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
524 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
525 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
526 }
527 if (S->getParent() == 0) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000528 if (Init) {
529 if (SC == VarDecl::Extern)
530 Diag(D.getIdentifierLoc(), diag::warn_extern_init);
Steve Naroff509d0b52007-09-04 02:20:04 +0000531 if (!D.getInvalidType())
532 CheckInitializer(Init, R, true);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000533 }
Chris Lattner4b009652007-07-25 00:24:17 +0000534 // File scope. C99 6.9.2p2: A declaration of an identifier for and
535 // object that has file scope without an initializer, and without a
536 // storage-class specifier or with the storage-class specifier "static",
537 // constitutes a tentative definition. Note: A tentative definition with
538 // external linkage is valid (C99 6.2.2p5).
539 if (!Init && SC == VarDecl::Static) {
540 // C99 6.9.2p3: If the declaration of an identifier for an object is
541 // a tentative definition and has internal linkage (C99 6.2.2p3), the
542 // declared type shall not be an incomplete type.
543 if (R->isIncompleteType()) {
544 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
545 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000546 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000547 }
548 }
549 // C99 6.9p2: The storage-class specifiers auto and register shall not
550 // appear in the declaration specifiers in an external declaration.
551 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
552 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
553 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000554 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000555 }
Steve Naroff5eb879b2007-08-31 17:20:07 +0000556 if (SC == VarDecl::Static) {
557 // C99 6.7.5.2p2: If an identifier is declared to be an object with
558 // static storage duration, it shall not have a variable length array.
559 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
560 Expr *Size = VLA->getSizeExpr();
561 if (Size || (!Size && !Init)) {
562 // FIXME: Since we don't support initializers yet, we only emit this
563 // error when we don't have an initializer. Once initializers are
564 // implemented, the VLA will change to a CLA.
565 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
566 InvalidDecl = true;
567 }
568 }
Chris Lattner4b009652007-07-25 00:24:17 +0000569 }
570 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000571 } else {
572 if (Init) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000573 if (SC == VarDecl::Extern) { // C99 6.7.8p5
574 Diag(D.getIdentifierLoc(), diag::err_block_extern_cant_init);
575 InvalidDecl = true;
Steve Naroff509d0b52007-09-04 02:20:04 +0000576 } else if (!D.getInvalidType()) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000577 CheckInitializer(Init, R, SC == VarDecl::Static);
578 }
Steve Naroffe14e5542007-09-02 02:04:30 +0000579 }
Chris Lattner4b009652007-07-25 00:24:17 +0000580 // Block scope. C99 6.7p7: If an identifier for an object is declared with
581 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
582 if (SC != VarDecl::Extern) {
583 if (R->isIncompleteType()) {
584 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
585 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000586 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000587 }
588 }
589 if (SC == VarDecl::Static) {
590 // C99 6.7.5.2p2: If an identifier is declared to be an object with
591 // static storage duration, it shall not have a variable length array.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000592 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
593 Expr *Size = VLA->getSizeExpr();
594 if (Size || (!Size && !Init)) {
595 // FIXME: Since we don't support initializers yet, we only emit this
596 // error when we don't have an initializer. Once initializers are
597 // implemented, the VLA will change to a CLA.
598 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffcae537d2007-08-28 18:45:29 +0000599 InvalidDecl = true;
Steve Naroff5eb879b2007-08-31 17:20:07 +0000600 }
Chris Lattner4b009652007-07-25 00:24:17 +0000601 }
602 }
603 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000604 }
Chris Lattner4b009652007-07-25 00:24:17 +0000605 // Handle attributes prior to checking for duplicates in MergeVarDecl
606 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
607 D.getAttributes());
608
609 // Merge the decl with the existing one if appropriate.
610 if (PrevDecl) {
611 NewVD = MergeVarDecl(NewVD, PrevDecl);
612 if (NewVD == 0) return 0;
613 }
Steve Naroffe14e5542007-09-02 02:04:30 +0000614 if (Init) { // FIXME: This will likely move up above...for now, it stays.
Steve Naroff0f32f432007-08-24 22:33:52 +0000615 NewVD->setInit(Init);
616 }
Chris Lattner4b009652007-07-25 00:24:17 +0000617 New = NewVD;
618 }
619
620 // If this has an identifier, add it to the scope stack.
621 if (II) {
622 New->setNext(II->getFETokenInfo<Decl>());
623 II->setFETokenInfo(New);
624 S->AddDecl(New);
625 }
626
627 if (S->getParent() == 0)
628 AddTopLevelDecl(New, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000629
630 // If any semantic error occurred, mark the decl as invalid.
631 if (D.getInvalidType() || InvalidDecl)
632 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000633
634 return New;
635}
636
637/// The declarators are chained together backwards, reverse the list.
638Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
639 // Often we have single declarators, handle them quickly.
640 Decl *Group = static_cast<Decl*>(group);
641 if (Group == 0 || Group->getNextDeclarator() == 0) return Group;
642
643 Decl *NewGroup = 0;
644 while (Group) {
645 Decl *Next = Group->getNextDeclarator();
646 Group->setNextDeclarator(NewGroup);
647 NewGroup = Group;
648 Group = Next;
649 }
650 return NewGroup;
651}
Steve Naroff91b03f72007-08-28 03:03:08 +0000652
653// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000654ParmVarDecl *
655Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
656 Scope *FnScope) {
657 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
658
659 IdentifierInfo *II = PI.Ident;
660 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
661 // Can this happen for params? We already checked that they don't conflict
662 // among each other. Here they can only shadow globals, which is ok.
663 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
664 PI.IdentLoc, FnScope)) {
665
666 }
667
668 // FIXME: Handle storage class (auto, register). No declarator?
669 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000670
671 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
672 // Doing the promotion here has a win and a loss. The win is the type for
673 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
674 // code generator). The loss is the orginal type isn't preserved. For example:
675 //
676 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
677 // int blockvardecl[5];
678 // sizeof(parmvardecl); // size == 4
679 // sizeof(blockvardecl); // size == 20
680 // }
681 //
682 // For expressions, all implicit conversions are captured using the
683 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
684 //
685 // FIXME: If a source translation tool needs to see the original type, then
686 // we need to consider storing both types (in ParmVarDecl)...
687 //
688 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
689 if (const ArrayType *AT = parmDeclType->getAsArrayType())
690 parmDeclType = Context.getPointerType(AT->getElementType());
691 else if (parmDeclType->isFunctionType())
692 parmDeclType = Context.getPointerType(parmDeclType);
693
694 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffcae537d2007-08-28 18:45:29 +0000695 VarDecl::None, 0);
696 if (PI.InvalidType)
697 New->setInvalidDecl();
698
Chris Lattner4b009652007-07-25 00:24:17 +0000699 // If this has an identifier, add it to the scope stack.
700 if (II) {
701 New->setNext(II->getFETokenInfo<Decl>());
702 II->setFETokenInfo(New);
703 FnScope->AddDecl(New);
704 }
705
706 return New;
707}
708
709
710Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
711 assert(CurFunctionDecl == 0 && "Function parsing confused");
712 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
713 "Not a function declarator!");
714 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
715
716 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
717 // for a K&R function.
718 if (!FTI.hasPrototype) {
719 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
720 if (FTI.ArgInfo[i].TypeInfo == 0) {
721 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
722 FTI.ArgInfo[i].Ident->getName());
723 // Implicitly declare the argument as type 'int' for lack of a better
724 // type.
725 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
726 }
727 }
728
729 // Since this is a function definition, act as though we have information
730 // about the arguments.
731 FTI.hasPrototype = true;
732 } else {
733 // FIXME: Diagnose arguments without names in C.
734
735 }
736
737 Scope *GlobalScope = FnBodyScope->getParent();
738
739 FunctionDecl *FD =
740 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0, 0));
741 CurFunctionDecl = FD;
742
743 // Create Decl objects for each parameter, adding them to the FunctionDecl.
744 llvm::SmallVector<ParmVarDecl*, 16> Params;
745
746 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
747 // no arguments, not a function that takes a single void argument.
748 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
749 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
750 // empty arg list, don't push any params.
751 } else {
752 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
753 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
754 }
755
756 FD->setParams(&Params[0], Params.size());
757
758 return FD;
759}
760
761Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
762 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
763 FD->setBody((Stmt*)Body);
764
765 assert(FD == CurFunctionDecl && "Function parsing confused");
766 CurFunctionDecl = 0;
767
768 // Verify and clean out per-function state.
769
770 // Check goto/label use.
771 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
772 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
773 // Verify that we have no forward references left. If so, there was a goto
774 // or address of a label taken, but no definition of it. Label fwd
775 // definitions are indicated with a null substmt.
776 if (I->second->getSubStmt() == 0) {
777 LabelStmt *L = I->second;
778 // Emit error.
779 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
780
781 // At this point, we have gotos that use the bogus label. Stitch it into
782 // the function body so that they aren't leaked and that the AST is well
783 // formed.
784 L->setSubStmt(new NullStmt(L->getIdentLoc()));
785 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
786 }
787 }
788 LabelMap.clear();
789
790 return FD;
791}
792
793
794/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
795/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
796Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
797 Scope *S) {
798 if (getLangOptions().C99) // Extension in C99.
799 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
800 else // Legal in C90, but warn about it.
801 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
802
803 // FIXME: handle stuff like:
804 // void foo() { extern float X(); }
805 // void bar() { X(); } <-- implicit decl for X in another scope.
806
807 // Set a Declarator for the implicit definition: int foo();
808 const char *Dummy;
809 DeclSpec DS;
810 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
811 Error = Error; // Silence warning.
812 assert(!Error && "Error setting up implicit decl!");
813 Declarator D(DS, Declarator::BlockContext);
814 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
815 D.SetIdentifier(&II, Loc);
816
817 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000818 if (Scope *FnS = S->getFnParent())
819 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000820 while (S->getParent())
821 S = S->getParent();
822
823 return static_cast<Decl*>(ParseDeclarator(S, D, 0, 0));
824}
825
826
827TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
828 Decl *LastDeclarator) {
829 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
830
831 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000832 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000833
834 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000835 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
836 T, LastDeclarator);
837 if (D.getInvalidType())
838 NewTD->setInvalidDecl();
839 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +0000840}
841
Steve Naroff81f1bba2007-09-06 21:24:23 +0000842Sema::DeclTy *Sema::ObjcStartClassInterface(SourceLocation AtInterfaceLoc,
843 IdentifierInfo *ClassName, SourceLocation ClassLoc,
844 IdentifierInfo *SuperName, SourceLocation SuperLoc,
845 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
846 AttributeList *AttrList) {
847 assert(ClassName && "Missing class identifier");
848 ObjcInterfaceDecl *IDecl;
849
850 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, ClassName);
851
852 // Chain & install the interface decl into the identifier.
853 IDecl->setNext(ClassName->getFETokenInfo<Decl>());
854 ClassName->setFETokenInfo(IDecl);
855 return IDecl;
856}
857
858/// ObjcClassDeclaration -
859/// Scope will always be top level file scope.
860Action::DeclTy *
861Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
862 IdentifierInfo **IdentList, unsigned NumElts) {
863 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
864
865 for (unsigned i = 0; i != NumElts; ++i) {
866 ObjcInterfaceDecl *IDecl;
867
Steve Narofffaed3bf2007-09-10 20:51:04 +0000868 // FIXME: before we create one, look up the interface decl in a hash table.
Steve Naroff81f1bba2007-09-06 21:24:23 +0000869 IDecl = new ObjcInterfaceDecl(SourceLocation(), IdentList[i], true);
870 // Chain & install the interface decl into the identifier.
871 IDecl->setNext(IdentList[i]->getFETokenInfo<Decl>());
872 IdentList[i]->setFETokenInfo(IDecl);
873
874 // Remember that this needs to be removed when the scope is popped.
875 S->AddDecl(IdentList[i]);
876
877 CDecl->setInterfaceDecl((int)i, IDecl);
878 }
879 return CDecl;
880}
881
Chris Lattner4b009652007-07-25 00:24:17 +0000882
883/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
884/// former case, Name will be non-null. In the later case, Name will be null.
885/// TagType indicates what kind of tag this is. TK indicates whether this is a
886/// reference/declaration/definition of a tag.
887Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
888 SourceLocation KWLoc, IdentifierInfo *Name,
889 SourceLocation NameLoc, AttributeList *Attr) {
890 // If this is a use of an existing tag, it must have a name.
891 assert((Name != 0 || TK == TK_Definition) &&
892 "Nameless record must be a definition!");
893
894 Decl::Kind Kind;
895 switch (TagType) {
896 default: assert(0 && "Unknown tag type!");
897 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
898 case DeclSpec::TST_union: Kind = Decl::Union; break;
899//case DeclSpec::TST_class: Kind = Decl::Class; break;
900 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
901 }
902
903 // If this is a named struct, check to see if there was a previous forward
904 // declaration or definition.
905 if (TagDecl *PrevDecl =
906 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
907 NameLoc, S))) {
908
909 // If this is a use of a previous tag, or if the tag is already declared in
910 // the same scope (so that the definition/declaration completes or
911 // rementions the tag), reuse the decl.
912 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
913 // Make sure that this wasn't declared as an enum and now used as a struct
914 // or something similar.
915 if (PrevDecl->getKind() != Kind) {
916 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
917 Diag(PrevDecl->getLocation(), diag::err_previous_use);
918 }
919
920 // If this is a use or a forward declaration, we're good.
921 if (TK != TK_Definition)
922 return PrevDecl;
923
924 // Diagnose attempts to redefine a tag.
925 if (PrevDecl->isDefinition()) {
926 Diag(NameLoc, diag::err_redefinition, Name->getName());
927 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
928 // If this is a redefinition, recover by making this struct be
929 // anonymous, which will make any later references get the previous
930 // definition.
931 Name = 0;
932 } else {
933 // Okay, this is definition of a previously declared or referenced tag.
934 // Move the location of the decl to be the definition site.
935 PrevDecl->setLocation(NameLoc);
936 return PrevDecl;
937 }
938 }
939 // If we get here, this is a definition of a new struct type in a nested
940 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
941 // type.
942 }
943
944 // If there is an identifier, use the location of the identifier as the
945 // location of the decl, otherwise use the location of the struct/union
946 // keyword.
947 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
948
949 // Otherwise, if this is the first time we've seen this tag, create the decl.
950 TagDecl *New;
951 switch (Kind) {
952 default: assert(0 && "Unknown tag kind!");
953 case Decl::Enum:
954 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
955 // enum X { A, B, C } D; D should chain to X.
956 New = new EnumDecl(Loc, Name, 0);
957 // If this is an undefined enum, warn.
958 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
959 break;
960 case Decl::Union:
961 case Decl::Struct:
962 case Decl::Class:
963 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
964 // struct X { int A; } D; D should chain to X.
965 New = new RecordDecl(Kind, Loc, Name, 0);
966 break;
967 }
968
969 // If this has an identifier, add it to the scope stack.
970 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +0000971 // The scope passed in may not be a decl scope. Zip up the scope tree until
972 // we find one that is.
973 while ((S->getFlags() & Scope::DeclScope) == 0)
974 S = S->getParent();
975
976 // Add it to the decl chain.
Chris Lattner4b009652007-07-25 00:24:17 +0000977 New->setNext(Name->getFETokenInfo<Decl>());
978 Name->setFETokenInfo(New);
979 S->AddDecl(New);
980 }
981
982 return New;
983}
984
985/// ParseField - Each field of a struct/union/class is passed into this in order
986/// to create a FieldDecl object for it.
987Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
988 SourceLocation DeclStart,
989 Declarator &D, ExprTy *BitfieldWidth) {
990 IdentifierInfo *II = D.getIdentifier();
991 Expr *BitWidth = (Expr*)BitfieldWidth;
992
993 SourceLocation Loc = DeclStart;
994 if (II) Loc = D.getIdentifierLoc();
995
996 // FIXME: Unnamed fields can be handled in various different ways, for
997 // example, unnamed unions inject all members into the struct namespace!
998
999
1000 if (BitWidth) {
1001 // TODO: Validate.
1002 //printf("WARNING: BITFIELDS IGNORED!\n");
1003
1004 // 6.7.2.1p3
1005 // 6.7.2.1p4
1006
1007 } else {
1008 // Not a bitfield.
1009
1010 // validate II.
1011
1012 }
1013
1014 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001015 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1016 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001017
Chris Lattner4b009652007-07-25 00:24:17 +00001018 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1019 // than a variably modified type.
Steve Naroff5eb879b2007-08-31 17:20:07 +00001020 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1021 Diag(Loc, diag::err_typecheck_illegal_vla,
1022 VAT->getSizeExpr()->getSourceRange());
1023 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001024 }
Chris Lattner4b009652007-07-25 00:24:17 +00001025 // FIXME: Chain fielddecls together.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001026 FieldDecl *NewFD = new FieldDecl(Loc, II, T, 0);
1027 if (D.getInvalidType() || InvalidDecl)
1028 NewFD->setInvalidDecl();
1029 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001030}
1031
1032void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
1033 DeclTy **Fields, unsigned NumFields) {
1034 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
1035 if (Record->isDefinition()) {
1036 // Diagnose code like:
1037 // struct S { struct S {} X; };
1038 // We discover this when we complete the outer S. Reject and ignore the
1039 // outer S.
1040 Diag(Record->getLocation(), diag::err_nested_redefinition,
1041 Record->getKindName());
1042 Diag(RecLoc, diag::err_previous_definition);
1043 return;
1044 }
1045
1046 // Verify that all the fields are okay.
1047 unsigned NumNamedMembers = 0;
1048 llvm::SmallVector<FieldDecl*, 32> RecFields;
1049 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
1050
1051 for (unsigned i = 0; i != NumFields; ++i) {
1052 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1053 if (!FD) continue; // Already issued a diagnostic.
1054
1055 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001056 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +00001057
1058 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001059 if (FDTy->isFunctionType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001060 Diag(FD->getLocation(), diag::err_field_declared_as_function,
1061 FD->getName());
1062 delete FD;
1063 continue;
1064 }
1065
1066 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1067 if (FDTy->isIncompleteType()) {
1068 if (i != NumFields-1 || // ... that the last member ...
1069 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001070 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001071 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1072 delete FD;
1073 continue;
1074 }
1075 if (NumNamedMembers < 1) { //... must have more than named member ...
1076 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1077 FD->getName());
1078 delete FD;
1079 continue;
1080 }
1081
1082 // Okay, we have a legal flexible array member at the end of the struct.
1083 Record->setHasFlexibleArrayMember(true);
1084 }
1085
1086
1087 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1088 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001089 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001090 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1091 // If this is a member of a union, then entire union becomes "flexible".
1092 if (Record->getKind() == Decl::Union) {
1093 Record->setHasFlexibleArrayMember(true);
1094 } else {
1095 // If this is a struct/class and this is not the last element, reject
1096 // it. Note that GCC supports variable sized arrays in the middle of
1097 // structures.
1098 if (i != NumFields-1) {
1099 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1100 FD->getName());
1101 delete FD;
1102 continue;
1103 }
1104
1105 // We support flexible arrays at the end of structs in other structs
1106 // as an extension.
1107 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1108 FD->getName());
1109 Record->setHasFlexibleArrayMember(true);
1110 }
1111 }
1112 }
1113
1114 // Keep track of the number of named members.
1115 if (IdentifierInfo *II = FD->getIdentifier()) {
1116 // Detect duplicate member names.
1117 if (!FieldIDs.insert(II)) {
1118 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1119 // Find the previous decl.
1120 SourceLocation PrevLoc;
1121 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1122 assert(i != e && "Didn't find previous def!");
1123 if (RecFields[i]->getIdentifier() == II) {
1124 PrevLoc = RecFields[i]->getLocation();
1125 break;
1126 }
1127 }
1128 Diag(PrevLoc, diag::err_previous_definition);
1129 delete FD;
1130 continue;
1131 }
1132 ++NumNamedMembers;
1133 }
1134
1135 // Remember good fields.
1136 RecFields.push_back(FD);
1137 }
1138
1139
1140 // Okay, we successfully defined 'Record'.
1141 Record->defineBody(&RecFields[0], RecFields.size());
1142}
1143
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001144void Sema::ObjcAddMethodsToClass(DeclTy *ClassDecl,
1145 DeclTy **allMethods, unsigned allNum) {
1146 // FIXME: Add method insertion code here.
1147#if 0
1148 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1149 static_cast<Decl*>(ClassDecl));
1150 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1151 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1152
1153 for (unsigned i = 0; i < allNum; i++ ) {
1154 ObjcMethodDecl *Method =
1155 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1156 if (!Method) continue; // Already issued a diagnostic.
1157 if (Method->isInstance())
1158 insMethods.push_back(Method);
1159 else
1160 clsMethods.push_back(Method);
1161 }
1162 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1163 &clsMethods[0], clsMethods.size());
1164#endif
1165 return;
1166}
1167
Chris Lattner4b009652007-07-25 00:24:17 +00001168Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
1169 DeclTy *lastEnumConst,
1170 SourceLocation IdLoc, IdentifierInfo *Id,
1171 SourceLocation EqualLoc, ExprTy *val) {
1172 theEnumDecl = theEnumDecl; // silence unused warning.
1173 EnumConstantDecl *LastEnumConst =
1174 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1175 Expr *Val = static_cast<Expr*>(val);
1176
Chris Lattnera7549902007-08-26 06:24:45 +00001177 // The scope passed in may not be a decl scope. Zip up the scope tree until
1178 // we find one that is.
1179 while ((S->getFlags() & Scope::DeclScope) == 0)
1180 S = S->getParent();
1181
Chris Lattner4b009652007-07-25 00:24:17 +00001182 // Verify that there isn't already something declared with this name in this
1183 // scope.
1184 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
1185 if (S->isDeclScope(PrevDecl)) {
1186 if (isa<EnumConstantDecl>(PrevDecl))
1187 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1188 else
1189 Diag(IdLoc, diag::err_redefinition, Id->getName());
1190 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1191 // FIXME: Don't leak memory: delete Val;
1192 return 0;
1193 }
1194 }
1195
1196 llvm::APSInt EnumVal(32);
1197 QualType EltTy;
1198 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001199 // Make sure to promote the operand type to int.
1200 UsualUnaryConversions(Val);
1201
Chris Lattner4b009652007-07-25 00:24:17 +00001202 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1203 SourceLocation ExpLoc;
1204 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1205 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1206 Id->getName());
1207 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001208 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001209 } else {
1210 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001211 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001212 }
1213
1214 if (!Val) {
1215 if (LastEnumConst) {
1216 // Assign the last value + 1.
1217 EnumVal = LastEnumConst->getInitVal();
1218 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001219
1220 // Check for overflow on increment.
1221 if (EnumVal < LastEnumConst->getInitVal())
1222 Diag(IdLoc, diag::warn_enum_value_overflow);
1223
Chris Lattnere7f53a42007-08-27 17:37:24 +00001224 EltTy = LastEnumConst->getType();
1225 } else {
1226 // First value, set to zero.
1227 EltTy = Context.IntTy;
Chris Lattner3496d522007-09-04 02:45:27 +00001228 EnumVal.zextOrTrunc(
1229 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001230 }
Chris Lattner4b009652007-07-25 00:24:17 +00001231 }
1232
Chris Lattner4b009652007-07-25 00:24:17 +00001233 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1234 LastEnumConst);
1235
1236 // Register this decl in the current scope stack.
1237 New->setNext(Id->getFETokenInfo<Decl>());
1238 Id->setFETokenInfo(New);
1239 S->AddDecl(New);
1240 return New;
1241}
1242
1243void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1244 DeclTy **Elements, unsigned NumElements) {
1245 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1246 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1247
Chris Lattner435c3fd2007-08-28 05:10:31 +00001248 // TODO: If the result value doesn't fit in an int, it must be a long or long
1249 // long value. ISO C does not support this, but GCC does as an extension,
1250 // emit a warning.
Chris Lattner206754a2007-08-28 06:15:15 +00001251 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner435c3fd2007-08-28 05:10:31 +00001252
1253
Chris Lattner206754a2007-08-28 06:15:15 +00001254 // Verify that all the values are okay, compute the size of the values, and
1255 // reverse the list.
1256 unsigned NumNegativeBits = 0;
1257 unsigned NumPositiveBits = 0;
1258
1259 // Keep track of whether all elements have type int.
1260 bool AllElementsInt = true;
1261
Chris Lattner4b009652007-07-25 00:24:17 +00001262 EnumConstantDecl *EltList = 0;
1263 for (unsigned i = 0; i != NumElements; ++i) {
1264 EnumConstantDecl *ECD =
1265 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1266 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001267
1268 // If the enum value doesn't fit in an int, emit an extension warning.
1269 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1270 "Should have promoted value to int");
1271 const llvm::APSInt &InitVal = ECD->getInitVal();
1272 if (InitVal.getBitWidth() > IntWidth) {
1273 llvm::APSInt V(InitVal);
1274 V.trunc(IntWidth);
1275 V.extend(InitVal.getBitWidth());
1276 if (V != InitVal)
1277 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1278 InitVal.toString());
1279 }
Chris Lattner206754a2007-08-28 06:15:15 +00001280
1281 // Keep track of the size of positive and negative values.
1282 if (InitVal.isUnsigned() || !InitVal.isNegative())
1283 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1284 else
1285 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001286
Chris Lattner206754a2007-08-28 06:15:15 +00001287 // Keep track of whether every enum element has type int (very commmon).
1288 if (AllElementsInt)
1289 AllElementsInt = ECD->getType() == Context.IntTy;
1290
Chris Lattner4b009652007-07-25 00:24:17 +00001291 ECD->setNextDeclarator(EltList);
1292 EltList = ECD;
1293 }
1294
Chris Lattner206754a2007-08-28 06:15:15 +00001295 // Figure out the type that should be used for this enum.
1296 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1297 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001298 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001299
1300 if (NumNegativeBits) {
1301 // If there is a negative value, figure out the smallest integer type (of
1302 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001303 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001304 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001305 BestWidth = IntWidth;
1306 } else {
1307 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1308 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001309 BestType = Context.LongTy;
1310 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001311 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1312 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001313 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1314 BestType = Context.LongLongTy;
1315 }
1316 }
1317 } else {
1318 // If there is no negative value, figure out which of uint, ulong, ulonglong
1319 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001320 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001321 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001322 BestWidth = IntWidth;
1323 } else if (NumPositiveBits <=
1324 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattner206754a2007-08-28 06:15:15 +00001325 BestType = Context.UnsignedLongTy;
1326 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001327 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1328 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001329 "How could an initializer get larger than ULL?");
1330 BestType = Context.UnsignedLongLongTy;
1331 }
1332 }
1333
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001334 // Loop over all of the enumerator constants, changing their types to match
1335 // the type of the enum if needed.
1336 for (unsigned i = 0; i != NumElements; ++i) {
1337 EnumConstantDecl *ECD =
1338 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1339 if (!ECD) continue; // Already issued a diagnostic.
1340
1341 // Standard C says the enumerators have int type, but we allow, as an
1342 // extension, the enumerators to be larger than int size. If each
1343 // enumerator value fits in an int, type it as an int, otherwise type it the
1344 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1345 // that X has type 'int', not 'unsigned'.
1346 if (ECD->getType() == Context.IntTy)
1347 continue; // Already int type.
1348
1349 // Determine whether the value fits into an int.
1350 llvm::APSInt InitVal = ECD->getInitVal();
1351 bool FitsInInt;
1352 if (InitVal.isUnsigned() || !InitVal.isNegative())
1353 FitsInInt = InitVal.getActiveBits() < IntWidth;
1354 else
1355 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1356
1357 // If it fits into an integer type, force it. Otherwise force it to match
1358 // the enum decl type.
1359 QualType NewTy;
1360 unsigned NewWidth;
1361 bool NewSign;
1362 if (FitsInInt) {
1363 NewTy = Context.IntTy;
1364 NewWidth = IntWidth;
1365 NewSign = true;
1366 } else if (ECD->getType() == BestType) {
1367 // Already the right type!
1368 continue;
1369 } else {
1370 NewTy = BestType;
1371 NewWidth = BestWidth;
1372 NewSign = BestType->isSignedIntegerType();
1373 }
1374
1375 // Adjust the APSInt value.
1376 InitVal.extOrTrunc(NewWidth);
1377 InitVal.setIsSigned(NewSign);
1378 ECD->setInitVal(InitVal);
1379
1380 // Adjust the Expr initializer and type.
1381 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1382 ECD->setType(NewTy);
1383 }
Chris Lattner206754a2007-08-28 06:15:15 +00001384
Chris Lattner90a018d2007-08-28 18:24:31 +00001385 Enum->defineElements(EltList, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00001386}
1387
1388void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1389 if (!current) return;
1390
1391 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1392 // remember this in the LastInGroupList list.
1393 if (last)
1394 LastInGroupList.push_back((Decl*)last);
1395}
1396
1397void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1398 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1399 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1400 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1401 if (!newType.isNull()) // install the new vector type into the decl
1402 vDecl->setType(newType);
1403 }
1404 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1405 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1406 rawAttr);
1407 if (!newType.isNull()) // install the new vector type into the decl
1408 tDecl->setUnderlyingType(newType);
1409 }
1410 }
1411 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroff82113e32007-07-29 16:33:31 +00001412 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1413 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1414 else
Chris Lattner4b009652007-07-25 00:24:17 +00001415 Diag(rawAttr->getAttributeLoc(),
1416 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner4b009652007-07-25 00:24:17 +00001417 }
1418 // FIXME: add other attributes...
1419}
1420
1421void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1422 AttributeList *declarator_postfix) {
1423 while (declspec_prefix) {
1424 HandleDeclAttribute(New, declspec_prefix);
1425 declspec_prefix = declspec_prefix->getNext();
1426 }
1427 while (declarator_postfix) {
1428 HandleDeclAttribute(New, declarator_postfix);
1429 declarator_postfix = declarator_postfix->getNext();
1430 }
1431}
1432
Steve Naroff82113e32007-07-29 16:33:31 +00001433void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1434 AttributeList *rawAttr) {
1435 QualType curType = tDecl->getUnderlyingType();
Chris Lattner4b009652007-07-25 00:24:17 +00001436 // check the attribute arugments.
1437 if (rawAttr->getNumArgs() != 1) {
1438 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1439 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001440 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001441 }
1442 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1443 llvm::APSInt vecSize(32);
1444 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1445 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1446 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001447 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001448 }
1449 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1450 // in conjunction with complex types (pointers, arrays, functions, etc.).
1451 Type *canonType = curType.getCanonicalType().getTypePtr();
1452 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1453 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1454 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001455 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001456 }
1457 // unlike gcc's vector_size attribute, the size is specified as the
1458 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00001459 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00001460
1461 if (vectorSize == 0) {
1462 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1463 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001464 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001465 }
Steve Naroff82113e32007-07-29 16:33:31 +00001466 // Instantiate/Install the vector type, the number of elements is > 0.
1467 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1468 // Remember this typedef decl, we will need it later for diagnostics.
1469 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001470}
1471
1472QualType Sema::HandleVectorTypeAttribute(QualType curType,
1473 AttributeList *rawAttr) {
1474 // check the attribute arugments.
1475 if (rawAttr->getNumArgs() != 1) {
1476 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1477 std::string("1"));
1478 return QualType();
1479 }
1480 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1481 llvm::APSInt vecSize(32);
1482 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1483 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1484 sizeExpr->getSourceRange());
1485 return QualType();
1486 }
1487 // navigate to the base type - we need to provide for vector pointers,
1488 // vector arrays, and functions returning vectors.
1489 Type *canonType = curType.getCanonicalType().getTypePtr();
1490
1491 if (canonType->isPointerType() || canonType->isArrayType() ||
1492 canonType->isFunctionType()) {
1493 assert(1 && "HandleVector(): Complex type construction unimplemented");
1494 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1495 do {
1496 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1497 canonType = PT->getPointeeType().getTypePtr();
1498 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1499 canonType = AT->getElementType().getTypePtr();
1500 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1501 canonType = FT->getResultType().getTypePtr();
1502 } while (canonType->isPointerType() || canonType->isArrayType() ||
1503 canonType->isFunctionType());
1504 */
1505 }
1506 // the base type must be integer or float.
1507 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1508 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1509 curType.getCanonicalType().getAsString());
1510 return QualType();
1511 }
Chris Lattner3496d522007-09-04 02:45:27 +00001512 unsigned typeSize = static_cast<unsigned>(
1513 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Chris Lattner4b009652007-07-25 00:24:17 +00001514 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00001515 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00001516
1517 // the vector size needs to be an integral multiple of the type size.
1518 if (vectorSize % typeSize) {
1519 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1520 sizeExpr->getSourceRange());
1521 return QualType();
1522 }
1523 if (vectorSize == 0) {
1524 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1525 sizeExpr->getSourceRange());
1526 return QualType();
1527 }
1528 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1529 // the number of elements to be a power of two (unlike GCC).
1530 // Instantiate the vector type, the number of elements is > 0.
1531 return Context.getVectorType(curType, vectorSize/typeSize);
1532}
1533