blob: 97e8e07aafbdd8fb6287b8b599ff6bd38dcc7ea9 [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +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
Chris Lattnere168f762006-11-10 05:29:30 +000014#include "Sema.h"
Chris Lattner5c5fbcc2006-12-03 08:41:30 +000015#include "clang/AST/ASTContext.h"
Chris Lattner9561a0b2007-01-28 08:20:04 +000016#include "clang/AST/Builtins.h"
Chris Lattnere168f762006-11-10 05:29:30 +000017#include "clang/AST/Decl.h"
Chris Lattner1300fb92007-01-23 23:42:53 +000018#include "clang/AST/Expr.h"
Chris Lattnerf84a79c2006-11-11 22:59:23 +000019#include "clang/AST/Type.h"
Chris Lattner591a6752006-11-19 23:16:18 +000020#include "clang/Parse/DeclSpec.h"
Chris Lattnere168f762006-11-10 05:29:30 +000021#include "clang/Parse/Scope.h"
22#include "clang/Lex/IdentifierTable.h"
Chris Lattnerac18be92006-11-20 06:49:47 +000023#include "clang/Basic/LangOptions.h"
Chris Lattner9561a0b2007-01-28 08:20:04 +000024#include "clang/Basic/TargetInfo.h"
Chris Lattner38047f92007-01-27 06:24:01 +000025#include "llvm/ADT/SmallSet.h"
Chris Lattner697e5d62006-11-09 06:32:27 +000026using namespace clang;
27
Chris Lattner2ebe4bb2006-11-20 01:29:42 +000028Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Steve Naroff09bf8152007-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 Lattnere168f762006-11-10 05:29:30 +000034}
35
Chris Lattner302b4be2006-11-19 02:31:38 +000036void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +000037 if (S->decl_empty()) return;
38 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
39
Chris Lattner302b4be2006-11-19 02:31:38 +000040 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
41 I != E; ++I) {
Steve Naroff9324db12007-09-13 18:10:37 +000042 Decl *TmpD = static_cast<Decl*>(*I);
43 assert(TmpD && "This decl didn't get pushed??");
44 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
45 assert(D && "This decl isn't a ScopedDecl?");
46
Chris Lattnerff65b6b2007-01-23 01:33:16 +000047 IdentifierInfo *II = D->getIdentifier();
48 if (!II) continue;
Chris Lattner302b4be2006-11-19 02:31:38 +000049
Chris Lattnerff65b6b2007-01-23 01:33:16 +000050 // Unlink this decl from the identifier. Because the scope contains decls
51 // in an unordered collection, and because we have multiple identifier
52 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
53 if (II->getFETokenInfo<Decl>() == D) {
54 // Normal case, no multiple decls in different namespaces.
55 II->setFETokenInfo(D->getNext());
56 } else {
57 // Scan ahead. There are only three namespaces in C, so this loop can
58 // never execute more than 3 times.
Steve Naroff9324db12007-09-13 18:10:37 +000059 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Chris Lattnerff65b6b2007-01-23 01:33:16 +000060 while (SomeDecl->getNext() != D) {
61 SomeDecl = SomeDecl->getNext();
62 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
63 }
64 SomeDecl->setNext(D->getNext());
65 }
Chris Lattner302b4be2006-11-19 02:31:38 +000066
Chris Lattner740b2f32006-11-21 01:32:20 +000067 // This will have to be revisited for C++: there we want to nest stuff in
68 // namespace decls etc. Even for C, we might want a top-level translation
69 // unit decl or something.
70 if (!CurFunctionDecl)
71 continue;
72
73 // Chain this decl to the containing function, it now owns the memory for
74 // the decl.
75 D->setNext(CurFunctionDecl->getDeclChain());
76 CurFunctionDecl->setDeclChain(D);
Chris Lattner302b4be2006-11-19 02:31:38 +000077 }
78}
79
Chris Lattner18b19622007-01-22 07:39:13 +000080/// LookupScopedDecl - Look up the inner-most declaration in the specified
81/// namespace.
Steve Naroff9324db12007-09-13 18:10:37 +000082ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
83 SourceLocation IdLoc, Scope *S) {
Chris Lattner18b19622007-01-22 07:39:13 +000084 if (II == 0) return 0;
Chris Lattnerb6738ec2007-01-28 00:38:24 +000085 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
Chris Lattner18b19622007-01-22 07:39:13 +000086
87 // Scan up the scope chain looking for a decl that matches this identifier
88 // that is in the appropriate namespace. This search should not take long, as
89 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroff9324db12007-09-13 18:10:37 +000090 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner18b19622007-01-22 07:39:13 +000091 if (D->getIdentifierNamespace() == NS)
92 return D;
Chris Lattnerb6738ec2007-01-28 00:38:24 +000093
Chris Lattner9561a0b2007-01-28 08:20:04 +000094 // If we didn't find a use of this identifier, and if the identifier
95 // corresponds to a compiler builtin, create the decl object for the builtin
96 // now, injecting it into translation unit scope, and return it.
97 if (NS == Decl::IDNS_Ordinary) {
98 // If this is a builtin on some other target, or if this builtin varies
99 // across targets (e.g. in type), emit a diagnostic and mark the translation
100 // unit non-portable for using it.
101 if (II->isNonPortableBuiltin()) {
102 // Only emit this diagnostic once for this builtin.
103 II->setNonPortableBuiltin(false);
104 Context.Target.DiagnoseNonPortability(IdLoc,
105 diag::port_target_builtin_use);
106 }
Chris Lattner9561a0b2007-01-28 08:20:04 +0000107 // If this is a builtin on this (or all) targets, create the decl.
108 if (unsigned BuiltinID = II->getBuiltinID())
109 return LazilyCreateBuiltin(II, BuiltinID, S);
110 }
Chris Lattner18b19622007-01-22 07:39:13 +0000111 return 0;
112}
113
Chris Lattner9561a0b2007-01-28 08:20:04 +0000114/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
115/// lazily create a decl for it.
Steve Naroff9324db12007-09-13 18:10:37 +0000116ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000117 Builtin::ID BID = (Builtin::ID)bid;
118
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000119 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner776fac82007-06-09 00:53:06 +0000120 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattnerb677a932007-08-26 04:02:13 +0000121 FunctionDecl::Extern, false, 0);
Chris Lattner9561a0b2007-01-28 08:20:04 +0000122
123 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000124 if (Scope *FnS = S->getFnParent())
125 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner9561a0b2007-01-28 08:20:04 +0000126 while (S->getParent())
127 S = S->getParent();
128 S->AddDecl(New);
129
130 // Add this decl to the end of the identifier info.
Steve Naroff9324db12007-09-13 18:10:37 +0000131 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000132 // Scan until we find the last (outermost) decl in the id chain.
133 while (LastDecl->getNext())
134 LastDecl = LastDecl->getNext();
135 // Insert before (outside) it.
136 LastDecl->setNext(New);
137 } else {
138 II->setFETokenInfo(New);
139 }
140 // Make sure clients iterating over decls see this.
141 LastInGroupList.push_back(New);
142
143 return New;
144}
145
Chris Lattner01564d92007-01-27 19:27:06 +0000146/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
147/// and scope as a previous declaration 'Old'. Figure out how to resolve this
148/// situation, merging decls or emitting diagnostics as appropriate.
149///
Steve Naroff9def2b12007-09-13 21:41:19 +0000150TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000151 // Verify the old decl was also a typedef.
152 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
153 if (!Old) {
154 Diag(New->getLocation(), diag::err_redefinition_different_kind,
155 New->getName());
156 Diag(OldD->getLocation(), diag::err_previous_definition);
157 return New;
158 }
159
Chris Lattner01564d92007-01-27 19:27:06 +0000160 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
161 // TODO: This is totally simplistic. It should handle merging functions
162 // together etc, merging extern int X; int X; ...
163 Diag(New->getLocation(), diag::err_redefinition, New->getName());
164 Diag(Old->getLocation(), diag::err_previous_definition);
165 return New;
166}
167
168/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
169/// and scope as a previous declaration 'Old'. Figure out how to resolve this
170/// situation, merging decls or emitting diagnostics as appropriate.
171///
Steve Naroff9def2b12007-09-13 21:41:19 +0000172FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000173 // Verify the old decl was also a function.
174 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
175 if (!Old) {
176 Diag(New->getLocation(), diag::err_redefinition_different_kind,
177 New->getName());
178 Diag(OldD->getLocation(), diag::err_previous_definition);
179 return New;
180 }
181
Chris Lattnerefe4aea2007-01-27 19:35:39 +0000182 // This is not right, but it's a start. If 'Old' is a function prototype with
183 // the same type as 'New', silently allow this. FIXME: We should link up decl
184 // objects here.
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000185 if (Old->getBody() == 0 &&
186 Old->getCanonicalType() == New->getCanonicalType()) {
Chris Lattnerefe4aea2007-01-27 19:35:39 +0000187 return New;
188 }
Chris Lattnerc511efb2007-01-27 19:32:14 +0000189
Chris Lattner01564d92007-01-27 19:27:06 +0000190 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
191 // TODO: This is totally simplistic. It should handle merging functions
192 // together etc, merging extern int X; int X; ...
193 Diag(New->getLocation(), diag::err_redefinition, New->getName());
194 Diag(Old->getLocation(), diag::err_previous_definition);
195 return New;
196}
197
198/// MergeVarDecl - We just parsed a variable 'New' which has the same name
199/// and scope as a previous declaration 'Old'. Figure out how to resolve this
200/// situation, merging decls or emitting diagnostics as appropriate.
201///
Steve Narofffc49d672007-04-01 21:27:45 +0000202/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
203/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
204///
Steve Naroff9def2b12007-09-13 21:41:19 +0000205VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000206 // Verify the old decl was also a variable.
207 VarDecl *Old = dyn_cast<VarDecl>(OldD);
208 if (!Old) {
209 Diag(New->getLocation(), diag::err_redefinition_different_kind,
210 New->getName());
211 Diag(OldD->getLocation(), diag::err_previous_definition);
212 return New;
213 }
Steve Naroff5c131802007-08-30 01:06:46 +0000214 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
215 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
216 bool OldIsTentative = false;
217
218 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
219 // Handle C "tentative" external object definitions. FIXME: finish!
220 if (!OldFSDecl->getInit() &&
221 (OldFSDecl->getStorageClass() == VarDecl::None ||
222 OldFSDecl->getStorageClass() == VarDecl::Static))
223 OldIsTentative = true;
224 }
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000225 // Verify the types match.
226 if (Old->getCanonicalType() != New->getCanonicalType()) {
227 Diag(New->getLocation(), diag::err_redefinition, New->getName());
228 Diag(Old->getLocation(), diag::err_previous_definition);
229 return New;
230 }
231 // We've verified the types match, now check if Old is "extern".
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000232 if (Old->getStorageClass() != VarDecl::Extern) {
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000233 Diag(New->getLocation(), diag::err_redefinition, New->getName());
234 Diag(Old->getLocation(), diag::err_previous_definition);
235 }
Chris Lattner01564d92007-01-27 19:27:06 +0000236 return New;
237}
238
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000239/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
240/// no declarator (e.g. "struct foo;") is parsed.
241Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
242 // TODO: emit error on 'int;' or 'const enum foo;'.
243 // TODO: emit error on 'typedef int;'
244 // if (!DS.isMissingDeclaratorOk()) Diag(...);
245
246 return 0;
247}
248
Steve Naroff77b97002007-09-04 14:36:54 +0000249bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroff2fea1392007-09-02 02:04:30 +0000250 AssignmentCheckResult result;
251 SourceLocation loc = Init->getLocStart();
252 // Get the type before calling CheckSingleAssignmentConstraints(), since
253 // it can promote the expression.
254 QualType rhsType = Init->getType();
255
256 result = CheckSingleAssignmentConstraints(DeclType, Init);
257
258 // decode the result (notice that extensions still return a type).
259 switch (result) {
260 case Compatible:
261 break;
262 case Incompatible:
Steve Narofff33527a2007-09-02 15:34:30 +0000263 // FIXME: tighten up this check which should allow:
264 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
265 if (rhsType == Context.getPointerType(Context.CharTy))
266 break;
Steve Naroff2fea1392007-09-02 02:04:30 +0000267 Diag(loc, diag::err_typecheck_assign_incompatible,
268 DeclType.getAsString(), rhsType.getAsString(),
269 Init->getSourceRange());
270 return true;
271 case PointerFromInt:
272 // check for null pointer constant (C99 6.3.2.3p3)
273 if (!Init->isNullPointerConstant(Context)) {
274 Diag(loc, diag::ext_typecheck_assign_pointer_int,
275 DeclType.getAsString(), rhsType.getAsString(),
276 Init->getSourceRange());
277 return true;
278 }
279 break;
280 case IntFromPointer:
281 Diag(loc, diag::ext_typecheck_assign_pointer_int,
282 DeclType.getAsString(), rhsType.getAsString(),
283 Init->getSourceRange());
284 break;
285 case IncompatiblePointer:
286 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
287 DeclType.getAsString(), rhsType.getAsString(),
288 Init->getSourceRange());
289 break;
290 case CompatiblePointerDiscardsQualifiers:
291 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
292 DeclType.getAsString(), rhsType.getAsString(),
293 Init->getSourceRange());
294 break;
295 }
296 return false;
297}
298
Steve Naroff77b97002007-09-04 14:36:54 +0000299bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
300 bool isStatic, QualType ElementType) {
Steve Naroffac074b42007-09-04 02:20:04 +0000301 SourceLocation loc;
Steve Naroff77b97002007-09-04 14:36:54 +0000302 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffac074b42007-09-04 02:20:04 +0000303
304 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
305 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
306 return true;
307 } else if (CheckSingleInitializer(expr, ElementType)) {
308 return true; // types weren't compatible.
309 }
Steve Naroff77b97002007-09-04 14:36:54 +0000310 if (savExpr != expr) // The type was promoted, update initializer list.
311 IList->setInit(slot, expr);
Steve Naroffac074b42007-09-04 02:20:04 +0000312 return false;
313}
314
315void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
316 QualType ElementType, bool isStatic,
317 int &nInitializers, bool &hadError) {
Steve Narofff33527a2007-09-02 15:34:30 +0000318 for (unsigned i = 0; i < IList->getNumInits(); i++) {
319 Expr *expr = IList->getInit(i);
320
Steve Naroffac074b42007-09-04 02:20:04 +0000321 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
322 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff67ae4432007-09-04 21:13:33 +0000323 int maxElements = CAT->getMaximumElements();
Steve Naroffac074b42007-09-04 02:20:04 +0000324 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
325 maxElements, hadError);
Steve Narofff33527a2007-09-02 15:34:30 +0000326 }
Steve Naroffac074b42007-09-04 02:20:04 +0000327 } else {
Steve Naroff77b97002007-09-04 14:36:54 +0000328 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Narofff33527a2007-09-02 15:34:30 +0000329 }
Steve Naroffac074b42007-09-04 02:20:04 +0000330 nInitializers++;
331 }
332 return;
333}
334
335// FIXME: Doesn't deal with arrays of structures yet.
336void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
337 QualType ElementType, bool isStatic,
338 int &totalInits, bool &hadError) {
339 int maxElementsAtThisLevel = 0;
340 int nInitsAtLevel = 0;
341
342 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
343 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff67ae4432007-09-04 21:13:33 +0000344 maxElementsAtThisLevel = CAT->getMaximumElements();
345 // Set DeclType, used below to recurse (for multi-dimensional arrays).
346 DeclType = CAT->getElementType();
Steve Naroffac074b42007-09-04 02:20:04 +0000347 } else if (DeclType->isScalarType()) {
348 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
349 IList->getSourceRange());
350 maxElementsAtThisLevel = 1;
351 }
352 // The empty init list "{ }" is treated specially below.
353 unsigned numInits = IList->getNumInits();
354 if (numInits) {
355 for (unsigned i = 0; i < numInits; i++) {
356 Expr *expr = IList->getInit(i);
357
358 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
359 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
360 totalInits, hadError);
361 } else {
Steve Naroff77b97002007-09-04 14:36:54 +0000362 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroffac074b42007-09-04 02:20:04 +0000363 nInitsAtLevel++; // increment the number of initializers at this level.
364 totalInits--; // decrement the total number of initializers.
365
366 // Check if we have space for another initializer.
367 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
368 Diag(expr->getLocStart(), diag::warn_excess_initializers,
369 expr->getSourceRange());
370 }
371 }
372 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
373 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
374 } else {
375 // we have an initializer list with no elements.
376 totalInits -= maxElementsAtThisLevel;
377 if (totalInits < 0)
378 Diag(IList->getLocStart(), diag::warn_excess_initializers,
379 IList->getSourceRange());
Steve Narofff33527a2007-09-02 15:34:30 +0000380 }
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000381 return;
Steve Narofff33527a2007-09-02 15:34:30 +0000382}
383
Steve Naroff77b97002007-09-04 14:36:54 +0000384bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Naroff2fea1392007-09-02 02:04:30 +0000385 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000386 if (!InitList)
387 return CheckSingleInitializer(Init, DeclType);
388
Steve Naroff2fea1392007-09-02 02:04:30 +0000389 // We have an InitListExpr, make sure we set the type.
390 Init->setType(DeclType);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000391
392 bool hadError = false;
Steve Narofff33527a2007-09-02 15:34:30 +0000393
Steve Naroffb03f5942007-09-02 20:30:18 +0000394 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
395 // of unknown size ("[]") or an object type that is not a variable array type.
396 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
397 Expr *expr = VAT->getSizeExpr();
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000398 if (expr)
399 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
400 expr->getSourceRange());
401
Steve Naroff67ae4432007-09-04 21:13:33 +0000402 // We have a VariableArrayType with unknown size. Note that only the first
403 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroffac074b42007-09-04 02:20:04 +0000404 int numInits = 0;
Steve Naroff67ae4432007-09-04 21:13:33 +0000405 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
406 isStatic, numInits, hadError);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000407 if (!hadError) {
408 // Return a new array type from the number of initializers (C99 6.7.8p22).
409 llvm::APSInt ConstVal(32);
Steve Naroffac074b42007-09-04 02:20:04 +0000410 ConstVal = numInits;
411 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000412 ArrayType::Normal, 0);
413 }
414 return hadError;
415 }
416 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff67ae4432007-09-04 21:13:33 +0000417 int maxElements = CAT->getMaximumElements();
418 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
419 isStatic, maxElements, hadError);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000420 return hadError;
421 }
Steve Naroffac074b42007-09-04 02:20:04 +0000422 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
423 int maxElements = 1;
424 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
425 hadError);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000426 return hadError;
Steve Naroffb03f5942007-09-02 20:30:18 +0000427 }
428 // FIXME: Handle struct/union types.
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000429 return hadError;
Steve Naroff2fea1392007-09-02 02:04:30 +0000430}
431
Chris Lattner776fac82007-06-09 00:53:06 +0000432Sema::DeclTy *
Steve Naroff61091402007-09-12 14:07:44 +0000433Sema::ParseDeclarator(Scope *S, Declarator &D, DeclTy *lastDeclarator) {
Chris Lattner776fac82007-06-09 00:53:06 +0000434 Decl *LastDeclarator = (Decl*)lastDeclarator;
Chris Lattnere168f762006-11-10 05:29:30 +0000435 IdentifierInfo *II = D.getIdentifier();
Chris Lattner302b4be2006-11-19 02:31:38 +0000436
Chris Lattner02c04392007-07-25 00:24:17 +0000437 // All of these full declarators require an identifier. If it doesn't have
438 // one, the ParsedFreeStandingDeclSpec action should be used.
439 if (II == 0) {
Chris Lattnerc4f6d0c2007-08-28 06:17:15 +0000440 Diag(D.getDeclSpec().getSourceRange().Begin(),
441 diag::err_declarator_need_ident,
Chris Lattner02c04392007-07-25 00:24:17 +0000442 D.getDeclSpec().getSourceRange(), D.getSourceRange());
443 return 0;
444 }
445
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000446 // The scope passed in may not be a decl scope. Zip up the scope tree until
447 // we find one that is.
448 while ((S->getFlags() & Scope::DeclScope) == 0)
449 S = S->getParent();
450
Chris Lattner01564d92007-01-27 19:27:06 +0000451 // See if this is a redefinition of a variable in the same scope.
Steve Naroff9324db12007-09-13 18:10:37 +0000452 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
453 D.getIdentifierLoc(), S);
Chris Lattner776fac82007-06-09 00:53:06 +0000454 if (PrevDecl && !S->isDeclScope(PrevDecl))
Chris Lattner01564d92007-01-27 19:27:06 +0000455 PrevDecl = 0; // If in outer scope, it isn't the same thing.
456
Steve Naroff9324db12007-09-13 18:10:37 +0000457 ScopedDecl *New;
Steve Narofff93b6722007-08-28 20:14:24 +0000458 bool InvalidDecl = false;
459
Chris Lattner01a7c532007-01-25 23:09:03 +0000460 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner776fac82007-06-09 00:53:06 +0000461 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
Chris Lattner01564d92007-01-27 19:27:06 +0000462 if (!NewTD) return 0;
Steve Naroffa8fd9732007-06-11 00:35:03 +0000463
464 // Handle attributes prior to checking for duplicates in MergeVarDecl
465 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
466 D.getAttributes());
Chris Lattner01564d92007-01-27 19:27:06 +0000467 // 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;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000473 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 Naroff096dd942007-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;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000481 }
482 }
Chris Lattner01a7c532007-01-25 23:09:03 +0000483 } else if (D.isFunctionDeclarator()) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000484 QualType R = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +0000485 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff7a5af782007-07-13 16:58:59 +0000486
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000487 FunctionDecl::StorageClass SC;
488 switch (D.getDeclSpec().getStorageClassSpec()) {
489 default: assert(0 && "Unknown storage class!");
490 case DeclSpec::SCS_auto:
491 case DeclSpec::SCS_register:
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000492 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
493 R.getAsString());
Steve Narofff93b6722007-08-28 20:14:24 +0000494 InvalidDecl = true;
495 break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000496 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
497 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
498 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
499 }
500
Chris Lattner776fac82007-06-09 00:53:06 +0000501 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattnerb677a932007-08-26 04:02:13 +0000502 D.getDeclSpec().isInlineSpecified(),
Chris Lattner776fac82007-06-09 00:53:06 +0000503 LastDeclarator);
Chris Lattner01564d92007-01-27 19:27:06 +0000504
505 // Merge the decl with the existing one if appropriate.
506 if (PrevDecl) {
507 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
508 if (NewFD == 0) return 0;
509 }
510 New = NewFD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000511 } else {
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000512 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffcf871f52007-08-28 18:45:29 +0000513 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner01564d92007-01-27 19:27:06 +0000514
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000515 VarDecl *NewVD;
516 VarDecl::StorageClass SC;
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000517 switch (D.getDeclSpec().getStorageClassSpec()) {
518 default: assert(0 && "Unknown storage class!");
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000519 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
520 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
521 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
522 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
523 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
524 }
Steve Narofffc49d672007-04-01 21:27:45 +0000525 if (S->getParent() == 0) {
Bill Wendlingd6de6572007-06-02 09:40:07 +0000526 // C99 6.9p2: The storage-class specifiers auto and register shall not
527 // appear in the declaration specifiers in an external declaration.
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000528 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000529 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
530 R.getAsString());
Steve Naroffcf871f52007-08-28 18:45:29 +0000531 InvalidDecl = true;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000532 }
Chris Lattner776fac82007-06-09 00:53:06 +0000533 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff2fea1392007-09-02 02:04:30 +0000534 } else {
Chris Lattner776fac82007-06-09 00:53:06 +0000535 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcf871f52007-08-28 18:45:29 +0000536 }
Steve Naroffa8fd9732007-06-11 00:35:03 +0000537 // Handle attributes prior to checking for duplicates in MergeVarDecl
538 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
539 D.getAttributes());
540
Chris Lattner01564d92007-01-27 19:27:06 +0000541 // Merge the decl with the existing one if appropriate.
542 if (PrevDecl) {
543 NewVD = MergeVarDecl(NewVD, PrevDecl);
544 if (NewVD == 0) return 0;
545 }
546 New = NewVD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000547 }
Chris Lattner302b4be2006-11-19 02:31:38 +0000548
Chris Lattnere168f762006-11-10 05:29:30 +0000549 // If this has an identifier, add it to the scope stack.
550 if (II) {
Steve Naroff9324db12007-09-13 18:10:37 +0000551 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattnere168f762006-11-10 05:29:30 +0000552 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000553 S->AddDecl(New);
Chris Lattnere168f762006-11-10 05:29:30 +0000554 }
555
Steve Naroff26c8ea52007-03-21 21:08:52 +0000556 if (S->getParent() == 0)
Chris Lattner776fac82007-06-09 00:53:06 +0000557 AddTopLevelDecl(New, LastDeclarator);
Steve Narofff93b6722007-08-28 20:14:24 +0000558
559 // If any semantic error occurred, mark the decl as invalid.
560 if (D.getInvalidType() || InvalidDecl)
561 New->setInvalidDecl();
Chris Lattnere168f762006-11-10 05:29:30 +0000562
563 return New;
564}
565
Steve Naroff61091402007-09-12 14:07:44 +0000566void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff437b4d82007-09-12 20:13:48 +0000567 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff61091402007-09-12 14:07:44 +0000568 Expr *Init = static_cast<Expr *>(init);
569
Steve Naroff437b4d82007-09-12 20:13:48 +0000570 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroff61091402007-09-12 14:07:44 +0000571
Steve Naroff437b4d82007-09-12 20:13:48 +0000572 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
573 if (!VDecl) {
Steve Naroff9def2b12007-09-13 21:41:19 +0000574 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
575 diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +0000576 RealDecl->setInvalidDecl();
577 return;
578 }
Steve Naroff61091402007-09-12 14:07:44 +0000579 // Get the decls type and save a reference for later, since
580 // CheckInitializer may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +0000581 QualType DclT = VDecl->getType(), SavT = DclT;
582 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff61091402007-09-12 14:07:44 +0000583 VarDecl::StorageClass SC = BVD->getStorageClass();
584 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +0000585 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff61091402007-09-12 14:07:44 +0000586 BVD->setInvalidDecl();
587 } else if (!BVD->isInvalidDecl()) {
588 CheckInitializer(Init, DclT, SC == VarDecl::Static);
589 }
Steve Naroff437b4d82007-09-12 20:13:48 +0000590 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff61091402007-09-12 14:07:44 +0000591 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff437b4d82007-09-12 20:13:48 +0000592 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff61091402007-09-12 14:07:44 +0000593 if (!FVD->isInvalidDecl())
594 CheckInitializer(Init, DclT, true);
595 }
596 // If the type changed, it means we had an incomplete type that was
597 // completed by the initializer. For example:
598 // int ary[] = { 1, 3, 5 };
599 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff437b4d82007-09-12 20:13:48 +0000600 if (!VDecl->isInvalidDecl() && (DclT != SavT))
601 VDecl->setType(DclT);
Steve Naroff61091402007-09-12 14:07:44 +0000602
603 // Attach the initializer to the decl.
Steve Naroff437b4d82007-09-12 20:13:48 +0000604 VDecl->setInit(Init);
Steve Naroff61091402007-09-12 14:07:44 +0000605 return;
606}
607
Chris Lattner776fac82007-06-09 00:53:06 +0000608/// The declarators are chained together backwards, reverse the list.
609Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
610 // Often we have single declarators, handle them quickly.
611 Decl *Group = static_cast<Decl*>(group);
Steve Naroff61091402007-09-12 14:07:44 +0000612 if (Group == 0)
613 return 0;
614
Chris Lattner776fac82007-06-09 00:53:06 +0000615 Decl *NewGroup = 0;
Steve Naroff61091402007-09-12 14:07:44 +0000616 if (Group->getNextDeclarator() == 0)
Chris Lattner776fac82007-06-09 00:53:06 +0000617 NewGroup = Group;
Steve Naroff61091402007-09-12 14:07:44 +0000618 else { // reverse the list.
619 while (Group) {
620 Decl *Next = Group->getNextDeclarator();
621 Group->setNextDeclarator(NewGroup);
622 NewGroup = Group;
623 Group = Next;
624 }
625 }
626 // Perform semantic analysis that depends on having fully processed both
627 // the declarator and initializer.
628 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
629 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
630 if (!IDecl)
631 continue;
632 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
633 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
634 QualType T = IDecl->getType();
635
636 // C99 6.7.5.2p2: If an identifier is declared to be an object with
637 // static storage duration, it shall not have a variable length array.
638 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
639 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
640 if (VLA->getSizeExpr()) {
641 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
642 IDecl->setInvalidDecl();
643 }
644 }
645 }
646 // Block scope. C99 6.7p7: If an identifier for an object is declared with
647 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
648 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
649 if (T->isIncompleteType()) {
650 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
651 T.getAsString());
652 IDecl->setInvalidDecl();
653 }
654 }
655 // File scope. C99 6.9.2p2: A declaration of an identifier for and
656 // object that has file scope without an initializer, and without a
657 // storage-class specifier or with the storage-class specifier "static",
658 // constitutes a tentative definition. Note: A tentative definition with
659 // external linkage is valid (C99 6.2.2p5).
660 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
661 // C99 6.9.2p3: If the declaration of an identifier for an object is
662 // a tentative definition and has internal linkage (C99 6.2.2p3), the
663 // declared type shall not be an incomplete type.
664 if (T->isIncompleteType()) {
665 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
666 T.getAsString());
667 IDecl->setInvalidDecl();
668 }
669 }
Chris Lattner776fac82007-06-09 00:53:06 +0000670 }
671 return NewGroup;
672}
Steve Naroff7e6f7c22007-08-28 03:03:08 +0000673
674// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner53621a52007-06-13 20:44:40 +0000675ParmVarDecl *
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000676Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
677 Scope *FnScope) {
678 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
Chris Lattner200bdc32006-11-19 02:43:37 +0000679
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000680 IdentifierInfo *II = PI.Ident;
Chris Lattnerc284e9b2007-01-23 05:14:32 +0000681 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
682 // Can this happen for params? We already checked that they don't conflict
683 // among each other. Here they can only shadow globals, which is ok.
Chris Lattnerd2b88ab2007-07-13 03:05:23 +0000684 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Chris Lattner9561a0b2007-01-28 08:20:04 +0000685 PI.IdentLoc, FnScope)) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000686
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000687 }
688
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000689 // FIXME: Handle storage class (auto, register). No declarator?
Chris Lattner776fac82007-06-09 00:53:06 +0000690 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff773df5c2007-08-07 22:44:21 +0000691
692 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
693 // Doing the promotion here has a win and a loss. The win is the type for
694 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
695 // code generator). The loss is the orginal type isn't preserved. For example:
696 //
697 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
698 // int blockvardecl[5];
699 // sizeof(parmvardecl); // size == 4
700 // sizeof(blockvardecl); // size == 20
701 // }
702 //
703 // For expressions, all implicit conversions are captured using the
704 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
705 //
706 // FIXME: If a source translation tool needs to see the original type, then
707 // we need to consider storing both types (in ParmVarDecl)...
708 //
709 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
710 if (const ArrayType *AT = parmDeclType->getAsArrayType())
711 parmDeclType = Context.getPointerType(AT->getElementType());
712 else if (parmDeclType->isFunctionType())
713 parmDeclType = Context.getPointerType(parmDeclType);
714
715 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffcf871f52007-08-28 18:45:29 +0000716 VarDecl::None, 0);
717 if (PI.InvalidType)
718 New->setInvalidDecl();
719
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000720 // If this has an identifier, add it to the scope stack.
721 if (II) {
Steve Naroff9324db12007-09-13 18:10:37 +0000722 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000723 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000724 FnScope->AddDecl(New);
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000725 }
Chris Lattner229ce602006-11-21 01:21:07 +0000726
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000727 return New;
728}
729
730
731Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner229ce602006-11-21 01:21:07 +0000732 assert(CurFunctionDecl == 0 && "Function parsing confused");
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000733 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
734 "Not a function declarator!");
735 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
736
737 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
738 // for a K&R function.
739 if (!FTI.hasPrototype) {
740 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
741 if (FTI.ArgInfo[i].TypeInfo == 0) {
Chris Lattner843c5922007-06-10 23:40:34 +0000742 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000743 FTI.ArgInfo[i].Ident->getName());
744 // Implicitly declare the argument as type 'int' for lack of a better
745 // type.
746 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
747 }
748 }
749
750 // Since this is a function definition, act as though we have information
751 // about the arguments.
752 FTI.hasPrototype = true;
Chris Lattner2114d5e2006-12-04 07:40:24 +0000753 } else {
754 // FIXME: Diagnose arguments without names in C.
755
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000756 }
757
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000758 Scope *GlobalScope = FnBodyScope->getParent();
759
760 FunctionDecl *FD =
Steve Naroff61091402007-09-12 14:07:44 +0000761 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0));
Chris Lattner229ce602006-11-21 01:21:07 +0000762 CurFunctionDecl = FD;
Chris Lattner2114d5e2006-12-04 07:40:24 +0000763
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000764 // Create Decl objects for each parameter, adding them to the FunctionDecl.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000765 llvm::SmallVector<ParmVarDecl*, 16> Params;
Chris Lattnerf61c8a82007-01-21 19:04:43 +0000766
767 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
768 // no arguments, not a function that takes a single void argument.
769 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
770 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
Chris Lattner99d31772007-01-21 22:37:37 +0000771 // empty arg list, don't push any params.
Chris Lattnerf61c8a82007-01-21 19:04:43 +0000772 } else {
773 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
774 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
775 }
Chris Lattner2114d5e2006-12-04 07:40:24 +0000776
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000777 FD->setParams(&Params[0], Params.size());
Chris Lattner2114d5e2006-12-04 07:40:24 +0000778
Chris Lattnere168f762006-11-10 05:29:30 +0000779 return FD;
780}
781
Chris Lattner229ce602006-11-21 01:21:07 +0000782Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
783 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
784 FD->setBody((Stmt*)Body);
785
786 assert(FD == CurFunctionDecl && "Function parsing confused");
787 CurFunctionDecl = 0;
Chris Lattnere2473062007-05-28 06:28:18 +0000788
789 // Verify and clean out per-function state.
790
791 // Check goto/label use.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000792 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
793 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
Chris Lattnere2473062007-05-28 06:28:18 +0000794 // Verify that we have no forward references left. If so, there was a goto
795 // or address of a label taken, but no definition of it. Label fwd
796 // definitions are indicated with a null substmt.
797 if (I->second->getSubStmt() == 0) {
798 LabelStmt *L = I->second;
799 // Emit error.
Chris Lattnereefa10e2007-05-28 06:56:27 +0000800 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
Chris Lattnere2473062007-05-28 06:28:18 +0000801
802 // At this point, we have gotos that use the bogus label. Stitch it into
803 // the function body so that they aren't leaked and that the AST is well
804 // formed.
805 L->setSubStmt(new NullStmt(L->getIdentLoc()));
806 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
807 }
808 }
809 LabelMap.clear();
810
Chris Lattner229ce602006-11-21 01:21:07 +0000811 return FD;
812}
813
814
Chris Lattnerac18be92006-11-20 06:49:47 +0000815/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
816/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
817Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
818 Scope *S) {
819 if (getLangOptions().C99) // Extension in C99.
820 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
821 else // Legal in C90, but warn about it.
822 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
823
824 // FIXME: handle stuff like:
825 // void foo() { extern float X(); }
826 // void bar() { X(); } <-- implicit decl for X in another scope.
827
828 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +0000829 const char *Dummy;
Chris Lattnerac18be92006-11-20 06:49:47 +0000830 DeclSpec DS;
Chris Lattnerb20e8942006-11-28 05:30:29 +0000831 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
Chris Lattnerb055f2d2007-02-11 08:19:57 +0000832 Error = Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +0000833 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +0000834 Declarator D(DS, Declarator::BlockContext);
Chris Lattnercbc426d2006-12-02 06:43:02 +0000835 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
Chris Lattnerac18be92006-11-20 06:49:47 +0000836 D.SetIdentifier(&II, Loc);
837
Chris Lattner62d2e662007-01-28 00:21:37 +0000838 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000839 if (Scope *FnS = S->getFnParent())
840 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner62d2e662007-01-28 00:21:37 +0000841 while (S->getParent())
842 S = S->getParent();
Chris Lattnerac18be92006-11-20 06:49:47 +0000843
Steve Naroff61091402007-09-12 14:07:44 +0000844 return static_cast<Decl*>(ParseDeclarator(S, D, 0));
Chris Lattnerac18be92006-11-20 06:49:47 +0000845}
846
Chris Lattner302b4be2006-11-19 02:31:38 +0000847
Chris Lattner776fac82007-06-09 00:53:06 +0000848TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
849 Decl *LastDeclarator) {
850 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Chris Lattner302b4be2006-11-19 02:31:38 +0000851
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000852 QualType T = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +0000853 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner0d8b1a12006-11-20 04:34:45 +0000854
Chris Lattner18b19622007-01-22 07:39:13 +0000855 // Scope manipulation handled by caller.
Steve Narofff93b6722007-08-28 20:14:24 +0000856 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
857 T, LastDeclarator);
858 if (D.getInvalidType())
859 NewTD->setInvalidDecl();
860 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +0000861}
862
Steve Naroff09bf8152007-09-06 21:24:23 +0000863Sema::DeclTy *Sema::ObjcStartClassInterface(SourceLocation AtInterfaceLoc,
864 IdentifierInfo *ClassName, SourceLocation ClassLoc,
865 IdentifierInfo *SuperName, SourceLocation SuperLoc,
866 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
867 AttributeList *AttrList) {
868 assert(ClassName && "Missing class identifier");
869 ObjcInterfaceDecl *IDecl;
870
871 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, ClassName);
872
873 // Chain & install the interface decl into the identifier.
Steve Naroff9324db12007-09-13 18:10:37 +0000874 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
Steve Naroff09bf8152007-09-06 21:24:23 +0000875 ClassName->setFETokenInfo(IDecl);
876 return IDecl;
877}
878
Fariborz Jahanian6812cbb2007-09-13 20:56:13 +0000879void Sema::ObjcAddInstanceVariable(DeclTy *ClassDecl, DeclTy **Ivar,
880 unsigned numIvars,
881 tok::ObjCKeywordKind *visibility) {
882 assert((ClassDecl && numIvars) && "missing class or instance variable");
Steve Narofff2fb4ad2007-09-11 21:17:26 +0000883 ObjcInterfaceDecl *OInterface = dyn_cast<ObjcInterfaceDecl>(
884 static_cast<Decl *>(ClassDecl));
Fariborz Jahanian6812cbb2007-09-13 20:56:13 +0000885 assert (OInterface && "mistyped class");
886 for (unsigned i = 0; i != numIvars; ++i) {
887 ObjcIvarDecl *OIvar = dyn_cast<ObjcIvarDecl>(static_cast<Decl *>(Ivar[i]));
888 tok::ObjCKeywordKind ivarVisibility = visibility[i];
Steve Narofff2fb4ad2007-09-11 21:17:26 +0000889
Fariborz Jahanian6812cbb2007-09-13 20:56:13 +0000890 assert(OIvar && "mistyped instance variable");
Steve Narofff2fb4ad2007-09-11 21:17:26 +0000891
Fariborz Jahanian6812cbb2007-09-13 20:56:13 +0000892 switch (ivarVisibility) {
893 case tok::objc_private:
894 OIvar->setAccessControl(ObjcIvarDecl::Private);
895 break;
896 case tok::objc_public:
897 OIvar->setAccessControl(ObjcIvarDecl::Public);
898 break;
899 case tok::objc_protected:
900 OIvar->setAccessControl(ObjcIvarDecl::Protected);
901 break;
902 case tok::objc_package:
903 OIvar->setAccessControl(ObjcIvarDecl::Package);
904 break;
905 default:
906 OIvar->setAccessControl(ObjcIvarDecl::None);
907 break;
908 }
Steve Narofff2fb4ad2007-09-11 21:17:26 +0000909 }
910 // FIXME: add to the class...
911}
912
Steve Naroff09bf8152007-09-06 21:24:23 +0000913/// ObjcClassDeclaration -
914/// Scope will always be top level file scope.
915Action::DeclTy *
916Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
917 IdentifierInfo **IdentList, unsigned NumElts) {
918 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
919
920 for (unsigned i = 0; i != NumElts; ++i) {
921 ObjcInterfaceDecl *IDecl;
922
Steve Naroffacb1e742007-09-10 20:51:04 +0000923 // FIXME: before we create one, look up the interface decl in a hash table.
Steve Naroff09bf8152007-09-06 21:24:23 +0000924 IDecl = new ObjcInterfaceDecl(SourceLocation(), IdentList[i], true);
925 // Chain & install the interface decl into the identifier.
Steve Naroff9324db12007-09-13 18:10:37 +0000926 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
Steve Naroff09bf8152007-09-06 21:24:23 +0000927 IdentList[i]->setFETokenInfo(IDecl);
928
929 // Remember that this needs to be removed when the scope is popped.
930 S->AddDecl(IdentList[i]);
931
932 CDecl->setInterfaceDecl((int)i, IDecl);
933 }
934 return CDecl;
935}
936
Chris Lattner18b19622007-01-22 07:39:13 +0000937
Chris Lattner1300fb92007-01-23 23:42:53 +0000938/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
939/// former case, Name will be non-null. In the later case, Name will be null.
940/// TagType indicates what kind of tag this is. TK indicates whether this is a
941/// reference/declaration/definition of a tag.
Chris Lattner7b9ace62007-01-23 20:11:08 +0000942Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000943 SourceLocation KWLoc, IdentifierInfo *Name,
Steve Naroffb3096442007-06-09 03:47:53 +0000944 SourceLocation NameLoc, AttributeList *Attr) {
Chris Lattner8799cf22007-01-23 01:57:16 +0000945 // If this is a use of an existing tag, it must have a name.
Chris Lattner7b9ace62007-01-23 20:11:08 +0000946 assert((Name != 0 || TK == TK_Definition) &&
947 "Nameless record must be a definition!");
Chris Lattner8799cf22007-01-23 01:57:16 +0000948
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000949 Decl::Kind Kind;
Chris Lattnerbf0b7982007-01-23 04:27:41 +0000950 switch (TagType) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000951 default: assert(0 && "Unknown tag type!");
Chris Lattnerbf0b7982007-01-23 04:27:41 +0000952 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
953 case DeclSpec::TST_union: Kind = Decl::Union; break;
954//case DeclSpec::TST_class: Kind = Decl::Class; break;
955 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000956 }
Chris Lattner7e783a12007-01-23 02:05:42 +0000957
Chris Lattner18b19622007-01-22 07:39:13 +0000958 // If this is a named struct, check to see if there was a previous forward
959 // declaration or definition.
Chris Lattner7b9ace62007-01-23 20:11:08 +0000960 if (TagDecl *PrevDecl =
Chris Lattner9561a0b2007-01-28 08:20:04 +0000961 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
962 NameLoc, S))) {
Chris Lattner8799cf22007-01-23 01:57:16 +0000963
964 // If this is a use of a previous tag, or if the tag is already declared in
965 // the same scope (so that the definition/declaration completes or
966 // rementions the tag), reuse the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +0000967 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
Chris Lattner7e783a12007-01-23 02:05:42 +0000968 // Make sure that this wasn't declared as an enum and now used as a struct
969 // or something similar.
970 if (PrevDecl->getKind() != Kind) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000971 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
Chris Lattner7e783a12007-01-23 02:05:42 +0000972 Diag(PrevDecl->getLocation(), diag::err_previous_use);
973 }
Chris Lattner7b9ace62007-01-23 20:11:08 +0000974
975 // If this is a use or a forward declaration, we're good.
976 if (TK != TK_Definition)
977 return PrevDecl;
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000978
Chris Lattner7b9ace62007-01-23 20:11:08 +0000979 // Diagnose attempts to redefine a tag.
980 if (PrevDecl->isDefinition()) {
981 Diag(NameLoc, diag::err_redefinition, Name->getName());
982 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
983 // If this is a redefinition, recover by making this struct be
984 // anonymous, which will make any later references get the previous
985 // definition.
986 Name = 0;
987 } else {
988 // Okay, this is definition of a previously declared or referenced tag.
989 // Move the location of the decl to be the definition site.
990 PrevDecl->setLocation(NameLoc);
Chris Lattner7b9ace62007-01-23 20:11:08 +0000991 return PrevDecl;
992 }
Chris Lattner8799cf22007-01-23 01:57:16 +0000993 }
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000994 // If we get here, this is a definition of a new struct type in a nested
995 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
996 // type.
Chris Lattner18b19622007-01-22 07:39:13 +0000997 }
998
Chris Lattnerbf0b7982007-01-23 04:27:41 +0000999 // If there is an identifier, use the location of the identifier as the
1000 // location of the decl, otherwise use the location of the struct/union
1001 // keyword.
1002 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1003
Chris Lattner18b19622007-01-22 07:39:13 +00001004 // Otherwise, if this is the first time we've seen this tag, create the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001005 TagDecl *New;
Chris Lattner720a0542007-01-25 00:44:24 +00001006 switch (Kind) {
1007 default: assert(0 && "Unknown tag kind!");
Chris Lattner5f521502007-01-25 06:27:24 +00001008 case Decl::Enum:
Chris Lattner776fac82007-06-09 00:53:06 +00001009 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1010 // enum X { A, B, C } D; D should chain to X.
1011 New = new EnumDecl(Loc, Name, 0);
Chris Lattner5f521502007-01-25 06:27:24 +00001012 // If this is an undefined enum, warn.
Chris Lattnerc1915e22007-01-25 07:29:02 +00001013 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Chris Lattner5f521502007-01-25 06:27:24 +00001014 break;
Chris Lattner720a0542007-01-25 00:44:24 +00001015 case Decl::Union:
1016 case Decl::Struct:
1017 case Decl::Class:
Chris Lattner776fac82007-06-09 00:53:06 +00001018 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1019 // struct X { int A; } D; D should chain to X.
1020 New = new RecordDecl(Kind, Loc, Name, 0);
Chris Lattner720a0542007-01-25 00:44:24 +00001021 break;
1022 }
Chris Lattner18b19622007-01-22 07:39:13 +00001023
1024 // If this has an identifier, add it to the scope stack.
1025 if (Name) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001026 // The scope passed in may not be a decl scope. Zip up the scope tree until
1027 // we find one that is.
1028 while ((S->getFlags() & Scope::DeclScope) == 0)
1029 S = S->getParent();
1030
1031 // Add it to the decl chain.
Steve Naroff9324db12007-09-13 18:10:37 +00001032 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner18b19622007-01-22 07:39:13 +00001033 Name->setFETokenInfo(New);
1034 S->AddDecl(New);
1035 }
1036
1037 return New;
1038}
Chris Lattner1300fb92007-01-23 23:42:53 +00001039
1040/// ParseField - Each field of a struct/union/class is passed into this in order
1041/// to create a FieldDecl object for it.
1042Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
1043 SourceLocation DeclStart,
1044 Declarator &D, ExprTy *BitfieldWidth) {
1045 IdentifierInfo *II = D.getIdentifier();
1046 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner1300fb92007-01-23 23:42:53 +00001047 SourceLocation Loc = DeclStart;
1048 if (II) Loc = D.getIdentifierLoc();
1049
Chris Lattner62d2e662007-01-28 00:21:37 +00001050 // FIXME: Unnamed fields can be handled in various different ways, for
1051 // example, unnamed unions inject all members into the struct namespace!
1052
1053
Chris Lattner1300fb92007-01-23 23:42:53 +00001054 if (BitWidth) {
1055 // TODO: Validate.
Steve Narofff84d11f2007-05-23 21:48:04 +00001056 //printf("WARNING: BITFIELDS IGNORED!\n");
Chris Lattner1300fb92007-01-23 23:42:53 +00001057
1058 // 6.7.2.1p3
1059 // 6.7.2.1p4
1060
1061 } else {
1062 // Not a bitfield.
1063
1064 // validate II.
1065
1066 }
1067
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001068 QualType T = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +00001069 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1070 bool InvalidDecl = false;
Steve Naroff096dd942007-08-31 17:20:07 +00001071
Steve Naroff8eeeb132007-05-08 21:09:37 +00001072 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1073 // than a variably modified type.
Steve Naroff096dd942007-08-31 17:20:07 +00001074 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1075 Diag(Loc, diag::err_typecheck_illegal_vla,
1076 VAT->getSizeExpr()->getSourceRange());
1077 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +00001078 }
Chris Lattner776fac82007-06-09 00:53:06 +00001079 // FIXME: Chain fielddecls together.
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001080 FieldDecl *NewFD;
1081
1082 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
1083 NewFD = new FieldDecl(Loc, II, T, 0);
1084 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl)))
1085 NewFD = new ObjcIvarDecl(Loc, II, T, 0);
1086 else
1087 assert(0 && "Sema::ParseField(): Unknown TagDecl");
1088
Steve Narofff93b6722007-08-28 20:14:24 +00001089 if (D.getInvalidType() || InvalidDecl)
1090 NewFD->setInvalidDecl();
1091 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00001092}
1093
1094void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
1095 DeclTy **Fields, unsigned NumFields) {
Chris Lattnerc1915e22007-01-25 07:29:02 +00001096 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
Chris Lattner1300fb92007-01-23 23:42:53 +00001097 if (Record->isDefinition()) {
1098 // Diagnose code like:
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001099 // struct S { struct S {} X; };
Chris Lattner1300fb92007-01-23 23:42:53 +00001100 // We discover this when we complete the outer S. Reject and ignore the
1101 // outer S.
1102 Diag(Record->getLocation(), diag::err_nested_redefinition,
1103 Record->getKindName());
1104 Diag(RecLoc, diag::err_previous_definition);
1105 return;
1106 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001107
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001108 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00001109 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +00001110 llvm::SmallVector<FieldDecl*, 32> RecFields;
1111 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Chris Lattnere5a66562007-01-25 22:48:42 +00001112
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001113 for (unsigned i = 0; i != NumFields; ++i) {
1114 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1115 if (!FD) continue; // Already issued a diagnostic.
Chris Lattner720a0542007-01-25 00:44:24 +00001116
1117 // Get the type for the field.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001118 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner720a0542007-01-25 00:44:24 +00001119
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001120 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001121 if (FDTy->isFunctionType()) {
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001122 Diag(FD->getLocation(), diag::err_field_declared_as_function,
1123 FD->getName());
Chris Lattner82625602007-01-24 02:26:21 +00001124 delete FD;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001125 continue;
1126 }
1127
Chris Lattner82625602007-01-24 02:26:21 +00001128 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
Chris Lattner720a0542007-01-25 00:44:24 +00001129 if (FDTy->isIncompleteType()) {
Chris Lattner82625602007-01-24 02:26:21 +00001130 if (i != NumFields-1 || // ... that the last member ...
1131 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner0fd893e2007-07-31 21:33:24 +00001132 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner82625602007-01-24 02:26:21 +00001133 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1134 delete FD;
1135 continue;
1136 }
Chris Lattner720a0542007-01-25 00:44:24 +00001137 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner82625602007-01-24 02:26:21 +00001138 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1139 FD->getName());
1140 delete FD;
1141 continue;
1142 }
Chris Lattner720a0542007-01-25 00:44:24 +00001143
1144 // Okay, we have a legal flexible array member at the end of the struct.
Chris Lattner41943152007-01-25 04:52:46 +00001145 Record->setHasFlexibleArrayMember(true);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001146 }
Chris Lattner720a0542007-01-25 00:44:24 +00001147
1148
1149 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1150 /// field of another structure or the element of an array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001151 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner720a0542007-01-25 00:44:24 +00001152 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1153 // If this is a member of a union, then entire union becomes "flexible".
1154 if (Record->getKind() == Decl::Union) {
Chris Lattner41943152007-01-25 04:52:46 +00001155 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00001156 } else {
1157 // If this is a struct/class and this is not the last element, reject
1158 // it. Note that GCC supports variable sized arrays in the middle of
1159 // structures.
1160 if (i != NumFields-1) {
1161 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1162 FD->getName());
1163 delete FD;
1164 continue;
1165 }
1166
1167 // We support flexible arrays at the end of structs in other structs
1168 // as an extension.
1169 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1170 FD->getName());
Chris Lattner41943152007-01-25 04:52:46 +00001171 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00001172 }
1173 }
1174 }
1175
Chris Lattner82625602007-01-24 02:26:21 +00001176 // Keep track of the number of named members.
Chris Lattnere5a66562007-01-25 22:48:42 +00001177 if (IdentifierInfo *II = FD->getIdentifier()) {
1178 // Detect duplicate member names.
Chris Lattnerbaf33662007-01-27 02:14:08 +00001179 if (!FieldIDs.insert(II)) {
Chris Lattnere5a66562007-01-25 22:48:42 +00001180 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1181 // Find the previous decl.
1182 SourceLocation PrevLoc;
1183 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1184 assert(i != e && "Didn't find previous def!");
1185 if (RecFields[i]->getIdentifier() == II) {
1186 PrevLoc = RecFields[i]->getLocation();
1187 break;
1188 }
1189 }
1190 Diag(PrevLoc, diag::err_previous_definition);
1191 delete FD;
1192 continue;
1193 }
Chris Lattner82625602007-01-24 02:26:21 +00001194 ++NumNamedMembers;
Chris Lattnere5a66562007-01-25 22:48:42 +00001195 }
Chris Lattner41943152007-01-25 04:52:46 +00001196
1197 // Remember good fields.
1198 RecFields.push_back(FD);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001199 }
Chris Lattner82625602007-01-24 02:26:21 +00001200
1201
1202 // Okay, we successfully defined 'Record'.
Chris Lattner41943152007-01-25 04:52:46 +00001203 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattner1300fb92007-01-23 23:42:53 +00001204}
1205
Fariborz Jahanian33d03742007-09-10 20:33:04 +00001206void Sema::ObjcAddMethodsToClass(DeclTy *ClassDecl,
1207 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahaniancfb31fa2007-09-12 18:23:47 +00001208 // FIXME: Fix this when we can handle methods declared in protocols.
1209 // See Parser::ParseObjCAtProtocolDeclaration
1210 if (!ClassDecl)
1211 return;
Fariborz Jahanian33d03742007-09-10 20:33:04 +00001212 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1213 static_cast<Decl*>(ClassDecl));
1214 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1215 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1216
1217 for (unsigned i = 0; i < allNum; i++ ) {
1218 ObjcMethodDecl *Method =
1219 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1220 if (!Method) continue; // Already issued a diagnostic.
1221 if (Method->isInstance())
1222 insMethods.push_back(Method);
1223 else
1224 clsMethods.push_back(Method);
1225 }
1226 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1227 &clsMethods[0], clsMethods.size());
Fariborz Jahanian33d03742007-09-10 20:33:04 +00001228 return;
1229}
1230
Fariborz Jahaniancfb31fa2007-09-12 18:23:47 +00001231Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
1232 tok::TokenKind MethodType, TypeTy *ReturnType,
1233 ObjcKeywordInfo *Keywords, unsigned NumKeywords,
1234 AttributeList *AttrList) {
1235 assert(NumKeywords && "Selector must be specified");
1236 // FIXME: SelectorName to be changed to comform to objc's abi for method names
1237 IdentifierInfo *SelectorName = Keywords[0].SelectorName;
1238 llvm::SmallVector<ParmVarDecl*, 16> Params;
1239
1240 for (unsigned i = 0; i < NumKeywords; i++) {
1241 ObjcKeywordInfo *arg = &Keywords[i];
1242 // FIXME: arg->AttrList must be stored too!
1243 ParmVarDecl* Param = new ParmVarDecl(arg->ColonLoc, arg->ArgumentName,
1244 QualType::getFromOpaquePtr(arg->TypeInfo),
1245 VarDecl::None, 0);
1246 // FIXME: 'InvalidType' does not get set by caller yet.
1247 if (arg->InvalidType)
1248 Param->setInvalidDecl();
1249 Params.push_back(Param);
1250 }
1251 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
1252 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc,
1253 SelectorName, resultDeclType,
1254 0, -1, AttrList, MethodType == tok::minus);
1255 ObjcMethod->setMethodParams(&Params[0], NumKeywords);
1256 return ObjcMethod;
1257}
1258
1259Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
1260 tok::TokenKind MethodType, TypeTy *ReturnType,
1261 IdentifierInfo *SelectorName, AttributeList *AttrList) {
1262 // FIXME: SelectorName to be changed to comform to objc's abi for method names
1263 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
1264 return new ObjcMethodDecl(MethodLoc, SelectorName, resultDeclType, 0, -1,
1265 AttrList, MethodType == tok::minus);
1266}
1267
Chris Lattner4ef40012007-06-11 01:28:17 +00001268Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
1269 DeclTy *lastEnumConst,
Chris Lattnerc1915e22007-01-25 07:29:02 +00001270 SourceLocation IdLoc, IdentifierInfo *Id,
Chris Lattner4ef40012007-06-11 01:28:17 +00001271 SourceLocation EqualLoc, ExprTy *val) {
1272 theEnumDecl = theEnumDecl; // silence unused warning.
1273 EnumConstantDecl *LastEnumConst =
1274 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1275 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00001276
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001277 // The scope passed in may not be a decl scope. Zip up the scope tree until
1278 // we find one that is.
1279 while ((S->getFlags() & Scope::DeclScope) == 0)
1280 S = S->getParent();
1281
Chris Lattner8116d1b2007-01-25 22:38:29 +00001282 // Verify that there isn't already something declared with this name in this
1283 // scope.
Steve Naroff9def2b12007-09-13 21:41:19 +00001284 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1285 IdLoc, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00001286 if (S->isDeclScope(PrevDecl)) {
1287 if (isa<EnumConstantDecl>(PrevDecl))
1288 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1289 else
1290 Diag(IdLoc, diag::err_redefinition, Id->getName());
1291 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner4ef40012007-06-11 01:28:17 +00001292 // FIXME: Don't leak memory: delete Val;
Chris Lattner8116d1b2007-01-25 22:38:29 +00001293 return 0;
1294 }
1295 }
Chris Lattner4ef40012007-06-11 01:28:17 +00001296
Chris Lattner23b7eb62007-06-15 23:05:46 +00001297 llvm::APSInt EnumVal(32);
Chris Lattner4ef40012007-06-11 01:28:17 +00001298 QualType EltTy;
1299 if (Val) {
Chris Lattner0515e4b2007-08-27 21:16:18 +00001300 // Make sure to promote the operand type to int.
1301 UsualUnaryConversions(Val);
1302
Chris Lattner4ef40012007-06-11 01:28:17 +00001303 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1304 SourceLocation ExpLoc;
Chris Lattner0e9d6222007-07-15 23:26:56 +00001305 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Chris Lattner4ef40012007-06-11 01:28:17 +00001306 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1307 Id->getName());
1308 // FIXME: Don't leak memory: delete Val;
Chris Lattnerf283a372007-08-27 17:37:24 +00001309 Val = 0; // Just forget about it.
Chris Lattnerc92bc4c2007-08-29 16:03:41 +00001310 } else {
1311 EltTy = Val->getType();
Chris Lattner4ef40012007-06-11 01:28:17 +00001312 }
Chris Lattnerf283a372007-08-27 17:37:24 +00001313 }
1314
1315 if (!Val) {
1316 if (LastEnumConst) {
1317 // Assign the last value + 1.
1318 EnumVal = LastEnumConst->getInitVal();
1319 ++EnumVal;
Chris Lattner0515e4b2007-08-27 21:16:18 +00001320
1321 // Check for overflow on increment.
1322 if (EnumVal < LastEnumConst->getInitVal())
1323 Diag(IdLoc, diag::warn_enum_value_overflow);
1324
Chris Lattnerf283a372007-08-27 17:37:24 +00001325 EltTy = LastEnumConst->getType();
1326 } else {
1327 // First value, set to zero.
1328 EltTy = Context.IntTy;
Chris Lattner9cf21c52007-09-04 02:45:27 +00001329 EnumVal.zextOrTrunc(
1330 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerf283a372007-08-27 17:37:24 +00001331 }
Steve Naroff63969212007-05-07 21:22:42 +00001332 }
Chris Lattner4ef40012007-06-11 01:28:17 +00001333
Chris Lattner4ef40012007-06-11 01:28:17 +00001334 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1335 LastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +00001336
1337 // Register this decl in the current scope stack.
Steve Naroff9324db12007-09-13 18:10:37 +00001338 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner8116d1b2007-01-25 22:38:29 +00001339 Id->setFETokenInfo(New);
1340 S->AddDecl(New);
1341 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001342}
1343
1344void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1345 DeclTy **Elements, unsigned NumElements) {
1346 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1347 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1348
Chris Lattner67933c02007-08-28 05:10:31 +00001349 // TODO: If the result value doesn't fit in an int, it must be a long or long
1350 // long value. ISO C does not support this, but GCC does as an extension,
1351 // emit a warning.
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001352 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner67933c02007-08-28 05:10:31 +00001353
1354
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001355 // Verify that all the values are okay, compute the size of the values, and
1356 // reverse the list.
1357 unsigned NumNegativeBits = 0;
1358 unsigned NumPositiveBits = 0;
1359
1360 // Keep track of whether all elements have type int.
1361 bool AllElementsInt = true;
1362
Chris Lattner4ef40012007-06-11 01:28:17 +00001363 EnumConstantDecl *EltList = 0;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001364 for (unsigned i = 0; i != NumElements; ++i) {
1365 EnumConstantDecl *ECD =
1366 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1367 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnerbf478cb2007-08-28 05:27:00 +00001368
1369 // If the enum value doesn't fit in an int, emit an extension warning.
1370 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1371 "Should have promoted value to int");
1372 const llvm::APSInt &InitVal = ECD->getInitVal();
1373 if (InitVal.getBitWidth() > IntWidth) {
1374 llvm::APSInt V(InitVal);
1375 V.trunc(IntWidth);
1376 V.extend(InitVal.getBitWidth());
1377 if (V != InitVal)
1378 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1379 InitVal.toString());
1380 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001381
1382 // Keep track of the size of positive and negative values.
1383 if (InitVal.isUnsigned() || !InitVal.isNegative())
1384 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1385 else
1386 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00001387
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001388 // Keep track of whether every enum element has type int (very commmon).
1389 if (AllElementsInt)
1390 AllElementsInt = ECD->getType() == Context.IntTy;
1391
Chris Lattner4ef40012007-06-11 01:28:17 +00001392 ECD->setNextDeclarator(EltList);
1393 EltList = ECD;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001394 }
1395
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001396 // Figure out the type that should be used for this enum.
1397 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1398 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001399 unsigned BestWidth;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001400
1401 if (NumNegativeBits) {
1402 // If there is a negative value, figure out the smallest integer type (of
1403 // int/long/longlong) that fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001404 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001405 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001406 BestWidth = IntWidth;
1407 } else {
1408 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1409 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001410 BestType = Context.LongTy;
1411 else {
Chris Lattner3a370bf2007-08-29 17:31:48 +00001412 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1413 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001414 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1415 BestType = Context.LongLongTy;
1416 }
1417 }
1418 } else {
1419 // If there is no negative value, figure out which of uint, ulong, ulonglong
1420 // fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001421 if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001422 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001423 BestWidth = IntWidth;
1424 } else if (NumPositiveBits <=
1425 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001426 BestType = Context.UnsignedLongTy;
1427 else {
Chris Lattner3a370bf2007-08-29 17:31:48 +00001428 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1429 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001430 "How could an initializer get larger than ULL?");
1431 BestType = Context.UnsignedLongLongTy;
1432 }
1433 }
1434
Chris Lattner3a370bf2007-08-29 17:31:48 +00001435 // Loop over all of the enumerator constants, changing their types to match
1436 // the type of the enum if needed.
1437 for (unsigned i = 0; i != NumElements; ++i) {
1438 EnumConstantDecl *ECD =
1439 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1440 if (!ECD) continue; // Already issued a diagnostic.
1441
1442 // Standard C says the enumerators have int type, but we allow, as an
1443 // extension, the enumerators to be larger than int size. If each
1444 // enumerator value fits in an int, type it as an int, otherwise type it the
1445 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1446 // that X has type 'int', not 'unsigned'.
1447 if (ECD->getType() == Context.IntTy)
1448 continue; // Already int type.
1449
1450 // Determine whether the value fits into an int.
1451 llvm::APSInt InitVal = ECD->getInitVal();
1452 bool FitsInInt;
1453 if (InitVal.isUnsigned() || !InitVal.isNegative())
1454 FitsInInt = InitVal.getActiveBits() < IntWidth;
1455 else
1456 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1457
1458 // If it fits into an integer type, force it. Otherwise force it to match
1459 // the enum decl type.
1460 QualType NewTy;
1461 unsigned NewWidth;
1462 bool NewSign;
1463 if (FitsInInt) {
1464 NewTy = Context.IntTy;
1465 NewWidth = IntWidth;
1466 NewSign = true;
1467 } else if (ECD->getType() == BestType) {
1468 // Already the right type!
1469 continue;
1470 } else {
1471 NewTy = BestType;
1472 NewWidth = BestWidth;
1473 NewSign = BestType->isSignedIntegerType();
1474 }
1475
1476 // Adjust the APSInt value.
1477 InitVal.extOrTrunc(NewWidth);
1478 InitVal.setIsSigned(NewSign);
1479 ECD->setInitVal(InitVal);
1480
1481 // Adjust the Expr initializer and type.
1482 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1483 ECD->setType(NewTy);
1484 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001485
Chris Lattner1c1f9322007-08-28 18:24:31 +00001486 Enum->defineElements(EltList, BestType);
Chris Lattnerc1915e22007-01-25 07:29:02 +00001487}
Chris Lattner1300fb92007-01-23 23:42:53 +00001488
Steve Naroff26c8ea52007-03-21 21:08:52 +00001489void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1490 if (!current) return;
1491
1492 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1493 // remember this in the LastInGroupList list.
Chris Lattner776fac82007-06-09 00:53:06 +00001494 if (last)
Steve Naroff26c8ea52007-03-21 21:08:52 +00001495 LastInGroupList.push_back((Decl*)last);
Steve Naroff26c8ea52007-03-21 21:08:52 +00001496}
Steve Naroffa8fd9732007-06-11 00:35:03 +00001497
1498void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1499 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1500 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001501 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001502 if (!newType.isNull()) // install the new vector type into the decl
1503 vDecl->setType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001504 }
1505 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001506 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1507 rawAttr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001508 if (!newType.isNull()) // install the new vector type into the decl
1509 tDecl->setUnderlyingType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001510 }
1511 }
Steve Naroff91fcddb2007-07-18 18:00:27 +00001512 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001513 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1514 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1515 else
Steve Naroff91fcddb2007-07-18 18:00:27 +00001516 Diag(rawAttr->getAttributeLoc(),
1517 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001518 }
Steve Naroffa8fd9732007-06-11 00:35:03 +00001519 // FIXME: add other attributes...
1520}
1521
1522void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1523 AttributeList *declarator_postfix) {
1524 while (declspec_prefix) {
1525 HandleDeclAttribute(New, declspec_prefix);
1526 declspec_prefix = declspec_prefix->getNext();
1527 }
1528 while (declarator_postfix) {
1529 HandleDeclAttribute(New, declarator_postfix);
1530 declarator_postfix = declarator_postfix->getNext();
1531 }
1532}
1533
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001534void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1535 AttributeList *rawAttr) {
1536 QualType curType = tDecl->getUnderlyingType();
Steve Naroff91fcddb2007-07-18 18:00:27 +00001537 // check the attribute arugments.
1538 if (rawAttr->getNumArgs() != 1) {
1539 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1540 std::string("1"));
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001541 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001542 }
1543 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1544 llvm::APSInt vecSize(32);
1545 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1546 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1547 sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001548 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001549 }
1550 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1551 // in conjunction with complex types (pointers, arrays, functions, etc.).
1552 Type *canonType = curType.getCanonicalType().getTypePtr();
1553 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1554 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1555 curType.getCanonicalType().getAsString());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001556 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001557 }
1558 // unlike gcc's vector_size attribute, the size is specified as the
1559 // number of elements, not the number of bytes.
Chris Lattner9cf21c52007-09-04 02:45:27 +00001560 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001561
1562 if (vectorSize == 0) {
1563 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1564 sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001565 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001566 }
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001567 // Instantiate/Install the vector type, the number of elements is > 0.
1568 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1569 // Remember this typedef decl, we will need it later for diagnostics.
1570 OCUVectorDecls.push_back(tDecl);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001571}
1572
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001573QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattner983a8bb2007-07-13 22:13:22 +00001574 AttributeList *rawAttr) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001575 // check the attribute arugments.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001576 if (rawAttr->getNumArgs() != 1) {
1577 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1578 std::string("1"));
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001579 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001580 }
1581 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
Chris Lattner23b7eb62007-06-15 23:05:46 +00001582 llvm::APSInt vecSize(32);
Chris Lattner0e9d6222007-07-15 23:26:56 +00001583 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Steve Naroffa8fd9732007-06-11 00:35:03 +00001584 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1585 sizeExpr->getSourceRange());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001586 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001587 }
1588 // navigate to the base type - we need to provide for vector pointers,
1589 // vector arrays, and functions returning vectors.
1590 Type *canonType = curType.getCanonicalType().getTypePtr();
1591
Steve Naroff91fcddb2007-07-18 18:00:27 +00001592 if (canonType->isPointerType() || canonType->isArrayType() ||
1593 canonType->isFunctionType()) {
1594 assert(1 && "HandleVector(): Complex type construction unimplemented");
1595 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1596 do {
1597 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1598 canonType = PT->getPointeeType().getTypePtr();
1599 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1600 canonType = AT->getElementType().getTypePtr();
1601 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1602 canonType = FT->getResultType().getTypePtr();
1603 } while (canonType->isPointerType() || canonType->isArrayType() ||
1604 canonType->isFunctionType());
1605 */
Steve Naroffa8fd9732007-06-11 00:35:03 +00001606 }
1607 // the base type must be integer or float.
1608 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1609 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1610 curType.getCanonicalType().getAsString());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001611 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001612 }
Chris Lattner9cf21c52007-09-04 02:45:27 +00001613 unsigned typeSize = static_cast<unsigned>(
1614 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001615 // vecSize is specified in bytes - convert to bits.
Chris Lattner9cf21c52007-09-04 02:45:27 +00001616 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001617
1618 // the vector size needs to be an integral multiple of the type size.
1619 if (vectorSize % typeSize) {
1620 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1621 sizeExpr->getSourceRange());
1622 return QualType();
1623 }
1624 if (vectorSize == 0) {
1625 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1626 sizeExpr->getSourceRange());
1627 return QualType();
1628 }
1629 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1630 // the number of elements to be a power of two (unlike GCC).
1631 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff91fcddb2007-07-18 18:00:27 +00001632 return Context.getVectorType(curType, vectorSize/typeSize);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001633}
1634