blob: 1165e526d8de942a78befeb3e1e91e557988b95c [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
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"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/TargetInfo.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000024#include "llvm/ADT/SmallString.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian67907bd2007-10-05 18:00:57 +000026#include "llvm/ADT/DenseSet.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Chris Lattner4b009652007-07-25 00:24:17 +000029Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000030 Decl *IIDecl = II.getFETokenInfo<Decl>();
31 // Find first occurance of none-tagged declaration
32 while(IIDecl && IIDecl->getIdentifierNamespace() != Decl::IDNS_Ordinary)
33 IIDecl = cast<ScopedDecl>(IIDecl)->getNext();
34 if (!IIDecl)
35 return 0;
36 if (isa<TypedefDecl>(IIDecl) || isa<ObjcInterfaceDecl>(IIDecl))
37 return IIDecl;
38 if (ObjcCompatibleAliasDecl *ADecl =
39 dyn_cast<ObjcCompatibleAliasDecl>(IIDecl))
40 return ADecl->getClassInterface();
Steve Naroff81f1bba2007-09-06 21:24:23 +000041 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000042}
43
Steve Naroff9637a9b2007-10-09 22:01:59 +000044void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000045 if (S->decl_empty()) return;
46 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
47
Chris Lattner4b009652007-07-25 00:24:17 +000048 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
49 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +000050 Decl *TmpD = static_cast<Decl*>(*I);
51 assert(TmpD && "This decl didn't get pushed??");
52 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
53 assert(D && "This decl isn't a ScopedDecl?");
54
Chris Lattner4b009652007-07-25 00:24:17 +000055 IdentifierInfo *II = D->getIdentifier();
56 if (!II) continue;
57
58 // Unlink this decl from the identifier. Because the scope contains decls
59 // in an unordered collection, and because we have multiple identifier
60 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
61 if (II->getFETokenInfo<Decl>() == D) {
62 // Normal case, no multiple decls in different namespaces.
63 II->setFETokenInfo(D->getNext());
64 } else {
65 // Scan ahead. There are only three namespaces in C, so this loop can
66 // never execute more than 3 times.
Steve Naroffd21bc0d2007-09-13 18:10:37 +000067 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Chris Lattner4b009652007-07-25 00:24:17 +000068 while (SomeDecl->getNext() != D) {
69 SomeDecl = SomeDecl->getNext();
70 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
71 }
72 SomeDecl->setNext(D->getNext());
73 }
74
75 // This will have to be revisited for C++: there we want to nest stuff in
76 // namespace decls etc. Even for C, we might want a top-level translation
77 // unit decl or something.
78 if (!CurFunctionDecl)
79 continue;
80
81 // Chain this decl to the containing function, it now owns the memory for
82 // the decl.
83 D->setNext(CurFunctionDecl->getDeclChain());
84 CurFunctionDecl->setDeclChain(D);
85 }
86}
87
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +000088/// LookupInterfaceDecl - Lookup interface declaration in the scope chain.
89/// Return the first declaration found (which may or may not be a class
Fariborz Jahanian8eaeff52007-10-12 19:53:08 +000090/// declaration. Caller is responsible for handling the none-class case.
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +000091/// Bypassing the alias of a class by returning the aliased class.
92ScopedDecl *Sema::LookupInterfaceDecl(IdentifierInfo *ClassName) {
93 ScopedDecl *IDecl;
94 // Scan up the scope chain looking for a decl that matches this identifier
95 // that is in the appropriate namespace.
96 for (IDecl = ClassName->getFETokenInfo<ScopedDecl>(); IDecl;
97 IDecl = IDecl->getNext())
98 if (IDecl->getIdentifierNamespace() == Decl::IDNS_Ordinary)
99 break;
100
101 if (ObjcCompatibleAliasDecl *ADecl =
102 dyn_cast_or_null<ObjcCompatibleAliasDecl>(IDecl))
103 return ADecl->getClassInterface();
104 return IDecl;
105}
106
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +0000107/// getObjcInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +0000108/// return 0 if one not found.
Steve Narofffa465d12007-10-02 20:01:56 +0000109ObjcInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000110 ScopedDecl *IdDecl = LookupInterfaceDecl(Id);
111 return cast_or_null<ObjcInterfaceDecl>(IdDecl);
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +0000112}
113
Chris Lattner4b009652007-07-25 00:24:17 +0000114/// LookupScopedDecl - Look up the inner-most declaration in the specified
115/// namespace.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000116ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
117 SourceLocation IdLoc, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000118 if (II == 0) return 0;
119 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
120
121 // Scan up the scope chain looking for a decl that matches this identifier
122 // that is in the appropriate namespace. This search should not take long, as
123 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000124 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner4b009652007-07-25 00:24:17 +0000125 if (D->getIdentifierNamespace() == NS)
126 return D;
127
128 // If we didn't find a use of this identifier, and if the identifier
129 // corresponds to a compiler builtin, create the decl object for the builtin
130 // now, injecting it into translation unit scope, and return it.
131 if (NS == Decl::IDNS_Ordinary) {
132 // If this is a builtin on some other target, or if this builtin varies
133 // across targets (e.g. in type), emit a diagnostic and mark the translation
134 // unit non-portable for using it.
135 if (II->isNonPortableBuiltin()) {
136 // Only emit this diagnostic once for this builtin.
137 II->setNonPortableBuiltin(false);
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000138 Context.Target.DiagnoseNonPortability(Context.getFullLoc(IdLoc),
Chris Lattner4b009652007-07-25 00:24:17 +0000139 diag::port_target_builtin_use);
140 }
141 // If this is a builtin on this (or all) targets, create the decl.
142 if (unsigned BuiltinID = II->getBuiltinID())
143 return LazilyCreateBuiltin(II, BuiltinID, S);
144 }
145 return 0;
146}
147
Anders Carlsson36760332007-10-15 20:28:48 +0000148void Sema::InitBuiltinVaListType()
149{
150 if (!Context.getBuiltinVaListType().isNull())
151 return;
152
153 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
154 ScopedDecl *VaDecl = LookupScopedDecl(VaIdent, Decl::IDNS_Ordinary,
155 SourceLocation(), TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000156 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000157 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
158}
159
Chris Lattner4b009652007-07-25 00:24:17 +0000160/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
161/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000162ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
163 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000164 Builtin::ID BID = (Builtin::ID)bid;
165
Anders Carlsson36760332007-10-15 20:28:48 +0000166 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000167 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson36760332007-10-15 20:28:48 +0000168 BID == Builtin::BI__builtin_va_end)
169 InitBuiltinVaListType();
170
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000171 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner4b009652007-07-25 00:24:17 +0000172 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner987058a2007-08-26 04:02:13 +0000173 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000174
175 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000176 if (Scope *FnS = S->getFnParent())
177 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000178 while (S->getParent())
179 S = S->getParent();
180 S->AddDecl(New);
181
182 // Add this decl to the end of the identifier info.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000183 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000184 // Scan until we find the last (outermost) decl in the id chain.
185 while (LastDecl->getNext())
186 LastDecl = LastDecl->getNext();
187 // Insert before (outside) it.
188 LastDecl->setNext(New);
189 } else {
190 II->setFETokenInfo(New);
191 }
Chris Lattner4b009652007-07-25 00:24:17 +0000192 return New;
193}
194
195/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
196/// and scope as a previous declaration 'Old'. Figure out how to resolve this
197/// situation, merging decls or emitting diagnostics as appropriate.
198///
Steve Naroffcb597472007-09-13 21:41:19 +0000199TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000200 // Verify the old decl was also a typedef.
201 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
202 if (!Old) {
203 Diag(New->getLocation(), diag::err_redefinition_different_kind,
204 New->getName());
205 Diag(OldD->getLocation(), diag::err_previous_definition);
206 return New;
207 }
208
Steve Naroffae84af82007-10-31 18:42:27 +0000209 // Allow multiple definitions for ObjC built-in typedefs.
210 // FIXME: Verify the underlying types are equivalent!
Chris Lattner855e51f2007-12-12 07:09:47 +0000211 if (getLangOptions().ObjC1 && isBuiltinObjcType(New))
Steve Naroffae84af82007-10-31 18:42:27 +0000212 return Old;
213
Chris Lattner4b009652007-07-25 00:24:17 +0000214 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
215 // TODO: This is totally simplistic. It should handle merging functions
216 // together etc, merging extern int X; int X; ...
217 Diag(New->getLocation(), diag::err_redefinition, New->getName());
218 Diag(Old->getLocation(), diag::err_previous_definition);
219 return New;
220}
221
222/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
223/// and scope as a previous declaration 'Old'. Figure out how to resolve this
224/// situation, merging decls or emitting diagnostics as appropriate.
225///
Steve Naroffcb597472007-09-13 21:41:19 +0000226FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000227 // Verify the old decl was also a function.
228 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
229 if (!Old) {
230 Diag(New->getLocation(), diag::err_redefinition_different_kind,
231 New->getName());
232 Diag(OldD->getLocation(), diag::err_previous_definition);
233 return New;
234 }
235
Chris Lattner60476ff2007-11-20 19:04:50 +0000236 QualType OldQType = Old->getCanonicalType();
237 QualType NewQType = New->getCanonicalType();
238
239 // This is not right, but it's a start.
240 // If Old is a function prototype with no defined arguments we only compare
241 // the return type; If arguments are defined on the prototype we validate the
242 // entire function type.
243 // FIXME: We should link up decl objects here.
244 if (Old->getBody() == 0) {
245 if (OldQType.getTypePtr()->getTypeClass() == Type::FunctionNoProto &&
246 Old->getResultType() == New->getResultType())
247 return New;
248 if (OldQType == NewQType)
249 return New;
Chris Lattner4b009652007-07-25 00:24:17 +0000250 }
Chris Lattner1470b072007-11-06 06:07:26 +0000251
Chris Lattner60476ff2007-11-20 19:04:50 +0000252 if (New->getBody() == 0 && OldQType == NewQType) {
Chris Lattner1470b072007-11-06 06:07:26 +0000253 return 0;
254 }
Chris Lattner4b009652007-07-25 00:24:17 +0000255
256 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
257 // TODO: This is totally simplistic. It should handle merging functions
258 // together etc, merging extern int X; int X; ...
259 Diag(New->getLocation(), diag::err_redefinition, New->getName());
260 Diag(Old->getLocation(), diag::err_previous_definition);
261 return New;
262}
263
Chris Lattnerf9167d12007-11-06 04:28:31 +0000264
265/// hasUndefinedLength - Used by equivalentArrayTypes to determine whether the
266/// the outermost VariableArrayType has no size defined.
267static bool hasUndefinedLength(const ArrayType *Array) {
268 const VariableArrayType *VAT = Array->getAsVariableArrayType();
269 return VAT && !VAT->getSizeExpr();
270}
271
272/// equivalentArrayTypes - Used to determine whether two array types are
273/// equivalent.
274/// We need to check this explicitly as an incomplete array definition is
275/// considered a VariableArrayType, so will not match a complete array
276/// definition that would be otherwise equivalent.
277static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
278 const ArrayType *NewAT = NewQType->getAsArrayType();
279 const ArrayType *OldAT = OldQType->getAsArrayType();
280
281 if (!NewAT || !OldAT)
282 return false;
283
284 // If either (or both) array types in incomplete we need to strip off the
285 // outer VariableArrayType. Once the outer VAT is removed the remaining
286 // types must be identical if the array types are to be considered
287 // equivalent.
288 // eg. int[][1] and int[1][1] become
289 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
290 // removing the outermost VAT gives
291 // CAT(1, int) and CAT(1, int)
292 // which are equal, therefore the array types are equivalent.
293 if (hasUndefinedLength(NewAT) || hasUndefinedLength(OldAT)) {
294 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
295 return false;
296 NewQType = NewAT->getElementType();
297 OldQType = OldAT->getElementType();
298 }
299
300 return NewQType == OldQType;
301}
302
Chris Lattner4b009652007-07-25 00:24:17 +0000303/// MergeVarDecl - We just parsed a variable 'New' which has the same name
304/// and scope as a previous declaration 'Old'. Figure out how to resolve this
305/// situation, merging decls or emitting diagnostics as appropriate.
306///
307/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
308/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
309///
Steve Naroffcb597472007-09-13 21:41:19 +0000310VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000311 // Verify the old decl was also a variable.
312 VarDecl *Old = dyn_cast<VarDecl>(OldD);
313 if (!Old) {
314 Diag(New->getLocation(), diag::err_redefinition_different_kind,
315 New->getName());
316 Diag(OldD->getLocation(), diag::err_previous_definition);
317 return New;
318 }
Steve Naroff83c13012007-08-30 01:06:46 +0000319 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
320 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
321 bool OldIsTentative = false;
322
323 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
324 // Handle C "tentative" external object definitions. FIXME: finish!
325 if (!OldFSDecl->getInit() &&
326 (OldFSDecl->getStorageClass() == VarDecl::None ||
327 OldFSDecl->getStorageClass() == VarDecl::Static))
328 OldIsTentative = true;
329 }
Chris Lattner4b009652007-07-25 00:24:17 +0000330 // Verify the types match.
Chris Lattnerf9167d12007-11-06 04:28:31 +0000331 if (Old->getCanonicalType() != New->getCanonicalType() &&
332 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Chris Lattner4b009652007-07-25 00:24:17 +0000333 Diag(New->getLocation(), diag::err_redefinition, New->getName());
334 Diag(Old->getLocation(), diag::err_previous_definition);
335 return New;
336 }
337 // We've verified the types match, now check if Old is "extern".
338 if (Old->getStorageClass() != VarDecl::Extern) {
339 Diag(New->getLocation(), diag::err_redefinition, New->getName());
340 Diag(Old->getLocation(), diag::err_previous_definition);
341 }
342 return New;
343}
344
345/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
346/// no declarator (e.g. "struct foo;") is parsed.
347Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
348 // TODO: emit error on 'int;' or 'const enum foo;'.
349 // TODO: emit error on 'typedef int;'
350 // if (!DS.isMissingDeclaratorOk()) Diag(...);
351
Steve Naroffedafc0b2007-11-17 21:37:36 +0000352 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000353}
354
Anders Carlsson855d78d2007-10-17 00:52:43 +0000355bool Sema::CheckSingleInitializer(Expr *&Init, bool isStatic,
356 QualType DeclType) {
Anders Carlsson855d78d2007-10-17 00:52:43 +0000357 // FIXME: Remove the isReferenceType check and handle assignment
358 // to a reference.
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000359 SourceLocation loc;
Anders Carlsson855d78d2007-10-17 00:52:43 +0000360 if (isStatic && !DeclType->isReferenceType() &&
361 !Init->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000362 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
Anders Carlsson855d78d2007-10-17 00:52:43 +0000363 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
364 return true;
365 }
366
Steve Naroffe14e5542007-09-02 02:04:30 +0000367 AssignmentCheckResult result;
Steve Naroffe14e5542007-09-02 02:04:30 +0000368 // Get the type before calling CheckSingleAssignmentConstraints(), since
369 // it can promote the expression.
370 QualType rhsType = Init->getType();
371
372 result = CheckSingleAssignmentConstraints(DeclType, Init);
373
374 // decode the result (notice that extensions still return a type).
375 switch (result) {
376 case Compatible:
377 break;
378 case Incompatible:
Steve Naroff9091f3f2007-09-02 15:34:30 +0000379 // FIXME: tighten up this check which should allow:
380 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
381 if (rhsType == Context.getPointerType(Context.CharTy))
382 break;
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000383 Diag(Init->getLocStart(), diag::err_typecheck_assign_incompatible,
Steve Naroffe14e5542007-09-02 02:04:30 +0000384 DeclType.getAsString(), rhsType.getAsString(),
385 Init->getSourceRange());
386 return true;
387 case PointerFromInt:
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000388 Diag(Init->getLocStart(), diag::ext_typecheck_assign_pointer_int,
Steve Naroffcdee22d2007-11-27 17:58:44 +0000389 DeclType.getAsString(), rhsType.getAsString(),
390 Init->getSourceRange());
Steve Naroffe14e5542007-09-02 02:04:30 +0000391 break;
392 case IntFromPointer:
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000393 Diag(Init->getLocStart(), diag::ext_typecheck_assign_pointer_int,
Steve Naroffe14e5542007-09-02 02:04:30 +0000394 DeclType.getAsString(), rhsType.getAsString(),
395 Init->getSourceRange());
396 break;
Chris Lattner4ca3d772008-01-03 22:56:36 +0000397 case FunctionVoidPointer:
398 Diag(Init->getLocStart(), diag::ext_typecheck_assign_pointer_void_func,
399 DeclType.getAsString(), rhsType.getAsString(),
400 Init->getSourceRange());
401 break;
Steve Naroffe14e5542007-09-02 02:04:30 +0000402 case IncompatiblePointer:
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000403 Diag(Init->getLocStart(), diag::ext_typecheck_assign_incompatible_pointer,
Steve Naroffe14e5542007-09-02 02:04:30 +0000404 DeclType.getAsString(), rhsType.getAsString(),
405 Init->getSourceRange());
406 break;
407 case CompatiblePointerDiscardsQualifiers:
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000408 Diag(Init->getLocStart(), diag::ext_typecheck_assign_discards_qualifiers,
Steve Naroffe14e5542007-09-02 02:04:30 +0000409 DeclType.getAsString(), rhsType.getAsString(),
410 Init->getSourceRange());
411 break;
412 }
413 return false;
414}
415
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000416bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
417 bool isStatic, QualType ElementType) {
Steve Naroff509d0b52007-09-04 02:20:04 +0000418 SourceLocation loc;
Steve Naroff509d0b52007-09-04 02:20:04 +0000419 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000420 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
Steve Naroff509d0b52007-09-04 02:20:04 +0000421 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
422 return true;
Steve Naroff509d0b52007-09-04 02:20:04 +0000423 }
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000424
425 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
426 if (CheckSingleInitializer(expr, isStatic, ElementType))
427 return true; // types weren't compatible.
428
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000429 if (savExpr != expr) // The type was promoted, update initializer list.
430 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000431 return false;
432}
433
434void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
435 QualType ElementType, bool isStatic,
436 int &nInitializers, bool &hadError) {
Steve Naroffcb69fb72007-12-10 22:44:33 +0000437 unsigned numInits = IList->getNumInits();
438
439 if (numInits) {
440 if (CheckForCharArrayInitializer(IList, ElementType, nInitializers,
441 false, hadError))
442 return;
443
444 for (unsigned i = 0; i < numInits; i++) {
445 Expr *expr = IList->getInit(i);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000446
Steve Naroffcb69fb72007-12-10 22:44:33 +0000447 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
448 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
449 int maxElements = CAT->getMaximumElements();
450 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
451 maxElements, hadError);
452 }
453 } else {
454 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
455 }
456 nInitializers++;
457 }
458 } else {
459 Diag(IList->getLocStart(),
460 diag::err_at_least_one_initializer_needed_to_size_array);
461 hadError = true;
462 }
463}
464
465bool Sema::CheckForCharArrayInitializer(InitListExpr *IList,
466 QualType ElementType,
467 int &nInitializers, bool isConstant,
468 bool &hadError)
469{
470 if (ElementType->isPointerType())
471 return false;
472
473 if (StringLiteral *literal = dyn_cast<StringLiteral>(IList->getInit(0))) {
474 // FIXME: Handle wide strings
475 if (ElementType->isCharType()) {
476 if (isConstant) {
477 if (literal->getByteLength() > (unsigned)nInitializers) {
478 Diag(literal->getSourceRange().getBegin(),
479 diag::warn_initializer_string_for_char_array_too_long,
480 literal->getSourceRange());
481 }
482 } else {
483 nInitializers = literal->getByteLength() + 1;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000484 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000485 } else {
Steve Naroffcb69fb72007-12-10 22:44:33 +0000486 // FIXME: It might be better if we could point to the declaration
487 // here, instead of the string literal.
488 Diag(literal->getSourceRange().getBegin(),
489 diag::array_of_wrong_type_initialized_from_string,
490 ElementType.getAsString());
491 hadError = true;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000492 }
Steve Naroffcb69fb72007-12-10 22:44:33 +0000493
494 // Check for excess initializers
495 for (unsigned i = 1; i < IList->getNumInits(); i++) {
496 Expr *expr = IList->getInit(i);
497 Diag(expr->getLocStart(),
498 diag::err_excess_initializers_in_char_array_initializer,
499 expr->getSourceRange());
500 }
501
502 return true;
Steve Naroff509d0b52007-09-04 02:20:04 +0000503 }
Steve Naroffcb69fb72007-12-10 22:44:33 +0000504
505 return false;
Steve Naroff509d0b52007-09-04 02:20:04 +0000506}
507
508// FIXME: Doesn't deal with arrays of structures yet.
509void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
510 QualType ElementType, bool isStatic,
511 int &totalInits, bool &hadError) {
512 int maxElementsAtThisLevel = 0;
513 int nInitsAtLevel = 0;
514
Steve Naroff4a4b2062007-12-07 21:12:53 +0000515 if (ElementType->isRecordType()) // FIXME: until we support structures...
516 return;
517
Steve Naroff509d0b52007-09-04 02:20:04 +0000518 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
519 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff4f910992007-09-04 21:13:33 +0000520 maxElementsAtThisLevel = CAT->getMaximumElements();
521 // Set DeclType, used below to recurse (for multi-dimensional arrays).
522 DeclType = CAT->getElementType();
Steve Naroff509d0b52007-09-04 02:20:04 +0000523 } else if (DeclType->isScalarType()) {
Anders Carlsson9864a512007-12-03 01:01:28 +0000524 if (const VectorType *VT = DeclType->getAsVectorType())
525 maxElementsAtThisLevel = VT->getNumElements();
526 else {
527 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
528 IList->getSourceRange());
529 maxElementsAtThisLevel = 1;
530 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000531 }
532 // The empty init list "{ }" is treated specially below.
533 unsigned numInits = IList->getNumInits();
534 if (numInits) {
Steve Naroffcb69fb72007-12-10 22:44:33 +0000535 if (CheckForCharArrayInitializer(IList, ElementType,
536 maxElementsAtThisLevel,
537 true, hadError))
538 return;
539
Steve Naroff509d0b52007-09-04 02:20:04 +0000540 for (unsigned i = 0; i < numInits; i++) {
541 Expr *expr = IList->getInit(i);
542
543 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
544 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
545 totalInits, hadError);
546 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000547 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff509d0b52007-09-04 02:20:04 +0000548 nInitsAtLevel++; // increment the number of initializers at this level.
549 totalInits--; // decrement the total number of initializers.
550
551 // Check if we have space for another initializer.
Anders Carlsson463f7ce2007-12-05 04:57:06 +0000552 if (((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0)))
Steve Naroff509d0b52007-09-04 02:20:04 +0000553 Diag(expr->getLocStart(), diag::warn_excess_initializers,
554 expr->getSourceRange());
555 }
556 }
557 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
558 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
559 } else {
560 // we have an initializer list with no elements.
561 totalInits -= maxElementsAtThisLevel;
562 if (totalInits < 0)
563 Diag(IList->getLocStart(), diag::warn_excess_initializers,
564 IList->getSourceRange());
Steve Naroff9091f3f2007-09-02 15:34:30 +0000565 }
Steve Naroff9091f3f2007-09-02 15:34:30 +0000566}
567
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000568bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Naroffcb69fb72007-12-10 22:44:33 +0000569 bool hadError = false;
Anders Carlsson855d78d2007-10-17 00:52:43 +0000570
Steve Naroffcb69fb72007-12-10 22:44:33 +0000571 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
572 if (!InitList) {
573 if (StringLiteral *strLiteral = dyn_cast<StringLiteral>(Init)) {
574 const VariableArrayType *VAT = DeclType->getAsVariableArrayType();
575 // FIXME: Handle wide strings
576 if (VAT && VAT->getElementType()->isCharType()) {
577 // C99 6.7.8p14. We have an array of character type with unknown size
578 // being initialized to a string literal.
579 llvm::APSInt ConstVal(32);
580 ConstVal = strLiteral->getByteLength() + 1;
581 // Return a new array type (C99 6.7.8p22).
582 DeclType = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
583 ArrayType::Normal, 0);
Steve Naroff6a2c3802007-12-11 00:00:01 +0000584 // set type from "char *" to "constant array of char".
585 strLiteral->setType(DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000586 return hadError;
587 }
588 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
589 if (CAT && CAT->getElementType()->isCharType()) {
590 // C99 6.7.8p14. We have an array of character type with known size.
591 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements()) {
592 Diag(strLiteral->getSourceRange().getBegin(),
593 diag::warn_initializer_string_for_char_array_too_long,
594 strLiteral->getSourceRange());
595 }
Steve Naroff6a2c3802007-12-11 00:00:01 +0000596 // set type from "char *" to "constant array of char".
597 strLiteral->setType(DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000598 return hadError;
599 }
600 }
601 return CheckSingleInitializer(Init, isStatic, DeclType);
602 }
Steve Naroffe14e5542007-09-02 02:04:30 +0000603 // We have an InitListExpr, make sure we set the type.
604 Init->setType(DeclType);
Steve Naroff1c9de712007-09-03 01:24:23 +0000605
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000606 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
607 // of unknown size ("[]") or an object type that is not a variable array type.
608 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
Chris Lattner6df93592007-12-18 07:02:56 +0000609 if (const Expr *expr = VAT->getSizeExpr())
Steve Naroff1c9de712007-09-03 01:24:23 +0000610 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
611 expr->getSourceRange());
612
Steve Naroff4f910992007-09-04 21:13:33 +0000613 // We have a VariableArrayType with unknown size. Note that only the first
614 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff509d0b52007-09-04 02:20:04 +0000615 int numInits = 0;
Steve Naroff4f910992007-09-04 21:13:33 +0000616 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
617 isStatic, numInits, hadError);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000618 llvm::APSInt ConstVal(32);
619
620 if (!hadError)
Steve Naroff509d0b52007-09-04 02:20:04 +0000621 ConstVal = numInits;
Steve Naroffcb69fb72007-12-10 22:44:33 +0000622
623 // Return a new array type from the number of initializers (C99 6.7.8p22).
624
625 // Note that if there was an error, we will still set the decl type,
626 // to an array type with 0 elements.
627 // This is to avoid "incomplete type foo[]" errors when we've already
628 // reported the real cause of the error.
629 DeclType = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
630 ArrayType::Normal, 0);
Steve Naroff1c9de712007-09-03 01:24:23 +0000631 return hadError;
632 }
633 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000634 int maxElements = CAT->getMaximumElements();
635 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
636 isStatic, maxElements, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000637 return hadError;
638 }
Anders Carlsson9864a512007-12-03 01:01:28 +0000639 if (const VectorType *VT = DeclType->getAsVectorType()) {
640 int maxElements = VT->getNumElements();
641 CheckConstantInitList(DeclType, InitList, VT->getElementType(),
642 isStatic, maxElements, hadError);
643 return hadError;
644 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000645 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
646 int maxElements = 1;
647 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
648 hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000649 return hadError;
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000650 }
Steve Naroffc7c66532007-12-05 04:00:10 +0000651 // FIXME: Handle struct/union types, including those appearing in a
652 // CompoundLiteralExpr...
Steve Naroff1c9de712007-09-03 01:24:23 +0000653 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +0000654}
655
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000656Sema::DeclTy *
Steve Naroff0acc9c92007-09-15 18:49:24 +0000657Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000658 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000659 IdentifierInfo *II = D.getIdentifier();
660
661 // All of these full declarators require an identifier. If it doesn't have
662 // one, the ParsedFreeStandingDeclSpec action should be used.
663 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000664 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000665 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000666 D.getDeclSpec().getSourceRange(), D.getSourceRange());
667 return 0;
668 }
669
Chris Lattnera7549902007-08-26 06:24:45 +0000670 // The scope passed in may not be a decl scope. Zip up the scope tree until
671 // we find one that is.
672 while ((S->getFlags() & Scope::DeclScope) == 0)
673 S = S->getParent();
674
Chris Lattner4b009652007-07-25 00:24:17 +0000675 // See if this is a redefinition of a variable in the same scope.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000676 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
677 D.getIdentifierLoc(), S);
Chris Lattner4b009652007-07-25 00:24:17 +0000678 if (PrevDecl && !S->isDeclScope(PrevDecl))
679 PrevDecl = 0; // If in outer scope, it isn't the same thing.
680
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000681 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000682 bool InvalidDecl = false;
683
Chris Lattner82bb4792007-11-14 06:34:38 +0000684 QualType R = GetTypeForDeclarator(D, S);
685 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
686
Chris Lattner4b009652007-07-25 00:24:17 +0000687 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner82bb4792007-11-14 06:34:38 +0000688 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000689 if (!NewTD) return 0;
690
691 // Handle attributes prior to checking for duplicates in MergeVarDecl
692 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
693 D.getAttributes());
694 // Merge the decl with the existing one if appropriate.
695 if (PrevDecl) {
696 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
697 if (NewTD == 0) return 0;
698 }
699 New = NewTD;
700 if (S->getParent() == 0) {
701 // C99 6.7.7p2: If a typedef name specifies a variably modified type
702 // then it shall have block scope.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000703 if (const VariableArrayType *VAT =
704 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
705 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
706 VAT->getSizeExpr()->getSourceRange());
707 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000708 }
709 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000710 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000711 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000712 switch (D.getDeclSpec().getStorageClassSpec()) {
713 default: assert(0 && "Unknown storage class!");
714 case DeclSpec::SCS_auto:
715 case DeclSpec::SCS_register:
716 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
717 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000718 InvalidDecl = true;
719 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000720 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
721 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
722 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
723 }
724
725 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000726 D.getDeclSpec().isInlineSpecified(),
Nate Begeman84079d72007-11-13 22:14:47 +0000727 LastDeclarator,
728 D.getDeclSpec().getAttributes());
729
730 // Transfer ownership of DeclSpec attributes to FunctionDecl
731 D.getDeclSpec().clearAttributes();
Chris Lattner4b009652007-07-25 00:24:17 +0000732
733 // Merge the decl with the existing one if appropriate.
734 if (PrevDecl) {
735 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
736 if (NewFD == 0) return 0;
737 }
738 New = NewFD;
739 } else {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000740 if (R.getTypePtr()->isObjcInterfaceType()) {
741 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
742 D.getIdentifier()->getName());
743 InvalidDecl = true;
744 }
Chris Lattner4b009652007-07-25 00:24:17 +0000745
746 VarDecl *NewVD;
747 VarDecl::StorageClass SC;
748 switch (D.getDeclSpec().getStorageClassSpec()) {
749 default: assert(0 && "Unknown storage class!");
750 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
751 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
752 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
753 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
754 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
755 }
756 if (S->getParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000757 // C99 6.9p2: The storage-class specifiers auto and register shall not
758 // appear in the declaration specifiers in an external declaration.
759 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
760 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
761 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000762 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000763 }
Chris Lattner4b009652007-07-25 00:24:17 +0000764 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000765 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000766 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000767 }
Chris Lattner4b009652007-07-25 00:24:17 +0000768 // Handle attributes prior to checking for duplicates in MergeVarDecl
769 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
770 D.getAttributes());
771
772 // Merge the decl with the existing one if appropriate.
773 if (PrevDecl) {
774 NewVD = MergeVarDecl(NewVD, PrevDecl);
775 if (NewVD == 0) return 0;
776 }
Chris Lattner4b009652007-07-25 00:24:17 +0000777 New = NewVD;
778 }
779
780 // If this has an identifier, add it to the scope stack.
781 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000782 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000783 II->setFETokenInfo(New);
784 S->AddDecl(New);
785 }
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000786 // If any semantic error occurred, mark the decl as invalid.
787 if (D.getInvalidType() || InvalidDecl)
788 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000789
790 return New;
791}
792
Steve Naroff6a0e2092007-09-12 14:07:44 +0000793void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000794 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000795 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +0000796 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +0000797
Chris Lattnerf31a2fb2007-10-19 20:10:30 +0000798 // If there is no declaration, there was an error parsing it. Just ignore
799 // the initializer.
800 if (RealDecl == 0) {
801 delete Init;
802 return;
803 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000804
Steve Naroff420d0f52007-09-12 20:13:48 +0000805 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
806 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +0000807 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
808 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +0000809 RealDecl->setInvalidDecl();
810 return;
811 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000812 // Get the decls type and save a reference for later, since
813 // CheckInitializer may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +0000814 QualType DclT = VDecl->getType(), SavT = DclT;
815 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000816 VarDecl::StorageClass SC = BVD->getStorageClass();
817 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +0000818 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000819 BVD->setInvalidDecl();
820 } else if (!BVD->isInvalidDecl()) {
821 CheckInitializer(Init, DclT, SC == VarDecl::Static);
822 }
Steve Naroff420d0f52007-09-12 20:13:48 +0000823 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000824 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +0000825 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000826 if (!FVD->isInvalidDecl())
827 CheckInitializer(Init, DclT, true);
828 }
829 // If the type changed, it means we had an incomplete type that was
830 // completed by the initializer. For example:
831 // int ary[] = { 1, 3, 5 };
832 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +0000833 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000834 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +0000835 Init->setType(DclT);
836 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000837
838 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +0000839 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000840 return;
841}
842
Chris Lattner4b009652007-07-25 00:24:17 +0000843/// The declarators are chained together backwards, reverse the list.
844Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
845 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000846 Decl *GroupDecl = static_cast<Decl*>(group);
847 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +0000848 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +0000849
850 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
851 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000852 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000853 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000854 else { // reverse the list.
855 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000856 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +0000857 Group->setNextDeclarator(NewGroup);
858 NewGroup = Group;
859 Group = Next;
860 }
861 }
862 // Perform semantic analysis that depends on having fully processed both
863 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000864 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000865 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
866 if (!IDecl)
867 continue;
868 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
869 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
870 QualType T = IDecl->getType();
871
872 // C99 6.7.5.2p2: If an identifier is declared to be an object with
873 // static storage duration, it shall not have a variable length array.
874 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
875 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
876 if (VLA->getSizeExpr()) {
877 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
878 IDecl->setInvalidDecl();
879 }
880 }
881 }
882 // Block scope. C99 6.7p7: If an identifier for an object is declared with
883 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
884 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
885 if (T->isIncompleteType()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +0000886 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
887 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +0000888 IDecl->setInvalidDecl();
889 }
890 }
891 // File scope. C99 6.9.2p2: A declaration of an identifier for and
892 // object that has file scope without an initializer, and without a
893 // storage-class specifier or with the storage-class specifier "static",
894 // constitutes a tentative definition. Note: A tentative definition with
895 // external linkage is valid (C99 6.2.2p5).
896 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
897 // C99 6.9.2p3: If the declaration of an identifier for an object is
898 // a tentative definition and has internal linkage (C99 6.2.2p3), the
899 // declared type shall not be an incomplete type.
900 if (T->isIncompleteType()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +0000901 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
902 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +0000903 IDecl->setInvalidDecl();
904 }
905 }
Chris Lattner4b009652007-07-25 00:24:17 +0000906 }
907 return NewGroup;
908}
Steve Naroff91b03f72007-08-28 03:03:08 +0000909
910// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000911ParmVarDecl *
Nate Begeman2240f542007-11-13 21:49:48 +0000912Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI, Scope *FnScope)
Steve Naroff434fa8d2007-11-12 03:44:46 +0000913{
Chris Lattner4b009652007-07-25 00:24:17 +0000914 IdentifierInfo *II = PI.Ident;
915 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
916 // Can this happen for params? We already checked that they don't conflict
917 // among each other. Here they can only shadow globals, which is ok.
918 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
919 PI.IdentLoc, FnScope)) {
920
921 }
922
923 // FIXME: Handle storage class (auto, register). No declarator?
924 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000925
926 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
927 // Doing the promotion here has a win and a loss. The win is the type for
928 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
929 // code generator). The loss is the orginal type isn't preserved. For example:
930 //
931 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
932 // int blockvardecl[5];
933 // sizeof(parmvardecl); // size == 4
934 // sizeof(blockvardecl); // size == 20
935 // }
936 //
937 // For expressions, all implicit conversions are captured using the
938 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
939 //
940 // FIXME: If a source translation tool needs to see the original type, then
941 // we need to consider storing both types (in ParmVarDecl)...
942 //
943 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattnerc08564a2008-01-02 22:50:48 +0000944 if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
945 // int x[restrict 4] -> int *restrict
Steve Naroff94cd93f2007-08-07 22:44:21 +0000946 parmDeclType = Context.getPointerType(AT->getElementType());
Chris Lattnerc08564a2008-01-02 22:50:48 +0000947 parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
948 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +0000949 parmDeclType = Context.getPointerType(parmDeclType);
950
951 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Nate Begeman84079d72007-11-13 22:14:47 +0000952 VarDecl::None, 0, PI.AttrList);
Steve Naroffcae537d2007-08-28 18:45:29 +0000953 if (PI.InvalidType)
954 New->setInvalidDecl();
955
Chris Lattner4b009652007-07-25 00:24:17 +0000956 // If this has an identifier, add it to the scope stack.
957 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000958 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000959 II->setFETokenInfo(New);
960 FnScope->AddDecl(New);
961 }
962
963 return New;
964}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000965
Chris Lattnerea148702007-10-09 17:14:05 +0000966Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000967 assert(CurFunctionDecl == 0 && "Function parsing confused");
968 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
969 "Not a function declarator!");
970 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
971
972 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
973 // for a K&R function.
974 if (!FTI.hasPrototype) {
975 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
976 if (FTI.ArgInfo[i].TypeInfo == 0) {
977 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
978 FTI.ArgInfo[i].Ident->getName());
979 // Implicitly declare the argument as type 'int' for lack of a better
980 // type.
981 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
982 }
983 }
984
985 // Since this is a function definition, act as though we have information
986 // about the arguments.
987 FTI.hasPrototype = true;
988 } else {
989 // FIXME: Diagnose arguments without names in C.
990
991 }
992
993 Scope *GlobalScope = FnBodyScope->getParent();
994
995 FunctionDecl *FD =
Steve Naroff0acc9c92007-09-15 18:49:24 +0000996 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattner4b009652007-07-25 00:24:17 +0000997 CurFunctionDecl = FD;
998
999 // Create Decl objects for each parameter, adding them to the FunctionDecl.
1000 llvm::SmallVector<ParmVarDecl*, 16> Params;
1001
1002 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1003 // no arguments, not a function that takes a single void argument.
1004 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnereee2f2b2007-11-28 18:51:29 +00001005 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getQualifiers() &&
1006 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001007 // empty arg list, don't push any params.
1008 } else {
Steve Naroff434fa8d2007-11-12 03:44:46 +00001009 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begeman2240f542007-11-13 21:49:48 +00001010 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroff434fa8d2007-11-12 03:44:46 +00001011 FnBodyScope));
1012 }
Chris Lattner4b009652007-07-25 00:24:17 +00001013 }
1014
1015 FD->setParams(&Params[0], Params.size());
1016
1017 return FD;
1018}
1019
Steve Naroff99ee4302007-11-11 23:20:51 +00001020Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1021 Decl *dcl = static_cast<Decl *>(D);
1022 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1023 FD->setBody((Stmt*)Body);
1024 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff8ba51142007-12-13 18:18:56 +00001025 CurFunctionDecl = 0;
Steve Naroff99ee4302007-11-11 23:20:51 +00001026 } else if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(dcl)) {
1027 MD->setBody((Stmt*)Body);
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001028 CurMethodDecl = 0;
Steve Naroff8ba51142007-12-13 18:18:56 +00001029 }
Chris Lattner4b009652007-07-25 00:24:17 +00001030 // Verify and clean out per-function state.
1031
1032 // Check goto/label use.
1033 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1034 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1035 // Verify that we have no forward references left. If so, there was a goto
1036 // or address of a label taken, but no definition of it. Label fwd
1037 // definitions are indicated with a null substmt.
1038 if (I->second->getSubStmt() == 0) {
1039 LabelStmt *L = I->second;
1040 // Emit error.
1041 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1042
1043 // At this point, we have gotos that use the bogus label. Stitch it into
1044 // the function body so that they aren't leaked and that the AST is well
1045 // formed.
1046 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1047 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1048 }
1049 }
1050 LabelMap.clear();
1051
Steve Naroff99ee4302007-11-11 23:20:51 +00001052 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001053}
1054
Chris Lattner4b009652007-07-25 00:24:17 +00001055/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1056/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001057ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1058 IdentifierInfo &II, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +00001059 if (getLangOptions().C99) // Extension in C99.
1060 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1061 else // Legal in C90, but warn about it.
1062 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1063
1064 // FIXME: handle stuff like:
1065 // void foo() { extern float X(); }
1066 // void bar() { X(); } <-- implicit decl for X in another scope.
1067
1068 // Set a Declarator for the implicit definition: int foo();
1069 const char *Dummy;
1070 DeclSpec DS;
1071 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1072 Error = Error; // Silence warning.
1073 assert(!Error && "Error setting up implicit decl!");
1074 Declarator D(DS, Declarator::BlockContext);
1075 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1076 D.SetIdentifier(&II, Loc);
1077
1078 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +00001079 if (Scope *FnS = S->getFnParent())
1080 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +00001081 while (S->getParent())
1082 S = S->getParent();
1083
Steve Narofff0c31dd2007-09-16 16:16:00 +00001084 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattner4b009652007-07-25 00:24:17 +00001085}
1086
1087
Chris Lattner82bb4792007-11-14 06:34:38 +00001088TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001089 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001090 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001091 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001092
1093 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001094 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
1095 T, LastDeclarator);
1096 if (D.getInvalidType())
1097 NewTD->setInvalidDecl();
1098 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001099}
1100
Steve Naroff0acc9c92007-09-15 18:49:24 +00001101/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001102/// former case, Name will be non-null. In the later case, Name will be null.
1103/// TagType indicates what kind of tag this is. TK indicates whether this is a
1104/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001105Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001106 SourceLocation KWLoc, IdentifierInfo *Name,
1107 SourceLocation NameLoc, AttributeList *Attr) {
1108 // If this is a use of an existing tag, it must have a name.
1109 assert((Name != 0 || TK == TK_Definition) &&
1110 "Nameless record must be a definition!");
1111
1112 Decl::Kind Kind;
1113 switch (TagType) {
1114 default: assert(0 && "Unknown tag type!");
1115 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1116 case DeclSpec::TST_union: Kind = Decl::Union; break;
1117//case DeclSpec::TST_class: Kind = Decl::Class; break;
1118 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1119 }
1120
1121 // If this is a named struct, check to see if there was a previous forward
1122 // declaration or definition.
1123 if (TagDecl *PrevDecl =
1124 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1125 NameLoc, S))) {
1126
1127 // If this is a use of a previous tag, or if the tag is already declared in
1128 // the same scope (so that the definition/declaration completes or
1129 // rementions the tag), reuse the decl.
1130 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1131 // Make sure that this wasn't declared as an enum and now used as a struct
1132 // or something similar.
1133 if (PrevDecl->getKind() != Kind) {
1134 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1135 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1136 }
1137
1138 // If this is a use or a forward declaration, we're good.
1139 if (TK != TK_Definition)
1140 return PrevDecl;
1141
1142 // Diagnose attempts to redefine a tag.
1143 if (PrevDecl->isDefinition()) {
1144 Diag(NameLoc, diag::err_redefinition, Name->getName());
1145 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1146 // If this is a redefinition, recover by making this struct be
1147 // anonymous, which will make any later references get the previous
1148 // definition.
1149 Name = 0;
1150 } else {
1151 // Okay, this is definition of a previously declared or referenced tag.
1152 // Move the location of the decl to be the definition site.
1153 PrevDecl->setLocation(NameLoc);
1154 return PrevDecl;
1155 }
1156 }
1157 // If we get here, this is a definition of a new struct type in a nested
1158 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1159 // type.
1160 }
1161
1162 // If there is an identifier, use the location of the identifier as the
1163 // location of the decl, otherwise use the location of the struct/union
1164 // keyword.
1165 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1166
1167 // Otherwise, if this is the first time we've seen this tag, create the decl.
1168 TagDecl *New;
1169 switch (Kind) {
1170 default: assert(0 && "Unknown tag kind!");
1171 case Decl::Enum:
1172 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1173 // enum X { A, B, C } D; D should chain to X.
1174 New = new EnumDecl(Loc, Name, 0);
1175 // If this is an undefined enum, warn.
1176 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1177 break;
1178 case Decl::Union:
1179 case Decl::Struct:
1180 case Decl::Class:
1181 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1182 // struct X { int A; } D; D should chain to X.
1183 New = new RecordDecl(Kind, Loc, Name, 0);
1184 break;
1185 }
1186
1187 // If this has an identifier, add it to the scope stack.
1188 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001189 // The scope passed in may not be a decl scope. Zip up the scope tree until
1190 // we find one that is.
1191 while ((S->getFlags() & Scope::DeclScope) == 0)
1192 S = S->getParent();
1193
1194 // Add it to the decl chain.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001195 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001196 Name->setFETokenInfo(New);
1197 S->AddDecl(New);
1198 }
Steve Naroff6fd865b2007-11-28 22:54:11 +00001199
Chris Lattner4b009652007-07-25 00:24:17 +00001200 return New;
1201}
1202
Steve Naroff0acc9c92007-09-15 18:49:24 +00001203/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001204/// to create a FieldDecl object for it.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001205Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001206 SourceLocation DeclStart,
1207 Declarator &D, ExprTy *BitfieldWidth) {
1208 IdentifierInfo *II = D.getIdentifier();
1209 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001210 SourceLocation Loc = DeclStart;
1211 if (II) Loc = D.getIdentifierLoc();
1212
1213 // FIXME: Unnamed fields can be handled in various different ways, for
1214 // example, unnamed unions inject all members into the struct namespace!
1215
1216
1217 if (BitWidth) {
1218 // TODO: Validate.
1219 //printf("WARNING: BITFIELDS IGNORED!\n");
1220
1221 // 6.7.2.1p3
1222 // 6.7.2.1p4
1223
1224 } else {
1225 // Not a bitfield.
1226
1227 // validate II.
1228
1229 }
1230
1231 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001232 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1233 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001234
Chris Lattner4b009652007-07-25 00:24:17 +00001235 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1236 // than a variably modified type.
Steve Naroff5eb879b2007-08-31 17:20:07 +00001237 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1238 Diag(Loc, diag::err_typecheck_illegal_vla,
1239 VAT->getSizeExpr()->getSourceRange());
1240 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001241 }
Chris Lattner4b009652007-07-25 00:24:17 +00001242 // FIXME: Chain fielddecls together.
Steve Naroff75494892007-09-11 21:17:26 +00001243 FieldDecl *NewFD;
1244
1245 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patelf616a242007-11-01 16:29:56 +00001246 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Steve Narofffa63d9d2007-11-12 04:22:52 +00001247 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1248 isa<ObjcImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroff4fbfb452007-11-14 14:15:31 +00001249 isa<ObjcCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
1250 // FIXME: ivars are currently used to model properties, and
1251 // properties can appear within a protocol.
1252 // See corresponding FIXME in DeclObjC.h:ObjcPropertyDecl.
1253 isa<ObjcProtocolDecl>(static_cast<Decl *>(TagDecl)))
Steve Naroffdc1ad762007-09-14 02:20:46 +00001254 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff75494892007-09-11 21:17:26 +00001255 else
Steve Naroff0acc9c92007-09-15 18:49:24 +00001256 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff75494892007-09-11 21:17:26 +00001257
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001258 if (D.getInvalidType() || InvalidDecl)
1259 NewFD->setInvalidDecl();
1260 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001261}
1262
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001263/// TranslateIvarVisibility - Translate visibility from a token ID to an
1264/// AST enum value.
1265static ObjcIvarDecl::AccessControl
1266TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001267 switch (ivarVisibility) {
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001268 case tok::objc_private: return ObjcIvarDecl::Private;
1269 case tok::objc_public: return ObjcIvarDecl::Public;
1270 case tok::objc_protected: return ObjcIvarDecl::Protected;
1271 case tok::objc_package: return ObjcIvarDecl::Package;
1272 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001273 }
1274}
1275
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00001276void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001277 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001278 DeclTy **Fields, unsigned NumFields,
Steve Naroff1a7fa7b2007-10-29 21:38:07 +00001279 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001280 tok::ObjCKeywordKind *visibility) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001281 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1282 assert(EnclosingDecl && "missing record or interface decl");
1283 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1284
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001285 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001286 // Diagnose code like:
1287 // struct S { struct S {} X; };
1288 // We discover this when we complete the outer S. Reject and ignore the
1289 // outer S.
1290 Diag(Record->getLocation(), diag::err_nested_redefinition,
1291 Record->getKindName());
1292 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001293 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001294 return;
1295 }
Chris Lattner4b009652007-07-25 00:24:17 +00001296 // Verify that all the fields are okay.
1297 unsigned NumNamedMembers = 0;
1298 llvm::SmallVector<FieldDecl*, 32> RecFields;
1299 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00001300
Chris Lattner4b009652007-07-25 00:24:17 +00001301 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001302
Steve Naroff9bb759f2007-09-14 22:20:54 +00001303 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1304 assert(FD && "missing field decl");
1305
1306 // Remember all fields.
1307 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00001308
1309 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001310 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +00001311
Steve Naroffffeaa552007-09-14 23:09:53 +00001312 // If we have visibility info, make sure the AST is set accordingly.
1313 if (visibility)
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001314 cast<ObjcIvarDecl>(FD)->setAccessControl(
1315 TranslateIvarVisibility(visibility[i]));
Steve Naroffffeaa552007-09-14 23:09:53 +00001316
Chris Lattner4b009652007-07-25 00:24:17 +00001317 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001318 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001319 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00001320 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001321 FD->setInvalidDecl();
1322 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001323 continue;
1324 }
Chris Lattner4b009652007-07-25 00:24:17 +00001325 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1326 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001327 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001328 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001329 FD->setInvalidDecl();
1330 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001331 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001332 }
Chris Lattner4b009652007-07-25 00:24:17 +00001333 if (i != NumFields-1 || // ... that the last member ...
1334 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001335 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001336 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001337 FD->setInvalidDecl();
1338 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001339 continue;
1340 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001341 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00001342 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1343 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001344 FD->setInvalidDecl();
1345 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001346 continue;
1347 }
Chris Lattner4b009652007-07-25 00:24:17 +00001348 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001349 if (Record)
1350 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001351 }
Chris Lattner4b009652007-07-25 00:24:17 +00001352 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1353 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001354 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001355 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1356 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001357 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner4b009652007-07-25 00:24:17 +00001358 Record->setHasFlexibleArrayMember(true);
1359 } else {
1360 // If this is a struct/class and this is not the last element, reject
1361 // it. Note that GCC supports variable sized arrays in the middle of
1362 // structures.
1363 if (i != NumFields-1) {
1364 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1365 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001366 FD->setInvalidDecl();
1367 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001368 continue;
1369 }
Chris Lattner4b009652007-07-25 00:24:17 +00001370 // We support flexible arrays at the end of structs in other structs
1371 // as an extension.
1372 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1373 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001374 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001375 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001376 }
1377 }
1378 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001379 /// A field cannot be an Objective-c object
1380 if (FDTy->isObjcInterfaceType()) {
1381 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1382 FD->getName());
1383 FD->setInvalidDecl();
1384 EnclosingDecl->setInvalidDecl();
1385 continue;
1386 }
Chris Lattner4b009652007-07-25 00:24:17 +00001387 // Keep track of the number of named members.
1388 if (IdentifierInfo *II = FD->getIdentifier()) {
1389 // Detect duplicate member names.
1390 if (!FieldIDs.insert(II)) {
1391 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1392 // Find the previous decl.
1393 SourceLocation PrevLoc;
1394 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1395 assert(i != e && "Didn't find previous def!");
1396 if (RecFields[i]->getIdentifier() == II) {
1397 PrevLoc = RecFields[i]->getLocation();
1398 break;
1399 }
1400 }
1401 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001402 FD->setInvalidDecl();
1403 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001404 continue;
1405 }
1406 ++NumNamedMembers;
1407 }
Chris Lattner4b009652007-07-25 00:24:17 +00001408 }
1409
Chris Lattner4b009652007-07-25 00:24:17 +00001410 // Okay, we successfully defined 'Record'.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001411 if (Record)
1412 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001413 else {
1414 ObjcIvarDecl **ClsFields =
1415 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001416 if (isa<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1417 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
Steve Naroff1a7fa7b2007-10-29 21:38:07 +00001418 addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001419 else if (isa<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1420 ObjcImplementationDecl* IMPDecl =
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001421 cast<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl));
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001422 assert(IMPDecl && "ActOnFields - missing ObjcImplementationDecl");
1423 IMPDecl->ObjcAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00001424 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001425 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001426 }
Chris Lattner4b009652007-07-25 00:24:17 +00001427}
1428
Steve Naroff0acc9c92007-09-15 18:49:24 +00001429Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001430 DeclTy *lastEnumConst,
1431 SourceLocation IdLoc, IdentifierInfo *Id,
1432 SourceLocation EqualLoc, ExprTy *val) {
1433 theEnumDecl = theEnumDecl; // silence unused warning.
1434 EnumConstantDecl *LastEnumConst =
1435 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1436 Expr *Val = static_cast<Expr*>(val);
1437
Chris Lattnera7549902007-08-26 06:24:45 +00001438 // The scope passed in may not be a decl scope. Zip up the scope tree until
1439 // we find one that is.
1440 while ((S->getFlags() & Scope::DeclScope) == 0)
1441 S = S->getParent();
1442
Chris Lattner4b009652007-07-25 00:24:17 +00001443 // Verify that there isn't already something declared with this name in this
1444 // scope.
Steve Naroffcb597472007-09-13 21:41:19 +00001445 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1446 IdLoc, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001447 if (S->isDeclScope(PrevDecl)) {
1448 if (isa<EnumConstantDecl>(PrevDecl))
1449 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1450 else
1451 Diag(IdLoc, diag::err_redefinition, Id->getName());
1452 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1453 // FIXME: Don't leak memory: delete Val;
1454 return 0;
1455 }
1456 }
1457
1458 llvm::APSInt EnumVal(32);
1459 QualType EltTy;
1460 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001461 // Make sure to promote the operand type to int.
1462 UsualUnaryConversions(Val);
1463
Chris Lattner4b009652007-07-25 00:24:17 +00001464 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1465 SourceLocation ExpLoc;
1466 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1467 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1468 Id->getName());
1469 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001470 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001471 } else {
1472 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001473 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001474 }
1475
1476 if (!Val) {
1477 if (LastEnumConst) {
1478 // Assign the last value + 1.
1479 EnumVal = LastEnumConst->getInitVal();
1480 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001481
1482 // Check for overflow on increment.
1483 if (EnumVal < LastEnumConst->getInitVal())
1484 Diag(IdLoc, diag::warn_enum_value_overflow);
1485
Chris Lattnere7f53a42007-08-27 17:37:24 +00001486 EltTy = LastEnumConst->getType();
1487 } else {
1488 // First value, set to zero.
1489 EltTy = Context.IntTy;
Chris Lattner3496d522007-09-04 02:45:27 +00001490 EnumVal.zextOrTrunc(
1491 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001492 }
Chris Lattner4b009652007-07-25 00:24:17 +00001493 }
1494
Chris Lattner4b009652007-07-25 00:24:17 +00001495 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1496 LastEnumConst);
1497
1498 // Register this decl in the current scope stack.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001499 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001500 Id->setFETokenInfo(New);
1501 S->AddDecl(New);
1502 return New;
1503}
1504
Steve Naroff0acc9c92007-09-15 18:49:24 +00001505void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00001506 DeclTy **Elements, unsigned NumElements) {
1507 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1508 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1509
Chris Lattner435c3fd2007-08-28 05:10:31 +00001510 // TODO: If the result value doesn't fit in an int, it must be a long or long
1511 // long value. ISO C does not support this, but GCC does as an extension,
1512 // emit a warning.
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001513 unsigned IntWidth =
1514 Context.Target.getIntWidth(Context.getFullLoc(Enum->getLocation()));
Chris Lattner435c3fd2007-08-28 05:10:31 +00001515
1516
Chris Lattner206754a2007-08-28 06:15:15 +00001517 // Verify that all the values are okay, compute the size of the values, and
1518 // reverse the list.
1519 unsigned NumNegativeBits = 0;
1520 unsigned NumPositiveBits = 0;
1521
1522 // Keep track of whether all elements have type int.
1523 bool AllElementsInt = true;
1524
Chris Lattner4b009652007-07-25 00:24:17 +00001525 EnumConstantDecl *EltList = 0;
1526 for (unsigned i = 0; i != NumElements; ++i) {
1527 EnumConstantDecl *ECD =
1528 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1529 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001530
1531 // If the enum value doesn't fit in an int, emit an extension warning.
1532 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1533 "Should have promoted value to int");
1534 const llvm::APSInt &InitVal = ECD->getInitVal();
1535 if (InitVal.getBitWidth() > IntWidth) {
1536 llvm::APSInt V(InitVal);
1537 V.trunc(IntWidth);
1538 V.extend(InitVal.getBitWidth());
1539 if (V != InitVal)
1540 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1541 InitVal.toString());
1542 }
Chris Lattner206754a2007-08-28 06:15:15 +00001543
1544 // Keep track of the size of positive and negative values.
1545 if (InitVal.isUnsigned() || !InitVal.isNegative())
1546 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1547 else
1548 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001549
Chris Lattner206754a2007-08-28 06:15:15 +00001550 // Keep track of whether every enum element has type int (very commmon).
1551 if (AllElementsInt)
1552 AllElementsInt = ECD->getType() == Context.IntTy;
1553
Chris Lattner4b009652007-07-25 00:24:17 +00001554 ECD->setNextDeclarator(EltList);
1555 EltList = ECD;
1556 }
1557
Chris Lattner206754a2007-08-28 06:15:15 +00001558 // Figure out the type that should be used for this enum.
1559 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1560 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001561 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001562
1563 if (NumNegativeBits) {
1564 // If there is a negative value, figure out the smallest integer type (of
1565 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001566 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001567 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001568 BestWidth = IntWidth;
1569 } else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001570 BestWidth =
1571 Context.Target.getLongWidth(Context.getFullLoc(Enum->getLocation()));
1572
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001573 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001574 BestType = Context.LongTy;
1575 else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001576 BestWidth = Context.Target.getLongLongWidth(
1577 Context.getFullLoc(Enum->getLocation()));
1578
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001579 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001580 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1581 BestType = Context.LongLongTy;
1582 }
1583 }
1584 } else {
1585 // If there is no negative value, figure out which of uint, ulong, ulonglong
1586 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001587 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001588 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001589 BestWidth = IntWidth;
1590 } else if (NumPositiveBits <=
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001591 (BestWidth = Context.Target.getLongWidth(
1592 Context.getFullLoc(Enum->getLocation()))))
1593
Chris Lattner206754a2007-08-28 06:15:15 +00001594 BestType = Context.UnsignedLongTy;
1595 else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001596 BestWidth =
1597 Context.Target.getLongLongWidth(Context.getFullLoc(Enum->getLocation()));
1598
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001599 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001600 "How could an initializer get larger than ULL?");
1601 BestType = Context.UnsignedLongLongTy;
1602 }
1603 }
1604
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001605 // Loop over all of the enumerator constants, changing their types to match
1606 // the type of the enum if needed.
1607 for (unsigned i = 0; i != NumElements; ++i) {
1608 EnumConstantDecl *ECD =
1609 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1610 if (!ECD) continue; // Already issued a diagnostic.
1611
1612 // Standard C says the enumerators have int type, but we allow, as an
1613 // extension, the enumerators to be larger than int size. If each
1614 // enumerator value fits in an int, type it as an int, otherwise type it the
1615 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1616 // that X has type 'int', not 'unsigned'.
1617 if (ECD->getType() == Context.IntTy)
1618 continue; // Already int type.
1619
1620 // Determine whether the value fits into an int.
1621 llvm::APSInt InitVal = ECD->getInitVal();
1622 bool FitsInInt;
1623 if (InitVal.isUnsigned() || !InitVal.isNegative())
1624 FitsInInt = InitVal.getActiveBits() < IntWidth;
1625 else
1626 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1627
1628 // If it fits into an integer type, force it. Otherwise force it to match
1629 // the enum decl type.
1630 QualType NewTy;
1631 unsigned NewWidth;
1632 bool NewSign;
1633 if (FitsInInt) {
1634 NewTy = Context.IntTy;
1635 NewWidth = IntWidth;
1636 NewSign = true;
1637 } else if (ECD->getType() == BestType) {
1638 // Already the right type!
1639 continue;
1640 } else {
1641 NewTy = BestType;
1642 NewWidth = BestWidth;
1643 NewSign = BestType->isSignedIntegerType();
1644 }
1645
1646 // Adjust the APSInt value.
1647 InitVal.extOrTrunc(NewWidth);
1648 InitVal.setIsSigned(NewSign);
1649 ECD->setInitVal(InitVal);
1650
1651 // Adjust the Expr initializer and type.
1652 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1653 ECD->setType(NewTy);
1654 }
Chris Lattner206754a2007-08-28 06:15:15 +00001655
Chris Lattner90a018d2007-08-28 18:24:31 +00001656 Enum->defineElements(EltList, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00001657}
1658
Chris Lattner4b009652007-07-25 00:24:17 +00001659void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
Anders Carlsson28e34e32007-12-19 06:16:30 +00001660 const char *attrName = rawAttr->getAttributeName()->getName();
1661 unsigned attrLen = rawAttr->getAttributeName()->getLength();
1662
Anders Carlsson5f558b52007-12-19 17:43:24 +00001663 // Normalize the attribute name, __foo__ becomes foo.
1664 if (attrLen > 4 && attrName[0] == '_' && attrName[1] == '_' &&
1665 attrName[attrLen - 2] == '_' && attrName[attrLen - 1] == '_') {
1666 attrName += 2;
1667 attrLen -= 4;
1668 }
1669
1670 if (attrLen == 11 && !memcmp(attrName, "vector_size", 11)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001671 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1672 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1673 if (!newType.isNull()) // install the new vector type into the decl
1674 vDecl->setType(newType);
1675 }
1676 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1677 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1678 rawAttr);
1679 if (!newType.isNull()) // install the new vector type into the decl
1680 tDecl->setUnderlyingType(newType);
1681 }
Anders Carlsson5f558b52007-12-19 17:43:24 +00001682 } else if (attrLen == 15 && !memcmp(attrName, "ocu_vector_type", 15)) {
Steve Naroff82113e32007-07-29 16:33:31 +00001683 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1684 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1685 else
Chris Lattner4b009652007-07-25 00:24:17 +00001686 Diag(rawAttr->getAttributeLoc(),
1687 diag::err_typecheck_ocu_vector_not_typedef);
Anders Carlssonc8b44122007-12-19 07:19:40 +00001688 } else if (attrLen == 7 && !memcmp(attrName, "aligned", 7)) {
1689 HandleAlignedAttribute(New, rawAttr);
Chris Lattner4b009652007-07-25 00:24:17 +00001690 }
Anders Carlssonc8b44122007-12-19 07:19:40 +00001691
Chris Lattner4b009652007-07-25 00:24:17 +00001692 // FIXME: add other attributes...
1693}
1694
1695void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1696 AttributeList *declarator_postfix) {
1697 while (declspec_prefix) {
1698 HandleDeclAttribute(New, declspec_prefix);
1699 declspec_prefix = declspec_prefix->getNext();
1700 }
1701 while (declarator_postfix) {
1702 HandleDeclAttribute(New, declarator_postfix);
1703 declarator_postfix = declarator_postfix->getNext();
1704 }
1705}
1706
Steve Naroff82113e32007-07-29 16:33:31 +00001707void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1708 AttributeList *rawAttr) {
1709 QualType curType = tDecl->getUnderlyingType();
Anders Carlssonc8b44122007-12-19 07:19:40 +00001710 // check the attribute arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001711 if (rawAttr->getNumArgs() != 1) {
1712 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1713 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001714 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001715 }
1716 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1717 llvm::APSInt vecSize(32);
1718 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1719 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1720 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001721 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001722 }
1723 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1724 // in conjunction with complex types (pointers, arrays, functions, etc.).
1725 Type *canonType = curType.getCanonicalType().getTypePtr();
1726 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1727 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1728 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001729 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001730 }
1731 // unlike gcc's vector_size attribute, the size is specified as the
1732 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00001733 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00001734
1735 if (vectorSize == 0) {
1736 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1737 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001738 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001739 }
Steve Naroff82113e32007-07-29 16:33:31 +00001740 // Instantiate/Install the vector type, the number of elements is > 0.
1741 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1742 // Remember this typedef decl, we will need it later for diagnostics.
1743 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001744}
1745
1746QualType Sema::HandleVectorTypeAttribute(QualType curType,
1747 AttributeList *rawAttr) {
1748 // check the attribute arugments.
1749 if (rawAttr->getNumArgs() != 1) {
1750 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1751 std::string("1"));
1752 return QualType();
1753 }
1754 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1755 llvm::APSInt vecSize(32);
1756 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1757 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1758 sizeExpr->getSourceRange());
1759 return QualType();
1760 }
1761 // navigate to the base type - we need to provide for vector pointers,
1762 // vector arrays, and functions returning vectors.
1763 Type *canonType = curType.getCanonicalType().getTypePtr();
1764
1765 if (canonType->isPointerType() || canonType->isArrayType() ||
1766 canonType->isFunctionType()) {
Chris Lattner5b5e1982007-12-19 05:38:06 +00001767 assert(0 && "HandleVector(): Complex type construction unimplemented");
Chris Lattner4b009652007-07-25 00:24:17 +00001768 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1769 do {
1770 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1771 canonType = PT->getPointeeType().getTypePtr();
1772 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1773 canonType = AT->getElementType().getTypePtr();
1774 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1775 canonType = FT->getResultType().getTypePtr();
1776 } while (canonType->isPointerType() || canonType->isArrayType() ||
1777 canonType->isFunctionType());
1778 */
1779 }
1780 // the base type must be integer or float.
1781 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1782 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1783 curType.getCanonicalType().getAsString());
1784 return QualType();
1785 }
Chris Lattner3496d522007-09-04 02:45:27 +00001786 unsigned typeSize = static_cast<unsigned>(
1787 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Chris Lattner4b009652007-07-25 00:24:17 +00001788 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00001789 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00001790
1791 // the vector size needs to be an integral multiple of the type size.
1792 if (vectorSize % typeSize) {
1793 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1794 sizeExpr->getSourceRange());
1795 return QualType();
1796 }
1797 if (vectorSize == 0) {
1798 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1799 sizeExpr->getSourceRange());
1800 return QualType();
1801 }
1802 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1803 // the number of elements to be a power of two (unlike GCC).
1804 // Instantiate the vector type, the number of elements is > 0.
1805 return Context.getVectorType(curType, vectorSize/typeSize);
1806}
1807
Anders Carlssonc8b44122007-12-19 07:19:40 +00001808void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
1809{
1810 // check the attribute arguments.
Anders Carlsson5f558b52007-12-19 17:43:24 +00001811 // FIXME: Handle the case where are no arguments.
Anders Carlssonc8b44122007-12-19 07:19:40 +00001812 if (rawAttr->getNumArgs() != 1) {
1813 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1814 std::string("1"));
1815 return;
1816 }
1817
1818 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
1819 llvm::APSInt alignment(32);
1820 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
1821 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1822 alignmentExpr->getSourceRange());
1823 return;
1824 }
1825}