blob: 425743aa320fe71e099aac23022dc5458f10f9b3 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Builtins.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/Type.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Parse/Scope.h"
22#include "clang/Lex/IdentifierTable.h"
23#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
25#include "llvm/ADT/SmallSet.h"
26using namespace clang;
27
28// C99: 6.7.5p3: Used by ParseDeclarator/ParseField to make sure we have
29// a constant expression of type int with a value greater than zero.
30bool Sema::VerifyConstantArrayType(const ArrayType *Array,
31 SourceLocation DeclLoc) {
Chris Lattner8b9023b2007-07-13 03:05:23 +000032 const Expr *Size = Array->getSizeExpr();
Reid Spencer5f016e22007-07-11 17:01:13 +000033 if (Size == 0) return false; // incomplete type.
34
35 if (!Size->getType()->isIntegerType()) {
36 Diag(Size->getLocStart(), diag::err_array_size_non_int,
37 Size->getType().getAsString(), Size->getSourceRange());
38 return true;
39 }
40
41 // Verify that the size of the array is an integer constant expr.
42 SourceLocation Loc;
43 llvm::APSInt SizeVal(32);
Chris Lattner590b6642007-07-15 23:26:56 +000044 if (!Size->isIntegerConstantExpr(SizeVal, Context, &Loc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +000045 // FIXME: This emits the diagnostic to enforce 6.7.2.1p8, but the message
46 // is wrong. It is also wrong for static variables.
47 // FIXME: This is also wrong for:
48 // int sub1(int i, char *pi) { typedef int foo[i];
49 // struct bar {foo f1; int f2:3; int f3:4} *p; }
50 Diag(DeclLoc, diag::err_typecheck_illegal_vla, Size->getSourceRange());
51 return true;
52 }
53
54 // We have a constant expression with an integer type, now make sure
55 // value greater than zero (C99 6.7.5.2p1).
56
57 // FIXME: This check isn't specific to static VLAs, this should be moved
58 // elsewhere or replicated. 'int X[-1];' inside a function should emit an
59 // error.
60 if (SizeVal.isSigned()) {
61 llvm::APSInt Zero(SizeVal.getBitWidth());
62 Zero.setIsUnsigned(false);
63 if (SizeVal < Zero) {
64 Diag(DeclLoc, diag::err_typecheck_negative_array_size,
65 Size->getSourceRange());
66 return true;
67 } else if (SizeVal == 0) {
68 // GCC accepts zero sized static arrays.
69 Diag(DeclLoc, diag::err_typecheck_zero_array_size,
70 Size->getSourceRange());
71 }
72 }
73 return false;
74}
75
76Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
77 return dyn_cast_or_null<TypedefDecl>(II.getFETokenInfo<Decl>());
78}
79
80void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000081 if (S->decl_empty()) return;
82 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
83
Reid Spencer5f016e22007-07-11 17:01:13 +000084 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
85 I != E; ++I) {
86 Decl *D = static_cast<Decl*>(*I);
87 assert(D && "This decl didn't get pushed??");
88 IdentifierInfo *II = D->getIdentifier();
89 if (!II) continue;
90
91 // Unlink this decl from the identifier. Because the scope contains decls
92 // in an unordered collection, and because we have multiple identifier
93 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
94 if (II->getFETokenInfo<Decl>() == D) {
95 // Normal case, no multiple decls in different namespaces.
96 II->setFETokenInfo(D->getNext());
97 } else {
98 // Scan ahead. There are only three namespaces in C, so this loop can
99 // never execute more than 3 times.
100 Decl *SomeDecl = II->getFETokenInfo<Decl>();
101 while (SomeDecl->getNext() != D) {
102 SomeDecl = SomeDecl->getNext();
103 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
104 }
105 SomeDecl->setNext(D->getNext());
106 }
107
108 // This will have to be revisited for C++: there we want to nest stuff in
109 // namespace decls etc. Even for C, we might want a top-level translation
110 // unit decl or something.
111 if (!CurFunctionDecl)
112 continue;
113
114 // Chain this decl to the containing function, it now owns the memory for
115 // the decl.
116 D->setNext(CurFunctionDecl->getDeclChain());
117 CurFunctionDecl->setDeclChain(D);
118 }
119}
120
121/// LookupScopedDecl - Look up the inner-most declaration in the specified
122/// namespace.
123Decl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
124 SourceLocation IdLoc, Scope *S) {
125 if (II == 0) return 0;
126 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
127
128 // Scan up the scope chain looking for a decl that matches this identifier
129 // that is in the appropriate namespace. This search should not take long, as
130 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
131 for (Decl *D = II->getFETokenInfo<Decl>(); D; D = D->getNext())
132 if (D->getIdentifierNamespace() == NS)
133 return D;
134
135 // If we didn't find a use of this identifier, and if the identifier
136 // corresponds to a compiler builtin, create the decl object for the builtin
137 // now, injecting it into translation unit scope, and return it.
138 if (NS == Decl::IDNS_Ordinary) {
139 // If this is a builtin on some other target, or if this builtin varies
140 // across targets (e.g. in type), emit a diagnostic and mark the translation
141 // unit non-portable for using it.
142 if (II->isNonPortableBuiltin()) {
143 // Only emit this diagnostic once for this builtin.
144 II->setNonPortableBuiltin(false);
145 Context.Target.DiagnoseNonPortability(IdLoc,
146 diag::port_target_builtin_use);
147 }
148 // If this is a builtin on this (or all) targets, create the decl.
149 if (unsigned BuiltinID = II->getBuiltinID())
150 return LazilyCreateBuiltin(II, BuiltinID, S);
151 }
152 return 0;
153}
154
155/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
156/// lazily create a decl for it.
157Decl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
158 Builtin::ID BID = (Builtin::ID)bid;
159
160 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
161 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000162 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000163
164 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000165 if (Scope *FnS = S->getFnParent())
166 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000167 while (S->getParent())
168 S = S->getParent();
169 S->AddDecl(New);
170
171 // Add this decl to the end of the identifier info.
172 if (Decl *LastDecl = II->getFETokenInfo<Decl>()) {
173 // Scan until we find the last (outermost) decl in the id chain.
174 while (LastDecl->getNext())
175 LastDecl = LastDecl->getNext();
176 // Insert before (outside) it.
177 LastDecl->setNext(New);
178 } else {
179 II->setFETokenInfo(New);
180 }
181 // Make sure clients iterating over decls see this.
182 LastInGroupList.push_back(New);
183
184 return New;
185}
186
187/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
188/// and scope as a previous declaration 'Old'. Figure out how to resolve this
189/// situation, merging decls or emitting diagnostics as appropriate.
190///
191TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
192 // Verify the old decl was also a typedef.
193 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
194 if (!Old) {
195 Diag(New->getLocation(), diag::err_redefinition_different_kind,
196 New->getName());
197 Diag(OldD->getLocation(), diag::err_previous_definition);
198 return New;
199 }
200
201 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
202 // TODO: This is totally simplistic. It should handle merging functions
203 // together etc, merging extern int X; int X; ...
204 Diag(New->getLocation(), diag::err_redefinition, New->getName());
205 Diag(Old->getLocation(), diag::err_previous_definition);
206 return New;
207}
208
209/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
210/// and scope as a previous declaration 'Old'. Figure out how to resolve this
211/// situation, merging decls or emitting diagnostics as appropriate.
212///
213FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
214 // Verify the old decl was also a function.
215 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
216 if (!Old) {
217 Diag(New->getLocation(), diag::err_redefinition_different_kind,
218 New->getName());
219 Diag(OldD->getLocation(), diag::err_previous_definition);
220 return New;
221 }
222
223 // This is not right, but it's a start. If 'Old' is a function prototype with
224 // the same type as 'New', silently allow this. FIXME: We should link up decl
225 // objects here.
226 if (Old->getBody() == 0 &&
227 Old->getCanonicalType() == New->getCanonicalType()) {
228 return New;
229 }
230
231 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
232 // TODO: This is totally simplistic. It should handle merging functions
233 // together etc, merging extern int X; int X; ...
234 Diag(New->getLocation(), diag::err_redefinition, New->getName());
235 Diag(Old->getLocation(), diag::err_previous_definition);
236 return New;
237}
238
239/// MergeVarDecl - We just parsed a variable 'New' which has the same name
240/// and scope as a previous declaration 'Old'. Figure out how to resolve this
241/// situation, merging decls or emitting diagnostics as appropriate.
242///
243/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
244/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
245///
246VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
247 // Verify the old decl was also a variable.
248 VarDecl *Old = dyn_cast<VarDecl>(OldD);
249 if (!Old) {
250 Diag(New->getLocation(), diag::err_redefinition_different_kind,
251 New->getName());
252 Diag(OldD->getLocation(), diag::err_previous_definition);
253 return New;
254 }
255 // Verify the types match.
256 if (Old->getCanonicalType() != New->getCanonicalType()) {
257 Diag(New->getLocation(), diag::err_redefinition, New->getName());
258 Diag(Old->getLocation(), diag::err_previous_definition);
259 return New;
260 }
261 // We've verified the types match, now check if Old is "extern".
262 if (Old->getStorageClass() != VarDecl::Extern) {
263 Diag(New->getLocation(), diag::err_redefinition, New->getName());
264 Diag(Old->getLocation(), diag::err_previous_definition);
265 }
266 return New;
267}
268
269/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
270/// no declarator (e.g. "struct foo;") is parsed.
271Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
272 // TODO: emit error on 'int;' or 'const enum foo;'.
273 // TODO: emit error on 'typedef int;'
274 // if (!DS.isMissingDeclaratorOk()) Diag(...);
275
276 return 0;
277}
278
279Sema::DeclTy *
Chris Lattner24c39902007-07-12 00:36:32 +0000280Sema::ParseDeclarator(Scope *S, Declarator &D, ExprTy *init,
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 DeclTy *lastDeclarator) {
282 Decl *LastDeclarator = (Decl*)lastDeclarator;
Chris Lattner24c39902007-07-12 00:36:32 +0000283 Expr *Init = static_cast<Expr*>(init);
Reid Spencer5f016e22007-07-11 17:01:13 +0000284 IdentifierInfo *II = D.getIdentifier();
285
Chris Lattnere80a59c2007-07-25 00:24:17 +0000286 // All of these full declarators require an identifier. If it doesn't have
287 // one, the ParsedFreeStandingDeclSpec action should be used.
288 if (II == 0) {
Chris Lattner98e08632007-08-28 06:17:15 +0000289 Diag(D.getDeclSpec().getSourceRange().Begin(),
290 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000291 D.getDeclSpec().getSourceRange(), D.getSourceRange());
292 return 0;
293 }
294
Chris Lattner31e05722007-08-26 06:24:45 +0000295 // The scope passed in may not be a decl scope. Zip up the scope tree until
296 // we find one that is.
297 while ((S->getFlags() & Scope::DeclScope) == 0)
298 S = S->getParent();
299
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 // See if this is a redefinition of a variable in the same scope.
301 Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
302 D.getIdentifierLoc(), S);
303 if (PrevDecl && !S->isDeclScope(PrevDecl))
304 PrevDecl = 0; // If in outer scope, it isn't the same thing.
305
306 Decl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000307 bool InvalidDecl = false;
308
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner24c39902007-07-12 00:36:32 +0000310 assert(Init == 0 && "Can't have initializer for a typedef!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
312 if (!NewTD) return 0;
313
314 // Handle attributes prior to checking for duplicates in MergeVarDecl
315 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
316 D.getAttributes());
317 // Merge the decl with the existing one if appropriate.
318 if (PrevDecl) {
319 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
320 if (NewTD == 0) return 0;
321 }
322 New = NewTD;
323 if (S->getParent() == 0) {
324 // C99 6.7.7p2: If a typedef name specifies a variably modified type
325 // then it shall have block scope.
326 if (ArrayType *ary = dyn_cast<ArrayType>(NewTD->getUnderlyingType())) {
327 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
Steve Naroff5912a352007-08-28 20:14:24 +0000328 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 }
330 }
331 } else if (D.isFunctionDeclarator()) {
Chris Lattner24c39902007-07-12 00:36:32 +0000332 assert(Init == 0 && "Can't have an initializer for a functiondecl!");
Steve Naroff5912a352007-08-28 20:14:24 +0000333
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000335 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000336
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 FunctionDecl::StorageClass SC;
338 switch (D.getDeclSpec().getStorageClassSpec()) {
339 default: assert(0 && "Unknown storage class!");
340 case DeclSpec::SCS_auto:
341 case DeclSpec::SCS_register:
342 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
343 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000344 InvalidDecl = true;
345 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
347 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
348 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
349 }
350
351 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000352 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 LastDeclarator);
354
355 // Merge the decl with the existing one if appropriate.
356 if (PrevDecl) {
357 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
358 if (NewFD == 0) return 0;
359 }
360 New = NewFD;
361 } else {
362 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff53a32342007-08-28 18:45:29 +0000363 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000364
365 VarDecl *NewVD;
366 VarDecl::StorageClass SC;
367 switch (D.getDeclSpec().getStorageClassSpec()) {
368 default: assert(0 && "Unknown storage class!");
369 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
370 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
371 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
372 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
373 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
374 }
375 if (S->getParent() == 0) {
376 // File scope. C99 6.9.2p2: A declaration of an identifier for and
377 // object that has file scope without an initializer, and without a
378 // storage-class specifier or with the storage-class specifier "static",
379 // constitutes a tentative definition. Note: A tentative definition with
380 // external linkage is valid (C99 6.2.2p5).
381 if (!Init && SC == VarDecl::Static) {
382 // C99 6.9.2p3: If the declaration of an identifier for an object is
383 // a tentative definition and has internal linkage (C99 6.2.2p3), the
384 // declared type shall not be an incomplete type.
385 if (R->isIncompleteType()) {
386 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
387 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000388 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 }
390 }
391 // C99 6.9p2: The storage-class specifiers auto and register shall not
392 // appear in the declaration specifiers in an external declaration.
393 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
394 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
395 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000396 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000397 }
398 // C99 6.7.5.2p2: If an identifier is declared to be an object with
399 // static storage duration, it shall not have a variable length array.
Chris Lattner02c642e2007-07-31 21:33:24 +0000400 if (const ArrayType *ary = R->getAsArrayType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
Steve Naroff53a32342007-08-28 18:45:29 +0000402 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 }
404 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
405 } else {
406 // Block scope. C99 6.7p7: If an identifier for an object is declared with
407 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
408 if (SC != VarDecl::Extern) {
409 if (R->isIncompleteType()) {
410 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
411 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000412 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000413 }
414 }
415 if (SC == VarDecl::Static) {
416 // C99 6.7.5.2p2: If an identifier is declared to be an object with
417 // static storage duration, it shall not have a variable length array.
Chris Lattner02c642e2007-07-31 21:33:24 +0000418 if (const ArrayType *ary = R->getAsArrayType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000419 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
Steve Naroff53a32342007-08-28 18:45:29 +0000420 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000421 }
422 }
423 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000424 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000425 // Handle attributes prior to checking for duplicates in MergeVarDecl
426 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
427 D.getAttributes());
428
429 // Merge the decl with the existing one if appropriate.
430 if (PrevDecl) {
431 NewVD = MergeVarDecl(NewVD, PrevDecl);
432 if (NewVD == 0) return 0;
433 }
Steve Narofff1120de2007-08-24 22:33:52 +0000434 if (Init) {
435 AssignmentCheckResult result;
436 result = CheckSingleAssignmentConstraints(R, Init);
437 // FIXME: emit errors if appropriate.
438 NewVD->setInit(Init);
439 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000440 New = NewVD;
441 }
442
443 // If this has an identifier, add it to the scope stack.
444 if (II) {
445 New->setNext(II->getFETokenInfo<Decl>());
446 II->setFETokenInfo(New);
447 S->AddDecl(New);
448 }
449
450 if (S->getParent() == 0)
451 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +0000452
453 // If any semantic error occurred, mark the decl as invalid.
454 if (D.getInvalidType() || InvalidDecl)
455 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000456
457 return New;
458}
459
460/// The declarators are chained together backwards, reverse the list.
461Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
462 // Often we have single declarators, handle them quickly.
463 Decl *Group = static_cast<Decl*>(group);
464 if (Group == 0 || Group->getNextDeclarator() == 0) return Group;
465
466 Decl *NewGroup = 0;
467 while (Group) {
468 Decl *Next = Group->getNextDeclarator();
469 Group->setNextDeclarator(NewGroup);
470 NewGroup = Group;
471 Group = Next;
472 }
473 return NewGroup;
474}
Steve Naroffe1223f72007-08-28 03:03:08 +0000475
476// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000477ParmVarDecl *
478Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
479 Scope *FnScope) {
480 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
481
482 IdentifierInfo *II = PI.Ident;
483 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
484 // Can this happen for params? We already checked that they don't conflict
485 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000486 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000487 PI.IdentLoc, FnScope)) {
488
489 }
490
491 // FIXME: Handle storage class (auto, register). No declarator?
492 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000493
494 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
495 // Doing the promotion here has a win and a loss. The win is the type for
496 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
497 // code generator). The loss is the orginal type isn't preserved. For example:
498 //
499 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
500 // int blockvardecl[5];
501 // sizeof(parmvardecl); // size == 4
502 // sizeof(blockvardecl); // size == 20
503 // }
504 //
505 // For expressions, all implicit conversions are captured using the
506 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
507 //
508 // FIXME: If a source translation tool needs to see the original type, then
509 // we need to consider storing both types (in ParmVarDecl)...
510 //
511 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
512 if (const ArrayType *AT = parmDeclType->getAsArrayType())
513 parmDeclType = Context.getPointerType(AT->getElementType());
514 else if (parmDeclType->isFunctionType())
515 parmDeclType = Context.getPointerType(parmDeclType);
516
517 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff53a32342007-08-28 18:45:29 +0000518 VarDecl::None, 0);
519 if (PI.InvalidType)
520 New->setInvalidDecl();
521
Reid Spencer5f016e22007-07-11 17:01:13 +0000522 // If this has an identifier, add it to the scope stack.
523 if (II) {
524 New->setNext(II->getFETokenInfo<Decl>());
525 II->setFETokenInfo(New);
526 FnScope->AddDecl(New);
527 }
528
529 return New;
530}
531
532
533Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
534 assert(CurFunctionDecl == 0 && "Function parsing confused");
535 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
536 "Not a function declarator!");
537 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
538
539 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
540 // for a K&R function.
541 if (!FTI.hasPrototype) {
542 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
543 if (FTI.ArgInfo[i].TypeInfo == 0) {
544 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
545 FTI.ArgInfo[i].Ident->getName());
546 // Implicitly declare the argument as type 'int' for lack of a better
547 // type.
548 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
549 }
550 }
551
552 // Since this is a function definition, act as though we have information
553 // about the arguments.
554 FTI.hasPrototype = true;
555 } else {
556 // FIXME: Diagnose arguments without names in C.
557
558 }
559
560 Scope *GlobalScope = FnBodyScope->getParent();
561
562 FunctionDecl *FD =
563 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0, 0));
564 CurFunctionDecl = FD;
565
566 // Create Decl objects for each parameter, adding them to the FunctionDecl.
567 llvm::SmallVector<ParmVarDecl*, 16> Params;
568
569 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
570 // no arguments, not a function that takes a single void argument.
571 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
572 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
573 // empty arg list, don't push any params.
574 } else {
575 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
576 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
577 }
578
579 FD->setParams(&Params[0], Params.size());
580
581 return FD;
582}
583
584Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
585 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
586 FD->setBody((Stmt*)Body);
587
588 assert(FD == CurFunctionDecl && "Function parsing confused");
589 CurFunctionDecl = 0;
590
591 // Verify and clean out per-function state.
592
593 // Check goto/label use.
594 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
595 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
596 // Verify that we have no forward references left. If so, there was a goto
597 // or address of a label taken, but no definition of it. Label fwd
598 // definitions are indicated with a null substmt.
599 if (I->second->getSubStmt() == 0) {
600 LabelStmt *L = I->second;
601 // Emit error.
602 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
603
604 // At this point, we have gotos that use the bogus label. Stitch it into
605 // the function body so that they aren't leaked and that the AST is well
606 // formed.
607 L->setSubStmt(new NullStmt(L->getIdentLoc()));
608 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
609 }
610 }
611 LabelMap.clear();
612
613 return FD;
614}
615
616
617/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
618/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
619Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
620 Scope *S) {
621 if (getLangOptions().C99) // Extension in C99.
622 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
623 else // Legal in C90, but warn about it.
624 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
625
626 // FIXME: handle stuff like:
627 // void foo() { extern float X(); }
628 // void bar() { X(); } <-- implicit decl for X in another scope.
629
630 // Set a Declarator for the implicit definition: int foo();
631 const char *Dummy;
632 DeclSpec DS;
633 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
634 Error = Error; // Silence warning.
635 assert(!Error && "Error setting up implicit decl!");
636 Declarator D(DS, Declarator::BlockContext);
637 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
638 D.SetIdentifier(&II, Loc);
639
640 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000641 if (Scope *FnS = S->getFnParent())
642 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 while (S->getParent())
644 S = S->getParent();
645
646 return static_cast<Decl*>(ParseDeclarator(S, D, 0, 0));
647}
648
649
650TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
651 Decl *LastDeclarator) {
652 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
653
654 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000655 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000656
657 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +0000658 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
659 T, LastDeclarator);
660 if (D.getInvalidType())
661 NewTD->setInvalidDecl();
662 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000663}
664
665
666/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
667/// former case, Name will be non-null. In the later case, Name will be null.
668/// TagType indicates what kind of tag this is. TK indicates whether this is a
669/// reference/declaration/definition of a tag.
670Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
671 SourceLocation KWLoc, IdentifierInfo *Name,
672 SourceLocation NameLoc, AttributeList *Attr) {
673 // If this is a use of an existing tag, it must have a name.
674 assert((Name != 0 || TK == TK_Definition) &&
675 "Nameless record must be a definition!");
676
677 Decl::Kind Kind;
678 switch (TagType) {
679 default: assert(0 && "Unknown tag type!");
680 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
681 case DeclSpec::TST_union: Kind = Decl::Union; break;
682//case DeclSpec::TST_class: Kind = Decl::Class; break;
683 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
684 }
685
686 // If this is a named struct, check to see if there was a previous forward
687 // declaration or definition.
688 if (TagDecl *PrevDecl =
689 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
690 NameLoc, S))) {
691
692 // If this is a use of a previous tag, or if the tag is already declared in
693 // the same scope (so that the definition/declaration completes or
694 // rementions the tag), reuse the decl.
695 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
696 // Make sure that this wasn't declared as an enum and now used as a struct
697 // or something similar.
698 if (PrevDecl->getKind() != Kind) {
699 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
700 Diag(PrevDecl->getLocation(), diag::err_previous_use);
701 }
702
703 // If this is a use or a forward declaration, we're good.
704 if (TK != TK_Definition)
705 return PrevDecl;
706
707 // Diagnose attempts to redefine a tag.
708 if (PrevDecl->isDefinition()) {
709 Diag(NameLoc, diag::err_redefinition, Name->getName());
710 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
711 // If this is a redefinition, recover by making this struct be
712 // anonymous, which will make any later references get the previous
713 // definition.
714 Name = 0;
715 } else {
716 // Okay, this is definition of a previously declared or referenced tag.
717 // Move the location of the decl to be the definition site.
718 PrevDecl->setLocation(NameLoc);
719 return PrevDecl;
720 }
721 }
722 // If we get here, this is a definition of a new struct type in a nested
723 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
724 // type.
725 }
726
727 // If there is an identifier, use the location of the identifier as the
728 // location of the decl, otherwise use the location of the struct/union
729 // keyword.
730 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
731
732 // Otherwise, if this is the first time we've seen this tag, create the decl.
733 TagDecl *New;
734 switch (Kind) {
735 default: assert(0 && "Unknown tag kind!");
736 case Decl::Enum:
737 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
738 // enum X { A, B, C } D; D should chain to X.
739 New = new EnumDecl(Loc, Name, 0);
740 // If this is an undefined enum, warn.
741 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
742 break;
743 case Decl::Union:
744 case Decl::Struct:
745 case Decl::Class:
746 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
747 // struct X { int A; } D; D should chain to X.
748 New = new RecordDecl(Kind, Loc, Name, 0);
749 break;
750 }
751
752 // If this has an identifier, add it to the scope stack.
753 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +0000754 // The scope passed in may not be a decl scope. Zip up the scope tree until
755 // we find one that is.
756 while ((S->getFlags() & Scope::DeclScope) == 0)
757 S = S->getParent();
758
759 // Add it to the decl chain.
Reid Spencer5f016e22007-07-11 17:01:13 +0000760 New->setNext(Name->getFETokenInfo<Decl>());
761 Name->setFETokenInfo(New);
762 S->AddDecl(New);
763 }
764
765 return New;
766}
767
768/// ParseField - Each field of a struct/union/class is passed into this in order
769/// to create a FieldDecl object for it.
770Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
771 SourceLocation DeclStart,
772 Declarator &D, ExprTy *BitfieldWidth) {
773 IdentifierInfo *II = D.getIdentifier();
774 Expr *BitWidth = (Expr*)BitfieldWidth;
775
776 SourceLocation Loc = DeclStart;
777 if (II) Loc = D.getIdentifierLoc();
778
779 // FIXME: Unnamed fields can be handled in various different ways, for
780 // example, unnamed unions inject all members into the struct namespace!
781
782
783 if (BitWidth) {
784 // TODO: Validate.
785 //printf("WARNING: BITFIELDS IGNORED!\n");
786
787 // 6.7.2.1p3
788 // 6.7.2.1p4
789
790 } else {
791 // Not a bitfield.
792
793 // validate II.
794
795 }
796
797 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000798 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
799 bool InvalidDecl = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000800
801 // C99 6.7.2.1p8: A member of a structure or union may have any type other
802 // than a variably modified type.
Chris Lattner02c642e2007-07-31 21:33:24 +0000803 if (const ArrayType *ary = T->getAsArrayType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000804 if (VerifyConstantArrayType(ary, Loc))
Steve Naroff5912a352007-08-28 20:14:24 +0000805 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000806 }
807
808 // FIXME: Chain fielddecls together.
Steve Naroff5912a352007-08-28 20:14:24 +0000809 FieldDecl *NewFD = new FieldDecl(Loc, II, T, 0);
810 if (D.getInvalidType() || InvalidDecl)
811 NewFD->setInvalidDecl();
812 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000813}
814
815void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
816 DeclTy **Fields, unsigned NumFields) {
817 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
818 if (Record->isDefinition()) {
819 // Diagnose code like:
820 // struct S { struct S {} X; };
821 // We discover this when we complete the outer S. Reject and ignore the
822 // outer S.
823 Diag(Record->getLocation(), diag::err_nested_redefinition,
824 Record->getKindName());
825 Diag(RecLoc, diag::err_previous_definition);
826 return;
827 }
828
829 // Verify that all the fields are okay.
830 unsigned NumNamedMembers = 0;
831 llvm::SmallVector<FieldDecl*, 32> RecFields;
832 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
833
834 for (unsigned i = 0; i != NumFields; ++i) {
835 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
836 if (!FD) continue; // Already issued a diagnostic.
837
838 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +0000839 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +0000840
841 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +0000842 if (FDTy->isFunctionType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000843 Diag(FD->getLocation(), diag::err_field_declared_as_function,
844 FD->getName());
845 delete FD;
846 continue;
847 }
848
849 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
850 if (FDTy->isIncompleteType()) {
851 if (i != NumFields-1 || // ... that the last member ...
852 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +0000853 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000854 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
855 delete FD;
856 continue;
857 }
858 if (NumNamedMembers < 1) { //... must have more than named member ...
859 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
860 FD->getName());
861 delete FD;
862 continue;
863 }
864
865 // Okay, we have a legal flexible array member at the end of the struct.
866 Record->setHasFlexibleArrayMember(true);
867 }
868
869
870 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
871 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +0000872 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000873 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
874 // If this is a member of a union, then entire union becomes "flexible".
875 if (Record->getKind() == Decl::Union) {
876 Record->setHasFlexibleArrayMember(true);
877 } else {
878 // If this is a struct/class and this is not the last element, reject
879 // it. Note that GCC supports variable sized arrays in the middle of
880 // structures.
881 if (i != NumFields-1) {
882 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
883 FD->getName());
884 delete FD;
885 continue;
886 }
887
888 // We support flexible arrays at the end of structs in other structs
889 // as an extension.
890 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
891 FD->getName());
892 Record->setHasFlexibleArrayMember(true);
893 }
894 }
895 }
896
897 // Keep track of the number of named members.
898 if (IdentifierInfo *II = FD->getIdentifier()) {
899 // Detect duplicate member names.
900 if (!FieldIDs.insert(II)) {
901 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
902 // Find the previous decl.
903 SourceLocation PrevLoc;
904 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
905 assert(i != e && "Didn't find previous def!");
906 if (RecFields[i]->getIdentifier() == II) {
907 PrevLoc = RecFields[i]->getLocation();
908 break;
909 }
910 }
911 Diag(PrevLoc, diag::err_previous_definition);
912 delete FD;
913 continue;
914 }
915 ++NumNamedMembers;
916 }
917
918 // Remember good fields.
919 RecFields.push_back(FD);
920 }
921
922
923 // Okay, we successfully defined 'Record'.
924 Record->defineBody(&RecFields[0], RecFields.size());
925}
926
927Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
928 DeclTy *lastEnumConst,
929 SourceLocation IdLoc, IdentifierInfo *Id,
930 SourceLocation EqualLoc, ExprTy *val) {
931 theEnumDecl = theEnumDecl; // silence unused warning.
932 EnumConstantDecl *LastEnumConst =
933 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
934 Expr *Val = static_cast<Expr*>(val);
935
Chris Lattner31e05722007-08-26 06:24:45 +0000936 // The scope passed in may not be a decl scope. Zip up the scope tree until
937 // we find one that is.
938 while ((S->getFlags() & Scope::DeclScope) == 0)
939 S = S->getParent();
940
Reid Spencer5f016e22007-07-11 17:01:13 +0000941 // Verify that there isn't already something declared with this name in this
942 // scope.
943 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
944 if (S->isDeclScope(PrevDecl)) {
945 if (isa<EnumConstantDecl>(PrevDecl))
946 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
947 else
948 Diag(IdLoc, diag::err_redefinition, Id->getName());
949 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
950 // FIXME: Don't leak memory: delete Val;
951 return 0;
952 }
953 }
954
955 llvm::APSInt EnumVal(32);
956 QualType EltTy;
957 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +0000958 // Make sure to promote the operand type to int.
959 UsualUnaryConversions(Val);
960
Reid Spencer5f016e22007-07-11 17:01:13 +0000961 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
962 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +0000963 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000964 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
965 Id->getName());
966 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +0000967 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +0000968 } else {
969 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000970 }
Chris Lattnerb7416f92007-08-27 17:37:24 +0000971 }
972
973 if (!Val) {
974 if (LastEnumConst) {
975 // Assign the last value + 1.
976 EnumVal = LastEnumConst->getInitVal();
977 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +0000978
979 // Check for overflow on increment.
980 if (EnumVal < LastEnumConst->getInitVal())
981 Diag(IdLoc, diag::warn_enum_value_overflow);
982
Chris Lattnerb7416f92007-08-27 17:37:24 +0000983 EltTy = LastEnumConst->getType();
984 } else {
985 // First value, set to zero.
986 EltTy = Context.IntTy;
Chris Lattner421a23d2007-08-27 21:16:18 +0000987 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy, IdLoc));
Chris Lattnerb7416f92007-08-27 17:37:24 +0000988 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000989 }
990
Reid Spencer5f016e22007-07-11 17:01:13 +0000991 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
992 LastEnumConst);
993
994 // Register this decl in the current scope stack.
995 New->setNext(Id->getFETokenInfo<Decl>());
996 Id->setFETokenInfo(New);
997 S->AddDecl(New);
998 return New;
999}
1000
1001void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1002 DeclTy **Elements, unsigned NumElements) {
1003 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1004 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1005
Chris Lattnere37f0be2007-08-28 05:10:31 +00001006 // TODO: If the result value doesn't fit in an int, it must be a long or long
1007 // long value. ISO C does not support this, but GCC does as an extension,
1008 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001009 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001010
1011
Chris Lattnerac609682007-08-28 06:15:15 +00001012 // Verify that all the values are okay, compute the size of the values, and
1013 // reverse the list.
1014 unsigned NumNegativeBits = 0;
1015 unsigned NumPositiveBits = 0;
1016
1017 // Keep track of whether all elements have type int.
1018 bool AllElementsInt = true;
1019
Reid Spencer5f016e22007-07-11 17:01:13 +00001020 EnumConstantDecl *EltList = 0;
1021 for (unsigned i = 0; i != NumElements; ++i) {
1022 EnumConstantDecl *ECD =
1023 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1024 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001025
1026 // If the enum value doesn't fit in an int, emit an extension warning.
1027 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1028 "Should have promoted value to int");
1029 const llvm::APSInt &InitVal = ECD->getInitVal();
1030 if (InitVal.getBitWidth() > IntWidth) {
1031 llvm::APSInt V(InitVal);
1032 V.trunc(IntWidth);
1033 V.extend(InitVal.getBitWidth());
1034 if (V != InitVal)
1035 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1036 InitVal.toString());
1037 }
Chris Lattnerac609682007-08-28 06:15:15 +00001038
1039 // Keep track of the size of positive and negative values.
1040 if (InitVal.isUnsigned() || !InitVal.isNegative())
1041 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1042 else
1043 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001044
Chris Lattnerac609682007-08-28 06:15:15 +00001045 // Keep track of whether every enum element has type int (very commmon).
1046 if (AllElementsInt)
1047 AllElementsInt = ECD->getType() == Context.IntTy;
1048
Reid Spencer5f016e22007-07-11 17:01:13 +00001049 ECD->setNextDeclarator(EltList);
1050 EltList = ECD;
1051 }
1052
Chris Lattnerac609682007-08-28 06:15:15 +00001053 // Figure out the type that should be used for this enum.
1054 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1055 QualType BestType;
1056
1057 if (NumNegativeBits) {
1058 // If there is a negative value, figure out the smallest integer type (of
1059 // int/long/longlong) that fits.
1060 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth)
1061 BestType = Context.IntTy;
1062 else {
1063 unsigned LongWidth = Context.Target.getLongWidth(Enum->getLocation());
1064 if (NumNegativeBits <= LongWidth && NumPositiveBits < LongWidth)
1065 BestType = Context.LongTy;
1066 else {
1067 unsigned LLWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1068 if (NumNegativeBits > LLWidth || NumPositiveBits >= LLWidth)
1069 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1070 BestType = Context.LongLongTy;
1071 }
1072 }
1073 } else {
1074 // If there is no negative value, figure out which of uint, ulong, ulonglong
1075 // fits.
1076 if (NumPositiveBits <= IntWidth)
1077 BestType = Context.UnsignedIntTy;
1078 else if (NumPositiveBits <=Context.Target.getLongWidth(Enum->getLocation()))
1079 BestType = Context.UnsignedLongTy;
1080 else {
1081 assert(NumPositiveBits <=
1082 Context.Target.getLongLongWidth(Enum->getLocation()) &&
1083 "How could an initializer get larger than ULL?");
1084 BestType = Context.UnsignedLongLongTy;
1085 }
1086 }
1087
1088 // FIXME: Install type in Enum and constant values.
1089
Chris Lattnere00b18c2007-08-28 18:24:31 +00001090 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001091}
1092
1093void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1094 if (!current) return;
1095
1096 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1097 // remember this in the LastInGroupList list.
1098 if (last)
1099 LastInGroupList.push_back((Decl*)last);
1100}
1101
1102void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1103 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1104 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1105 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1106 if (!newType.isNull()) // install the new vector type into the decl
1107 vDecl->setType(newType);
1108 }
1109 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1110 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1111 rawAttr);
1112 if (!newType.isNull()) // install the new vector type into the decl
1113 tDecl->setUnderlyingType(newType);
1114 }
1115 }
Steve Naroff73322922007-07-18 18:00:27 +00001116 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001117 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1118 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1119 else
Steve Naroff73322922007-07-18 18:00:27 +00001120 Diag(rawAttr->getAttributeLoc(),
1121 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00001122 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001123 // FIXME: add other attributes...
1124}
1125
1126void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1127 AttributeList *declarator_postfix) {
1128 while (declspec_prefix) {
1129 HandleDeclAttribute(New, declspec_prefix);
1130 declspec_prefix = declspec_prefix->getNext();
1131 }
1132 while (declarator_postfix) {
1133 HandleDeclAttribute(New, declarator_postfix);
1134 declarator_postfix = declarator_postfix->getNext();
1135 }
1136}
1137
Steve Naroffbea0b342007-07-29 16:33:31 +00001138void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1139 AttributeList *rawAttr) {
1140 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00001141 // check the attribute arugments.
1142 if (rawAttr->getNumArgs() != 1) {
1143 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1144 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001145 return;
Steve Naroff73322922007-07-18 18:00:27 +00001146 }
1147 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1148 llvm::APSInt vecSize(32);
1149 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1150 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1151 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001152 return;
Steve Naroff73322922007-07-18 18:00:27 +00001153 }
1154 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1155 // in conjunction with complex types (pointers, arrays, functions, etc.).
1156 Type *canonType = curType.getCanonicalType().getTypePtr();
1157 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1158 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1159 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001160 return;
Steve Naroff73322922007-07-18 18:00:27 +00001161 }
1162 // unlike gcc's vector_size attribute, the size is specified as the
1163 // number of elements, not the number of bytes.
1164 unsigned vectorSize = vecSize.getZExtValue();
1165
1166 if (vectorSize == 0) {
1167 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1168 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001169 return;
Steve Naroff73322922007-07-18 18:00:27 +00001170 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001171 // Instantiate/Install the vector type, the number of elements is > 0.
1172 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1173 // Remember this typedef decl, we will need it later for diagnostics.
1174 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001175}
1176
Reid Spencer5f016e22007-07-11 17:01:13 +00001177QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001178 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001179 // check the attribute arugments.
1180 if (rawAttr->getNumArgs() != 1) {
1181 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1182 std::string("1"));
1183 return QualType();
1184 }
1185 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1186 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001187 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001188 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1189 sizeExpr->getSourceRange());
1190 return QualType();
1191 }
1192 // navigate to the base type - we need to provide for vector pointers,
1193 // vector arrays, and functions returning vectors.
1194 Type *canonType = curType.getCanonicalType().getTypePtr();
1195
Steve Naroff73322922007-07-18 18:00:27 +00001196 if (canonType->isPointerType() || canonType->isArrayType() ||
1197 canonType->isFunctionType()) {
1198 assert(1 && "HandleVector(): Complex type construction unimplemented");
1199 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1200 do {
1201 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1202 canonType = PT->getPointeeType().getTypePtr();
1203 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1204 canonType = AT->getElementType().getTypePtr();
1205 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1206 canonType = FT->getResultType().getTypePtr();
1207 } while (canonType->isPointerType() || canonType->isArrayType() ||
1208 canonType->isFunctionType());
1209 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001210 }
1211 // the base type must be integer or float.
1212 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1213 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1214 curType.getCanonicalType().getAsString());
1215 return QualType();
1216 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001217 unsigned typeSize = Context.getTypeSize(curType, rawAttr->getAttributeLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +00001218 // vecSize is specified in bytes - convert to bits.
1219 unsigned vectorSize = vecSize.getZExtValue() * 8;
1220
1221 // the vector size needs to be an integral multiple of the type size.
1222 if (vectorSize % typeSize) {
1223 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1224 sizeExpr->getSourceRange());
1225 return QualType();
1226 }
1227 if (vectorSize == 0) {
1228 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1229 sizeExpr->getSourceRange());
1230 return QualType();
1231 }
1232 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1233 // the number of elements to be a power of two (unlike GCC).
1234 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00001235 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001236}
1237