blob: 4d2fd4d515a151a47be19e9092915ce437a9e5ff [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Builtins.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/Type.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Parse/Scope.h"
22#include "clang/Lex/IdentifierTable.h"
23#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
25#include "llvm/ADT/SmallSet.h"
26using namespace clang;
27
Reid Spencer5f016e22007-07-11 17:01:13 +000028Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
29 return dyn_cast_or_null<TypedefDecl>(II.getFETokenInfo<Decl>());
30}
31
32void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000033 if (S->decl_empty()) return;
34 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
35
Reid Spencer5f016e22007-07-11 17:01:13 +000036 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
37 I != E; ++I) {
38 Decl *D = static_cast<Decl*>(*I);
39 assert(D && "This decl didn't get pushed??");
40 IdentifierInfo *II = D->getIdentifier();
41 if (!II) continue;
42
43 // Unlink this decl from the identifier. Because the scope contains decls
44 // in an unordered collection, and because we have multiple identifier
45 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
46 if (II->getFETokenInfo<Decl>() == D) {
47 // Normal case, no multiple decls in different namespaces.
48 II->setFETokenInfo(D->getNext());
49 } else {
50 // Scan ahead. There are only three namespaces in C, so this loop can
51 // never execute more than 3 times.
52 Decl *SomeDecl = II->getFETokenInfo<Decl>();
53 while (SomeDecl->getNext() != D) {
54 SomeDecl = SomeDecl->getNext();
55 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
56 }
57 SomeDecl->setNext(D->getNext());
58 }
59
60 // This will have to be revisited for C++: there we want to nest stuff in
61 // namespace decls etc. Even for C, we might want a top-level translation
62 // unit decl or something.
63 if (!CurFunctionDecl)
64 continue;
65
66 // Chain this decl to the containing function, it now owns the memory for
67 // the decl.
68 D->setNext(CurFunctionDecl->getDeclChain());
69 CurFunctionDecl->setDeclChain(D);
70 }
71}
72
73/// LookupScopedDecl - Look up the inner-most declaration in the specified
74/// namespace.
75Decl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
76 SourceLocation IdLoc, Scope *S) {
77 if (II == 0) return 0;
78 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
79
80 // Scan up the scope chain looking for a decl that matches this identifier
81 // that is in the appropriate namespace. This search should not take long, as
82 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
83 for (Decl *D = II->getFETokenInfo<Decl>(); D; D = D->getNext())
84 if (D->getIdentifierNamespace() == NS)
85 return D;
86
87 // If we didn't find a use of this identifier, and if the identifier
88 // corresponds to a compiler builtin, create the decl object for the builtin
89 // now, injecting it into translation unit scope, and return it.
90 if (NS == Decl::IDNS_Ordinary) {
91 // If this is a builtin on some other target, or if this builtin varies
92 // across targets (e.g. in type), emit a diagnostic and mark the translation
93 // unit non-portable for using it.
94 if (II->isNonPortableBuiltin()) {
95 // Only emit this diagnostic once for this builtin.
96 II->setNonPortableBuiltin(false);
97 Context.Target.DiagnoseNonPortability(IdLoc,
98 diag::port_target_builtin_use);
99 }
100 // If this is a builtin on this (or all) targets, create the decl.
101 if (unsigned BuiltinID = II->getBuiltinID())
102 return LazilyCreateBuiltin(II, BuiltinID, S);
103 }
104 return 0;
105}
106
107/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
108/// lazily create a decl for it.
109Decl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
110 Builtin::ID BID = (Builtin::ID)bid;
111
112 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
113 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000114 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000115
116 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000117 if (Scope *FnS = S->getFnParent())
118 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 while (S->getParent())
120 S = S->getParent();
121 S->AddDecl(New);
122
123 // Add this decl to the end of the identifier info.
124 if (Decl *LastDecl = II->getFETokenInfo<Decl>()) {
125 // Scan until we find the last (outermost) decl in the id chain.
126 while (LastDecl->getNext())
127 LastDecl = LastDecl->getNext();
128 // Insert before (outside) it.
129 LastDecl->setNext(New);
130 } else {
131 II->setFETokenInfo(New);
132 }
133 // Make sure clients iterating over decls see this.
134 LastInGroupList.push_back(New);
135
136 return New;
137}
138
139/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
140/// and scope as a previous declaration 'Old'. Figure out how to resolve this
141/// situation, merging decls or emitting diagnostics as appropriate.
142///
143TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
144 // Verify the old decl was also a typedef.
145 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
146 if (!Old) {
147 Diag(New->getLocation(), diag::err_redefinition_different_kind,
148 New->getName());
149 Diag(OldD->getLocation(), diag::err_previous_definition);
150 return New;
151 }
152
153 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
154 // TODO: This is totally simplistic. It should handle merging functions
155 // together etc, merging extern int X; int X; ...
156 Diag(New->getLocation(), diag::err_redefinition, New->getName());
157 Diag(Old->getLocation(), diag::err_previous_definition);
158 return New;
159}
160
161/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
162/// and scope as a previous declaration 'Old'. Figure out how to resolve this
163/// situation, merging decls or emitting diagnostics as appropriate.
164///
165FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
166 // Verify the old decl was also a function.
167 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
168 if (!Old) {
169 Diag(New->getLocation(), diag::err_redefinition_different_kind,
170 New->getName());
171 Diag(OldD->getLocation(), diag::err_previous_definition);
172 return New;
173 }
174
175 // This is not right, but it's a start. If 'Old' is a function prototype with
176 // the same type as 'New', silently allow this. FIXME: We should link up decl
177 // objects here.
178 if (Old->getBody() == 0 &&
179 Old->getCanonicalType() == New->getCanonicalType()) {
180 return New;
181 }
182
183 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
184 // TODO: This is totally simplistic. It should handle merging functions
185 // together etc, merging extern int X; int X; ...
186 Diag(New->getLocation(), diag::err_redefinition, New->getName());
187 Diag(Old->getLocation(), diag::err_previous_definition);
188 return New;
189}
190
191/// MergeVarDecl - We just parsed a variable 'New' which has the same name
192/// and scope as a previous declaration 'Old'. Figure out how to resolve this
193/// situation, merging decls or emitting diagnostics as appropriate.
194///
195/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
196/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
197///
198VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
199 // Verify the old decl was also a variable.
200 VarDecl *Old = dyn_cast<VarDecl>(OldD);
201 if (!Old) {
202 Diag(New->getLocation(), diag::err_redefinition_different_kind,
203 New->getName());
204 Diag(OldD->getLocation(), diag::err_previous_definition);
205 return New;
206 }
Steve Narofffb22d962007-08-30 01:06:46 +0000207 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
208 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
209 bool OldIsTentative = false;
210
211 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
212 // Handle C "tentative" external object definitions. FIXME: finish!
213 if (!OldFSDecl->getInit() &&
214 (OldFSDecl->getStorageClass() == VarDecl::None ||
215 OldFSDecl->getStorageClass() == VarDecl::Static))
216 OldIsTentative = true;
217 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000218 // Verify the types match.
219 if (Old->getCanonicalType() != New->getCanonicalType()) {
220 Diag(New->getLocation(), diag::err_redefinition, New->getName());
221 Diag(Old->getLocation(), diag::err_previous_definition);
222 return New;
223 }
224 // We've verified the types match, now check if Old is "extern".
225 if (Old->getStorageClass() != VarDecl::Extern) {
226 Diag(New->getLocation(), diag::err_redefinition, New->getName());
227 Diag(Old->getLocation(), diag::err_previous_definition);
228 }
229 return New;
230}
231
232/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
233/// no declarator (e.g. "struct foo;") is parsed.
234Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
235 // TODO: emit error on 'int;' or 'const enum foo;'.
236 // TODO: emit error on 'typedef int;'
237 // if (!DS.isMissingDeclaratorOk()) Diag(...);
238
239 return 0;
240}
241
242Sema::DeclTy *
Chris Lattner24c39902007-07-12 00:36:32 +0000243Sema::ParseDeclarator(Scope *S, Declarator &D, ExprTy *init,
Reid Spencer5f016e22007-07-11 17:01:13 +0000244 DeclTy *lastDeclarator) {
245 Decl *LastDeclarator = (Decl*)lastDeclarator;
Chris Lattner24c39902007-07-12 00:36:32 +0000246 Expr *Init = static_cast<Expr*>(init);
Reid Spencer5f016e22007-07-11 17:01:13 +0000247 IdentifierInfo *II = D.getIdentifier();
248
Chris Lattnere80a59c2007-07-25 00:24:17 +0000249 // All of these full declarators require an identifier. If it doesn't have
250 // one, the ParsedFreeStandingDeclSpec action should be used.
251 if (II == 0) {
Chris Lattner98e08632007-08-28 06:17:15 +0000252 Diag(D.getDeclSpec().getSourceRange().Begin(),
253 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000254 D.getDeclSpec().getSourceRange(), D.getSourceRange());
255 return 0;
256 }
257
Chris Lattner31e05722007-08-26 06:24:45 +0000258 // The scope passed in may not be a decl scope. Zip up the scope tree until
259 // we find one that is.
260 while ((S->getFlags() & Scope::DeclScope) == 0)
261 S = S->getParent();
262
Reid Spencer5f016e22007-07-11 17:01:13 +0000263 // See if this is a redefinition of a variable in the same scope.
264 Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
265 D.getIdentifierLoc(), S);
266 if (PrevDecl && !S->isDeclScope(PrevDecl))
267 PrevDecl = 0; // If in outer scope, it isn't the same thing.
268
269 Decl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000270 bool InvalidDecl = false;
271
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner24c39902007-07-12 00:36:32 +0000273 assert(Init == 0 && "Can't have initializer for a typedef!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
275 if (!NewTD) return 0;
276
277 // Handle attributes prior to checking for duplicates in MergeVarDecl
278 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
279 D.getAttributes());
280 // Merge the decl with the existing one if appropriate.
281 if (PrevDecl) {
282 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
283 if (NewTD == 0) return 0;
284 }
285 New = NewTD;
286 if (S->getParent() == 0) {
287 // C99 6.7.7p2: If a typedef name specifies a variably modified type
288 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000289 if (const VariableArrayType *VAT =
290 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
291 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
292 VAT->getSizeExpr()->getSourceRange());
293 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 }
295 }
296 } else if (D.isFunctionDeclarator()) {
Chris Lattner24c39902007-07-12 00:36:32 +0000297 assert(Init == 0 && "Can't have an initializer for a functiondecl!");
Steve Naroff5912a352007-08-28 20:14:24 +0000298
Reid Spencer5f016e22007-07-11 17:01:13 +0000299 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000300 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000301
Reid Spencer5f016e22007-07-11 17:01:13 +0000302 FunctionDecl::StorageClass SC;
303 switch (D.getDeclSpec().getStorageClassSpec()) {
304 default: assert(0 && "Unknown storage class!");
305 case DeclSpec::SCS_auto:
306 case DeclSpec::SCS_register:
307 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
308 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000309 InvalidDecl = true;
310 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
312 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
313 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
314 }
315
316 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000317 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000318 LastDeclarator);
319
320 // Merge the decl with the existing one if appropriate.
321 if (PrevDecl) {
322 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
323 if (NewFD == 0) return 0;
324 }
325 New = NewFD;
326 } else {
327 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff53a32342007-08-28 18:45:29 +0000328 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000329
330 VarDecl *NewVD;
331 VarDecl::StorageClass SC;
332 switch (D.getDeclSpec().getStorageClassSpec()) {
333 default: assert(0 && "Unknown storage class!");
334 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
335 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
336 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
337 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
338 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
339 }
340 if (S->getParent() == 0) {
341 // File scope. C99 6.9.2p2: A declaration of an identifier for and
342 // object that has file scope without an initializer, and without a
343 // storage-class specifier or with the storage-class specifier "static",
344 // constitutes a tentative definition. Note: A tentative definition with
345 // external linkage is valid (C99 6.2.2p5).
346 if (!Init && SC == VarDecl::Static) {
347 // C99 6.9.2p3: If the declaration of an identifier for an object is
348 // a tentative definition and has internal linkage (C99 6.2.2p3), the
349 // declared type shall not be an incomplete type.
350 if (R->isIncompleteType()) {
351 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
352 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000353 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000354 }
355 }
356 // C99 6.9p2: The storage-class specifiers auto and register shall not
357 // appear in the declaration specifiers in an external declaration.
358 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
359 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
360 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000361 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 }
Steve Naroffd7444aa2007-08-31 17:20:07 +0000363 if (SC == VarDecl::Static) {
364 // C99 6.7.5.2p2: If an identifier is declared to be an object with
365 // static storage duration, it shall not have a variable length array.
366 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
367 Expr *Size = VLA->getSizeExpr();
368 if (Size || (!Size && !Init)) {
369 // FIXME: Since we don't support initializers yet, we only emit this
370 // error when we don't have an initializer. Once initializers are
371 // implemented, the VLA will change to a CLA.
372 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
373 InvalidDecl = true;
374 }
375 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000376 }
377 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
378 } else {
379 // Block scope. C99 6.7p7: If an identifier for an object is declared with
380 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
381 if (SC != VarDecl::Extern) {
382 if (R->isIncompleteType()) {
383 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
384 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000385 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 }
387 }
388 if (SC == VarDecl::Static) {
389 // C99 6.7.5.2p2: If an identifier is declared to be an object with
390 // static storage duration, it shall not have a variable length array.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000391 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
392 Expr *Size = VLA->getSizeExpr();
393 if (Size || (!Size && !Init)) {
394 // FIXME: Since we don't support initializers yet, we only emit this
395 // error when we don't have an initializer. Once initializers are
396 // implemented, the VLA will change to a CLA.
397 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff53a32342007-08-28 18:45:29 +0000398 InvalidDecl = true;
Steve Naroffd7444aa2007-08-31 17:20:07 +0000399 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 }
401 }
402 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000403 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 // Handle attributes prior to checking for duplicates in MergeVarDecl
405 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
406 D.getAttributes());
407
408 // Merge the decl with the existing one if appropriate.
409 if (PrevDecl) {
410 NewVD = MergeVarDecl(NewVD, PrevDecl);
411 if (NewVD == 0) return 0;
412 }
Steve Narofff1120de2007-08-24 22:33:52 +0000413 if (Init) {
414 AssignmentCheckResult result;
415 result = CheckSingleAssignmentConstraints(R, Init);
416 // FIXME: emit errors if appropriate.
417 NewVD->setInit(Init);
418 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000419 New = NewVD;
420 }
421
422 // If this has an identifier, add it to the scope stack.
423 if (II) {
424 New->setNext(II->getFETokenInfo<Decl>());
425 II->setFETokenInfo(New);
426 S->AddDecl(New);
427 }
428
429 if (S->getParent() == 0)
430 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +0000431
432 // If any semantic error occurred, mark the decl as invalid.
433 if (D.getInvalidType() || InvalidDecl)
434 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000435
436 return New;
437}
438
439/// The declarators are chained together backwards, reverse the list.
440Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
441 // Often we have single declarators, handle them quickly.
442 Decl *Group = static_cast<Decl*>(group);
443 if (Group == 0 || Group->getNextDeclarator() == 0) return Group;
444
445 Decl *NewGroup = 0;
446 while (Group) {
447 Decl *Next = Group->getNextDeclarator();
448 Group->setNextDeclarator(NewGroup);
449 NewGroup = Group;
450 Group = Next;
451 }
452 return NewGroup;
453}
Steve Naroffe1223f72007-08-28 03:03:08 +0000454
455// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000456ParmVarDecl *
457Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
458 Scope *FnScope) {
459 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
460
461 IdentifierInfo *II = PI.Ident;
462 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
463 // Can this happen for params? We already checked that they don't conflict
464 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000465 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 PI.IdentLoc, FnScope)) {
467
468 }
469
470 // FIXME: Handle storage class (auto, register). No declarator?
471 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000472
473 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
474 // Doing the promotion here has a win and a loss. The win is the type for
475 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
476 // code generator). The loss is the orginal type isn't preserved. For example:
477 //
478 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
479 // int blockvardecl[5];
480 // sizeof(parmvardecl); // size == 4
481 // sizeof(blockvardecl); // size == 20
482 // }
483 //
484 // For expressions, all implicit conversions are captured using the
485 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
486 //
487 // FIXME: If a source translation tool needs to see the original type, then
488 // we need to consider storing both types (in ParmVarDecl)...
489 //
490 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
491 if (const ArrayType *AT = parmDeclType->getAsArrayType())
492 parmDeclType = Context.getPointerType(AT->getElementType());
493 else if (parmDeclType->isFunctionType())
494 parmDeclType = Context.getPointerType(parmDeclType);
495
496 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff53a32342007-08-28 18:45:29 +0000497 VarDecl::None, 0);
498 if (PI.InvalidType)
499 New->setInvalidDecl();
500
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 // If this has an identifier, add it to the scope stack.
502 if (II) {
503 New->setNext(II->getFETokenInfo<Decl>());
504 II->setFETokenInfo(New);
505 FnScope->AddDecl(New);
506 }
507
508 return New;
509}
510
511
512Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
513 assert(CurFunctionDecl == 0 && "Function parsing confused");
514 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
515 "Not a function declarator!");
516 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
517
518 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
519 // for a K&R function.
520 if (!FTI.hasPrototype) {
521 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
522 if (FTI.ArgInfo[i].TypeInfo == 0) {
523 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
524 FTI.ArgInfo[i].Ident->getName());
525 // Implicitly declare the argument as type 'int' for lack of a better
526 // type.
527 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
528 }
529 }
530
531 // Since this is a function definition, act as though we have information
532 // about the arguments.
533 FTI.hasPrototype = true;
534 } else {
535 // FIXME: Diagnose arguments without names in C.
536
537 }
538
539 Scope *GlobalScope = FnBodyScope->getParent();
540
541 FunctionDecl *FD =
542 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0, 0));
543 CurFunctionDecl = FD;
544
545 // Create Decl objects for each parameter, adding them to the FunctionDecl.
546 llvm::SmallVector<ParmVarDecl*, 16> Params;
547
548 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
549 // no arguments, not a function that takes a single void argument.
550 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
551 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
552 // empty arg list, don't push any params.
553 } else {
554 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
555 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
556 }
557
558 FD->setParams(&Params[0], Params.size());
559
560 return FD;
561}
562
563Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
564 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
565 FD->setBody((Stmt*)Body);
566
567 assert(FD == CurFunctionDecl && "Function parsing confused");
568 CurFunctionDecl = 0;
569
570 // Verify and clean out per-function state.
571
572 // Check goto/label use.
573 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
574 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
575 // Verify that we have no forward references left. If so, there was a goto
576 // or address of a label taken, but no definition of it. Label fwd
577 // definitions are indicated with a null substmt.
578 if (I->second->getSubStmt() == 0) {
579 LabelStmt *L = I->second;
580 // Emit error.
581 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
582
583 // At this point, we have gotos that use the bogus label. Stitch it into
584 // the function body so that they aren't leaked and that the AST is well
585 // formed.
586 L->setSubStmt(new NullStmt(L->getIdentLoc()));
587 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
588 }
589 }
590 LabelMap.clear();
591
592 return FD;
593}
594
595
596/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
597/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
598Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
599 Scope *S) {
600 if (getLangOptions().C99) // Extension in C99.
601 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
602 else // Legal in C90, but warn about it.
603 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
604
605 // FIXME: handle stuff like:
606 // void foo() { extern float X(); }
607 // void bar() { X(); } <-- implicit decl for X in another scope.
608
609 // Set a Declarator for the implicit definition: int foo();
610 const char *Dummy;
611 DeclSpec DS;
612 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
613 Error = Error; // Silence warning.
614 assert(!Error && "Error setting up implicit decl!");
615 Declarator D(DS, Declarator::BlockContext);
616 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
617 D.SetIdentifier(&II, Loc);
618
619 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000620 if (Scope *FnS = S->getFnParent())
621 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 while (S->getParent())
623 S = S->getParent();
624
625 return static_cast<Decl*>(ParseDeclarator(S, D, 0, 0));
626}
627
628
629TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
630 Decl *LastDeclarator) {
631 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
632
633 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000634 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000635
636 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +0000637 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
638 T, LastDeclarator);
639 if (D.getInvalidType())
640 NewTD->setInvalidDecl();
641 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000642}
643
644
645/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
646/// former case, Name will be non-null. In the later case, Name will be null.
647/// TagType indicates what kind of tag this is. TK indicates whether this is a
648/// reference/declaration/definition of a tag.
649Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
650 SourceLocation KWLoc, IdentifierInfo *Name,
651 SourceLocation NameLoc, AttributeList *Attr) {
652 // If this is a use of an existing tag, it must have a name.
653 assert((Name != 0 || TK == TK_Definition) &&
654 "Nameless record must be a definition!");
655
656 Decl::Kind Kind;
657 switch (TagType) {
658 default: assert(0 && "Unknown tag type!");
659 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
660 case DeclSpec::TST_union: Kind = Decl::Union; break;
661//case DeclSpec::TST_class: Kind = Decl::Class; break;
662 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
663 }
664
665 // If this is a named struct, check to see if there was a previous forward
666 // declaration or definition.
667 if (TagDecl *PrevDecl =
668 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
669 NameLoc, S))) {
670
671 // If this is a use of a previous tag, or if the tag is already declared in
672 // the same scope (so that the definition/declaration completes or
673 // rementions the tag), reuse the decl.
674 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
675 // Make sure that this wasn't declared as an enum and now used as a struct
676 // or something similar.
677 if (PrevDecl->getKind() != Kind) {
678 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
679 Diag(PrevDecl->getLocation(), diag::err_previous_use);
680 }
681
682 // If this is a use or a forward declaration, we're good.
683 if (TK != TK_Definition)
684 return PrevDecl;
685
686 // Diagnose attempts to redefine a tag.
687 if (PrevDecl->isDefinition()) {
688 Diag(NameLoc, diag::err_redefinition, Name->getName());
689 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
690 // If this is a redefinition, recover by making this struct be
691 // anonymous, which will make any later references get the previous
692 // definition.
693 Name = 0;
694 } else {
695 // Okay, this is definition of a previously declared or referenced tag.
696 // Move the location of the decl to be the definition site.
697 PrevDecl->setLocation(NameLoc);
698 return PrevDecl;
699 }
700 }
701 // If we get here, this is a definition of a new struct type in a nested
702 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
703 // type.
704 }
705
706 // If there is an identifier, use the location of the identifier as the
707 // location of the decl, otherwise use the location of the struct/union
708 // keyword.
709 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
710
711 // Otherwise, if this is the first time we've seen this tag, create the decl.
712 TagDecl *New;
713 switch (Kind) {
714 default: assert(0 && "Unknown tag kind!");
715 case Decl::Enum:
716 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
717 // enum X { A, B, C } D; D should chain to X.
718 New = new EnumDecl(Loc, Name, 0);
719 // If this is an undefined enum, warn.
720 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
721 break;
722 case Decl::Union:
723 case Decl::Struct:
724 case Decl::Class:
725 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
726 // struct X { int A; } D; D should chain to X.
727 New = new RecordDecl(Kind, Loc, Name, 0);
728 break;
729 }
730
731 // If this has an identifier, add it to the scope stack.
732 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +0000733 // The scope passed in may not be a decl scope. Zip up the scope tree until
734 // we find one that is.
735 while ((S->getFlags() & Scope::DeclScope) == 0)
736 S = S->getParent();
737
738 // Add it to the decl chain.
Reid Spencer5f016e22007-07-11 17:01:13 +0000739 New->setNext(Name->getFETokenInfo<Decl>());
740 Name->setFETokenInfo(New);
741 S->AddDecl(New);
742 }
743
744 return New;
745}
746
747/// ParseField - Each field of a struct/union/class is passed into this in order
748/// to create a FieldDecl object for it.
749Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
750 SourceLocation DeclStart,
751 Declarator &D, ExprTy *BitfieldWidth) {
752 IdentifierInfo *II = D.getIdentifier();
753 Expr *BitWidth = (Expr*)BitfieldWidth;
754
755 SourceLocation Loc = DeclStart;
756 if (II) Loc = D.getIdentifierLoc();
757
758 // FIXME: Unnamed fields can be handled in various different ways, for
759 // example, unnamed unions inject all members into the struct namespace!
760
761
762 if (BitWidth) {
763 // TODO: Validate.
764 //printf("WARNING: BITFIELDS IGNORED!\n");
765
766 // 6.7.2.1p3
767 // 6.7.2.1p4
768
769 } else {
770 // Not a bitfield.
771
772 // validate II.
773
774 }
775
776 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000777 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
778 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +0000779
Reid Spencer5f016e22007-07-11 17:01:13 +0000780 // C99 6.7.2.1p8: A member of a structure or union may have any type other
781 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000782 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
783 Diag(Loc, diag::err_typecheck_illegal_vla,
784 VAT->getSizeExpr()->getSourceRange());
785 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 // FIXME: Chain fielddecls together.
Steve Naroff5912a352007-08-28 20:14:24 +0000788 FieldDecl *NewFD = new FieldDecl(Loc, II, T, 0);
789 if (D.getInvalidType() || InvalidDecl)
790 NewFD->setInvalidDecl();
791 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000792}
793
794void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
795 DeclTy **Fields, unsigned NumFields) {
796 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
797 if (Record->isDefinition()) {
798 // Diagnose code like:
799 // struct S { struct S {} X; };
800 // We discover this when we complete the outer S. Reject and ignore the
801 // outer S.
802 Diag(Record->getLocation(), diag::err_nested_redefinition,
803 Record->getKindName());
804 Diag(RecLoc, diag::err_previous_definition);
805 return;
806 }
807
808 // Verify that all the fields are okay.
809 unsigned NumNamedMembers = 0;
810 llvm::SmallVector<FieldDecl*, 32> RecFields;
811 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
812
813 for (unsigned i = 0; i != NumFields; ++i) {
814 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
815 if (!FD) continue; // Already issued a diagnostic.
816
817 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +0000818 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +0000819
820 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +0000821 if (FDTy->isFunctionType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 Diag(FD->getLocation(), diag::err_field_declared_as_function,
823 FD->getName());
824 delete FD;
825 continue;
826 }
827
828 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
829 if (FDTy->isIncompleteType()) {
830 if (i != NumFields-1 || // ... that the last member ...
831 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +0000832 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000833 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
834 delete FD;
835 continue;
836 }
837 if (NumNamedMembers < 1) { //... must have more than named member ...
838 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
839 FD->getName());
840 delete FD;
841 continue;
842 }
843
844 // Okay, we have a legal flexible array member at the end of the struct.
845 Record->setHasFlexibleArrayMember(true);
846 }
847
848
849 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
850 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +0000851 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000852 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
853 // If this is a member of a union, then entire union becomes "flexible".
854 if (Record->getKind() == Decl::Union) {
855 Record->setHasFlexibleArrayMember(true);
856 } else {
857 // If this is a struct/class and this is not the last element, reject
858 // it. Note that GCC supports variable sized arrays in the middle of
859 // structures.
860 if (i != NumFields-1) {
861 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
862 FD->getName());
863 delete FD;
864 continue;
865 }
866
867 // We support flexible arrays at the end of structs in other structs
868 // as an extension.
869 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
870 FD->getName());
871 Record->setHasFlexibleArrayMember(true);
872 }
873 }
874 }
875
876 // Keep track of the number of named members.
877 if (IdentifierInfo *II = FD->getIdentifier()) {
878 // Detect duplicate member names.
879 if (!FieldIDs.insert(II)) {
880 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
881 // Find the previous decl.
882 SourceLocation PrevLoc;
883 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
884 assert(i != e && "Didn't find previous def!");
885 if (RecFields[i]->getIdentifier() == II) {
886 PrevLoc = RecFields[i]->getLocation();
887 break;
888 }
889 }
890 Diag(PrevLoc, diag::err_previous_definition);
891 delete FD;
892 continue;
893 }
894 ++NumNamedMembers;
895 }
896
897 // Remember good fields.
898 RecFields.push_back(FD);
899 }
900
901
902 // Okay, we successfully defined 'Record'.
903 Record->defineBody(&RecFields[0], RecFields.size());
904}
905
906Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
907 DeclTy *lastEnumConst,
908 SourceLocation IdLoc, IdentifierInfo *Id,
909 SourceLocation EqualLoc, ExprTy *val) {
910 theEnumDecl = theEnumDecl; // silence unused warning.
911 EnumConstantDecl *LastEnumConst =
912 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
913 Expr *Val = static_cast<Expr*>(val);
914
Chris Lattner31e05722007-08-26 06:24:45 +0000915 // The scope passed in may not be a decl scope. Zip up the scope tree until
916 // we find one that is.
917 while ((S->getFlags() & Scope::DeclScope) == 0)
918 S = S->getParent();
919
Reid Spencer5f016e22007-07-11 17:01:13 +0000920 // Verify that there isn't already something declared with this name in this
921 // scope.
922 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
923 if (S->isDeclScope(PrevDecl)) {
924 if (isa<EnumConstantDecl>(PrevDecl))
925 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
926 else
927 Diag(IdLoc, diag::err_redefinition, Id->getName());
928 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
929 // FIXME: Don't leak memory: delete Val;
930 return 0;
931 }
932 }
933
934 llvm::APSInt EnumVal(32);
935 QualType EltTy;
936 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +0000937 // Make sure to promote the operand type to int.
938 UsualUnaryConversions(Val);
939
Reid Spencer5f016e22007-07-11 17:01:13 +0000940 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
941 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +0000942 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000943 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
944 Id->getName());
945 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +0000946 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +0000947 } else {
948 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000949 }
Chris Lattnerb7416f92007-08-27 17:37:24 +0000950 }
951
952 if (!Val) {
953 if (LastEnumConst) {
954 // Assign the last value + 1.
955 EnumVal = LastEnumConst->getInitVal();
956 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +0000957
958 // Check for overflow on increment.
959 if (EnumVal < LastEnumConst->getInitVal())
960 Diag(IdLoc, diag::warn_enum_value_overflow);
961
Chris Lattnerb7416f92007-08-27 17:37:24 +0000962 EltTy = LastEnumConst->getType();
963 } else {
964 // First value, set to zero.
965 EltTy = Context.IntTy;
Chris Lattner421a23d2007-08-27 21:16:18 +0000966 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy, IdLoc));
Chris Lattnerb7416f92007-08-27 17:37:24 +0000967 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000968 }
969
Reid Spencer5f016e22007-07-11 17:01:13 +0000970 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
971 LastEnumConst);
972
973 // Register this decl in the current scope stack.
974 New->setNext(Id->getFETokenInfo<Decl>());
975 Id->setFETokenInfo(New);
976 S->AddDecl(New);
977 return New;
978}
979
980void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
981 DeclTy **Elements, unsigned NumElements) {
982 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
983 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
984
Chris Lattnere37f0be2007-08-28 05:10:31 +0000985 // TODO: If the result value doesn't fit in an int, it must be a long or long
986 // long value. ISO C does not support this, but GCC does as an extension,
987 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +0000988 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +0000989
990
Chris Lattnerac609682007-08-28 06:15:15 +0000991 // Verify that all the values are okay, compute the size of the values, and
992 // reverse the list.
993 unsigned NumNegativeBits = 0;
994 unsigned NumPositiveBits = 0;
995
996 // Keep track of whether all elements have type int.
997 bool AllElementsInt = true;
998
Reid Spencer5f016e22007-07-11 17:01:13 +0000999 EnumConstantDecl *EltList = 0;
1000 for (unsigned i = 0; i != NumElements; ++i) {
1001 EnumConstantDecl *ECD =
1002 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1003 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001004
1005 // If the enum value doesn't fit in an int, emit an extension warning.
1006 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1007 "Should have promoted value to int");
1008 const llvm::APSInt &InitVal = ECD->getInitVal();
1009 if (InitVal.getBitWidth() > IntWidth) {
1010 llvm::APSInt V(InitVal);
1011 V.trunc(IntWidth);
1012 V.extend(InitVal.getBitWidth());
1013 if (V != InitVal)
1014 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1015 InitVal.toString());
1016 }
Chris Lattnerac609682007-08-28 06:15:15 +00001017
1018 // Keep track of the size of positive and negative values.
1019 if (InitVal.isUnsigned() || !InitVal.isNegative())
1020 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1021 else
1022 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001023
Chris Lattnerac609682007-08-28 06:15:15 +00001024 // Keep track of whether every enum element has type int (very commmon).
1025 if (AllElementsInt)
1026 AllElementsInt = ECD->getType() == Context.IntTy;
1027
Reid Spencer5f016e22007-07-11 17:01:13 +00001028 ECD->setNextDeclarator(EltList);
1029 EltList = ECD;
1030 }
1031
Chris Lattnerac609682007-08-28 06:15:15 +00001032 // Figure out the type that should be used for this enum.
1033 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1034 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001035 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001036
1037 if (NumNegativeBits) {
1038 // If there is a negative value, figure out the smallest integer type (of
1039 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001040 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001041 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001042 BestWidth = IntWidth;
1043 } else {
1044 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1045 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001046 BestType = Context.LongTy;
1047 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001048 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1049 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001050 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1051 BestType = Context.LongLongTy;
1052 }
1053 }
1054 } else {
1055 // If there is no negative value, figure out which of uint, ulong, ulonglong
1056 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001057 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001058 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001059 BestWidth = IntWidth;
1060 } else if (NumPositiveBits <=
1061 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001062 BestType = Context.UnsignedLongTy;
1063 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001064 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1065 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001066 "How could an initializer get larger than ULL?");
1067 BestType = Context.UnsignedLongLongTy;
1068 }
1069 }
1070
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001071 // Loop over all of the enumerator constants, changing their types to match
1072 // the type of the enum if needed.
1073 for (unsigned i = 0; i != NumElements; ++i) {
1074 EnumConstantDecl *ECD =
1075 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1076 if (!ECD) continue; // Already issued a diagnostic.
1077
1078 // Standard C says the enumerators have int type, but we allow, as an
1079 // extension, the enumerators to be larger than int size. If each
1080 // enumerator value fits in an int, type it as an int, otherwise type it the
1081 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1082 // that X has type 'int', not 'unsigned'.
1083 if (ECD->getType() == Context.IntTy)
1084 continue; // Already int type.
1085
1086 // Determine whether the value fits into an int.
1087 llvm::APSInt InitVal = ECD->getInitVal();
1088 bool FitsInInt;
1089 if (InitVal.isUnsigned() || !InitVal.isNegative())
1090 FitsInInt = InitVal.getActiveBits() < IntWidth;
1091 else
1092 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1093
1094 // If it fits into an integer type, force it. Otherwise force it to match
1095 // the enum decl type.
1096 QualType NewTy;
1097 unsigned NewWidth;
1098 bool NewSign;
1099 if (FitsInInt) {
1100 NewTy = Context.IntTy;
1101 NewWidth = IntWidth;
1102 NewSign = true;
1103 } else if (ECD->getType() == BestType) {
1104 // Already the right type!
1105 continue;
1106 } else {
1107 NewTy = BestType;
1108 NewWidth = BestWidth;
1109 NewSign = BestType->isSignedIntegerType();
1110 }
1111
1112 // Adjust the APSInt value.
1113 InitVal.extOrTrunc(NewWidth);
1114 InitVal.setIsSigned(NewSign);
1115 ECD->setInitVal(InitVal);
1116
1117 // Adjust the Expr initializer and type.
1118 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1119 ECD->setType(NewTy);
1120 }
Chris Lattnerac609682007-08-28 06:15:15 +00001121
Chris Lattnere00b18c2007-08-28 18:24:31 +00001122 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001123}
1124
1125void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1126 if (!current) return;
1127
1128 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1129 // remember this in the LastInGroupList list.
1130 if (last)
1131 LastInGroupList.push_back((Decl*)last);
1132}
1133
1134void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1135 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1136 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1137 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1138 if (!newType.isNull()) // install the new vector type into the decl
1139 vDecl->setType(newType);
1140 }
1141 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1142 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1143 rawAttr);
1144 if (!newType.isNull()) // install the new vector type into the decl
1145 tDecl->setUnderlyingType(newType);
1146 }
1147 }
Steve Naroff73322922007-07-18 18:00:27 +00001148 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001149 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1150 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1151 else
Steve Naroff73322922007-07-18 18:00:27 +00001152 Diag(rawAttr->getAttributeLoc(),
1153 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00001154 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 // FIXME: add other attributes...
1156}
1157
1158void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1159 AttributeList *declarator_postfix) {
1160 while (declspec_prefix) {
1161 HandleDeclAttribute(New, declspec_prefix);
1162 declspec_prefix = declspec_prefix->getNext();
1163 }
1164 while (declarator_postfix) {
1165 HandleDeclAttribute(New, declarator_postfix);
1166 declarator_postfix = declarator_postfix->getNext();
1167 }
1168}
1169
Steve Naroffbea0b342007-07-29 16:33:31 +00001170void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1171 AttributeList *rawAttr) {
1172 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00001173 // check the attribute arugments.
1174 if (rawAttr->getNumArgs() != 1) {
1175 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1176 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001177 return;
Steve Naroff73322922007-07-18 18:00:27 +00001178 }
1179 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1180 llvm::APSInt vecSize(32);
1181 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1182 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1183 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001184 return;
Steve Naroff73322922007-07-18 18:00:27 +00001185 }
1186 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1187 // in conjunction with complex types (pointers, arrays, functions, etc.).
1188 Type *canonType = curType.getCanonicalType().getTypePtr();
1189 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1190 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1191 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001192 return;
Steve Naroff73322922007-07-18 18:00:27 +00001193 }
1194 // unlike gcc's vector_size attribute, the size is specified as the
1195 // number of elements, not the number of bytes.
1196 unsigned vectorSize = vecSize.getZExtValue();
1197
1198 if (vectorSize == 0) {
1199 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1200 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001201 return;
Steve Naroff73322922007-07-18 18:00:27 +00001202 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001203 // Instantiate/Install the vector type, the number of elements is > 0.
1204 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1205 // Remember this typedef decl, we will need it later for diagnostics.
1206 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001207}
1208
Reid Spencer5f016e22007-07-11 17:01:13 +00001209QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001210 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001211 // check the attribute arugments.
1212 if (rawAttr->getNumArgs() != 1) {
1213 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1214 std::string("1"));
1215 return QualType();
1216 }
1217 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1218 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001219 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001220 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1221 sizeExpr->getSourceRange());
1222 return QualType();
1223 }
1224 // navigate to the base type - we need to provide for vector pointers,
1225 // vector arrays, and functions returning vectors.
1226 Type *canonType = curType.getCanonicalType().getTypePtr();
1227
Steve Naroff73322922007-07-18 18:00:27 +00001228 if (canonType->isPointerType() || canonType->isArrayType() ||
1229 canonType->isFunctionType()) {
1230 assert(1 && "HandleVector(): Complex type construction unimplemented");
1231 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1232 do {
1233 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1234 canonType = PT->getPointeeType().getTypePtr();
1235 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1236 canonType = AT->getElementType().getTypePtr();
1237 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1238 canonType = FT->getResultType().getTypePtr();
1239 } while (canonType->isPointerType() || canonType->isArrayType() ||
1240 canonType->isFunctionType());
1241 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 }
1243 // the base type must be integer or float.
1244 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1245 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1246 curType.getCanonicalType().getAsString());
1247 return QualType();
1248 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001249 unsigned typeSize = Context.getTypeSize(curType, rawAttr->getAttributeLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +00001250 // vecSize is specified in bytes - convert to bits.
1251 unsigned vectorSize = vecSize.getZExtValue() * 8;
1252
1253 // the vector size needs to be an integral multiple of the type size.
1254 if (vectorSize % typeSize) {
1255 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1256 sizeExpr->getSourceRange());
1257 return QualType();
1258 }
1259 if (vectorSize == 0) {
1260 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1261 sizeExpr->getSourceRange());
1262 return QualType();
1263 }
1264 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1265 // the number of elements to be a power of two (unlike GCC).
1266 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00001267 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001268}
1269