blob: 44eb70b74992e3840c1c3173d7537da373911797 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/TargetInfo.h"
Steve Naroff563477d2007-09-18 23:55:05 +000024#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000026#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Reid Spencer5f016e22007-07-11 17:01:13 +000029Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Fariborz Jahanianbece4ac2007-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;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000036 if (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000037 return IIDecl;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000038 if (ObjCCompatibleAliasDecl *ADecl =
39 dyn_cast<ObjCCompatibleAliasDecl>(IIDecl))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000040 return ADecl->getClassInterface();
Steve Naroff3536b442007-09-06 21:24:23 +000041 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000042}
43
Steve Naroffb216c882007-10-09 22:01:59 +000044void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000045 if (S->decl_empty()) return;
46 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
47
Reid Spencer5f016e22007-07-11 17:01:13 +000048 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
49 I != E; ++I) {
Steve Naroffc752d042007-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
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroffc752d042007-09-13 18:10:37 +000067 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +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 Jahanian4cabdfc2007-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 Jahanian3fe44e42007-10-12 19:53:08 +000090/// declaration. Caller is responsible for handling the none-class case.
Fariborz Jahanian4cabdfc2007-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
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000101 if (ObjCCompatibleAliasDecl *ADecl =
102 dyn_cast_or_null<ObjCCompatibleAliasDecl>(IDecl))
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000103 return ADecl->getClassInterface();
104 return IDecl;
105}
106
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000107/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +0000108/// return 0 if one not found.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000109ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000110 ScopedDecl *IdDecl = LookupInterfaceDecl(Id);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000111 return cast_or_null<ObjCInterfaceDecl>(IdDecl);
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +0000112}
113
Reid Spencer5f016e22007-07-11 17:01:13 +0000114/// LookupScopedDecl - Look up the inner-most declaration in the specified
115/// namespace.
Steve Naroffc752d042007-09-13 18:10:37 +0000116ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
117 SourceLocation IdLoc, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroffc752d042007-09-13 18:10:37 +0000124 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenek9c728dc2007-12-12 22:39:36 +0000138 Context.Target.DiagnoseNonPortability(Context.getFullLoc(IdLoc),
Reid Spencer5f016e22007-07-11 17:01:13 +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 Carlsson7c50aca2007-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 Naroff733002f2007-10-18 22:17:45 +0000156 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000157 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
158}
159
Reid Spencer5f016e22007-07-11 17:01:13 +0000160/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
161/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000162ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
163 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000164 Builtin::ID BID = (Builtin::ID)bid;
165
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000166 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson793680e2007-10-12 23:56:29 +0000167 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000168 BID == Builtin::BI__builtin_va_end)
169 InitBuiltinVaListType();
170
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000171 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Reid Spencer5f016e22007-07-11 17:01:13 +0000172 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000173 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000174
175 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000176 if (Scope *FnS = S->getFnParent())
177 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroffc752d042007-09-13 18:10:37 +0000183 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 }
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff8e74c932007-09-13 21:41:19 +0000199TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff8ee529b2007-10-31 18:42:27 +0000209 // Allow multiple definitions for ObjC built-in typedefs.
210 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000211 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000212 return Old;
213
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff8e74c932007-09-13 21:41:19 +0000226FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner55196442007-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;
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000249 // Function types need to be compatible, not identical. This handles
250 // duplicate function decls like "void f(int); void f(enum X);" properly.
251 if (Context.functionTypesAreCompatible(OldQType, NewQType))
252 return New;
Chris Lattnere3995fe2007-11-06 06:07:26 +0000253
Steve Naroff837618c2008-01-16 15:01:34 +0000254 // A function that has already been declared has been redeclared or defined
255 // with a different type- show appropriate diagnostic
256 diag::kind PrevDiag = Old->getBody() ? diag::err_previous_definition :
257 diag::err_previous_declaration;
258
Reid Spencer5f016e22007-07-11 17:01:13 +0000259 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
260 // TODO: This is totally simplistic. It should handle merging functions
261 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000262 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
263 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000264 return New;
265}
266
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000267
268/// hasUndefinedLength - Used by equivalentArrayTypes to determine whether the
269/// the outermost VariableArrayType has no size defined.
270static bool hasUndefinedLength(const ArrayType *Array) {
271 const VariableArrayType *VAT = Array->getAsVariableArrayType();
272 return VAT && !VAT->getSizeExpr();
273}
274
275/// equivalentArrayTypes - Used to determine whether two array types are
276/// equivalent.
277/// We need to check this explicitly as an incomplete array definition is
278/// considered a VariableArrayType, so will not match a complete array
279/// definition that would be otherwise equivalent.
280static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
281 const ArrayType *NewAT = NewQType->getAsArrayType();
282 const ArrayType *OldAT = OldQType->getAsArrayType();
283
284 if (!NewAT || !OldAT)
285 return false;
286
287 // If either (or both) array types in incomplete we need to strip off the
288 // outer VariableArrayType. Once the outer VAT is removed the remaining
289 // types must be identical if the array types are to be considered
290 // equivalent.
291 // eg. int[][1] and int[1][1] become
292 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
293 // removing the outermost VAT gives
294 // CAT(1, int) and CAT(1, int)
295 // which are equal, therefore the array types are equivalent.
296 if (hasUndefinedLength(NewAT) || hasUndefinedLength(OldAT)) {
297 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
298 return false;
299 NewQType = NewAT->getElementType();
300 OldQType = OldAT->getElementType();
301 }
302
303 return NewQType == OldQType;
304}
305
Reid Spencer5f016e22007-07-11 17:01:13 +0000306/// MergeVarDecl - We just parsed a variable 'New' which has the same name
307/// and scope as a previous declaration 'Old'. Figure out how to resolve this
308/// situation, merging decls or emitting diagnostics as appropriate.
309///
310/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
311/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
312///
Steve Naroff8e74c932007-09-13 21:41:19 +0000313VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 // Verify the old decl was also a variable.
315 VarDecl *Old = dyn_cast<VarDecl>(OldD);
316 if (!Old) {
317 Diag(New->getLocation(), diag::err_redefinition_different_kind,
318 New->getName());
319 Diag(OldD->getLocation(), diag::err_previous_definition);
320 return New;
321 }
Steve Narofffb22d962007-08-30 01:06:46 +0000322 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
323 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
324 bool OldIsTentative = false;
325
326 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
327 // Handle C "tentative" external object definitions. FIXME: finish!
328 if (!OldFSDecl->getInit() &&
329 (OldFSDecl->getStorageClass() == VarDecl::None ||
330 OldFSDecl->getStorageClass() == VarDecl::Static))
331 OldIsTentative = true;
332 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 // Verify the types match.
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000334 if (Old->getCanonicalType() != New->getCanonicalType() &&
335 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 Diag(New->getLocation(), diag::err_redefinition, New->getName());
337 Diag(Old->getLocation(), diag::err_previous_definition);
338 return New;
339 }
340 // We've verified the types match, now check if Old is "extern".
341 if (Old->getStorageClass() != VarDecl::Extern) {
342 Diag(New->getLocation(), diag::err_redefinition, New->getName());
343 Diag(Old->getLocation(), diag::err_previous_definition);
344 }
345 return New;
346}
347
348/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
349/// no declarator (e.g. "struct foo;") is parsed.
350Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
351 // TODO: emit error on 'int;' or 'const enum foo;'.
352 // TODO: emit error on 'typedef int;'
353 // if (!DS.isMissingDeclaratorOk()) Diag(...);
354
Steve Naroff92199282007-11-17 21:37:36 +0000355 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000356}
357
Steve Naroffd0091aa2008-01-10 22:15:12 +0000358bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000359 // Get the type before calling CheckSingleAssignmentConstraints(), since
360 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000361 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000362
Chris Lattner5cf216b2008-01-04 18:04:52 +0000363 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
364 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
365 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000366}
367
Steve Naroff9e8925e2007-09-04 14:36:54 +0000368bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000369 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000370 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000371 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000372 return true; // types weren't compatible.
373
Steve Naroff9e8925e2007-09-04 14:36:54 +0000374 if (savExpr != expr) // The type was promoted, update initializer list.
375 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000376 return false;
377}
378
379void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000380 QualType ElementType,
Steve Naroff371227d2007-09-04 02:20:04 +0000381 int &nInitializers, bool &hadError) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000382 unsigned numInits = IList->getNumInits();
383
384 if (numInits) {
385 if (CheckForCharArrayInitializer(IList, ElementType, nInitializers,
386 false, hadError))
387 return;
388
389 for (unsigned i = 0; i < numInits; i++) {
390 Expr *expr = IList->getInit(i);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000391
Steve Naroff2fdc3742007-12-10 22:44:33 +0000392 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
393 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
394 int maxElements = CAT->getMaximumElements();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000395 CheckConstantInitList(DeclType, InitList, ElementType,
Steve Naroff2fdc3742007-12-10 22:44:33 +0000396 maxElements, hadError);
397 }
398 } else {
Steve Naroffd0091aa2008-01-10 22:15:12 +0000399 hadError = CheckInitExpr(expr, IList, i, ElementType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000400 }
401 nInitializers++;
402 }
403 } else {
404 Diag(IList->getLocStart(),
405 diag::err_at_least_one_initializer_needed_to_size_array);
406 hadError = true;
407 }
408}
409
410bool Sema::CheckForCharArrayInitializer(InitListExpr *IList,
411 QualType ElementType,
412 int &nInitializers, bool isConstant,
413 bool &hadError)
414{
415 if (ElementType->isPointerType())
416 return false;
417
418 if (StringLiteral *literal = dyn_cast<StringLiteral>(IList->getInit(0))) {
419 // FIXME: Handle wide strings
420 if (ElementType->isCharType()) {
421 if (isConstant) {
422 if (literal->getByteLength() > (unsigned)nInitializers) {
423 Diag(literal->getSourceRange().getBegin(),
424 diag::warn_initializer_string_for_char_array_too_long,
425 literal->getSourceRange());
426 }
427 } else {
428 nInitializers = literal->getByteLength() + 1;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000429 }
Steve Naroff371227d2007-09-04 02:20:04 +0000430 } else {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000431 // FIXME: It might be better if we could point to the declaration
432 // here, instead of the string literal.
433 Diag(literal->getSourceRange().getBegin(),
434 diag::array_of_wrong_type_initialized_from_string,
435 ElementType.getAsString());
436 hadError = true;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000437 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000438
439 // Check for excess initializers
440 for (unsigned i = 1; i < IList->getNumInits(); i++) {
441 Expr *expr = IList->getInit(i);
442 Diag(expr->getLocStart(),
443 diag::err_excess_initializers_in_char_array_initializer,
444 expr->getSourceRange());
445 }
446
447 return true;
Steve Naroff371227d2007-09-04 02:20:04 +0000448 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000449
450 return false;
Steve Naroff371227d2007-09-04 02:20:04 +0000451}
452
453// FIXME: Doesn't deal with arrays of structures yet.
454void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000455 QualType ElementType,
Steve Naroff371227d2007-09-04 02:20:04 +0000456 int &totalInits, bool &hadError) {
457 int maxElementsAtThisLevel = 0;
458 int nInitsAtLevel = 0;
459
Steve Naroff32c39042007-12-07 21:12:53 +0000460 if (ElementType->isRecordType()) // FIXME: until we support structures...
461 return;
462
Steve Naroff371227d2007-09-04 02:20:04 +0000463 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
464 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff7cf8c442007-09-04 21:13:33 +0000465 maxElementsAtThisLevel = CAT->getMaximumElements();
466 // Set DeclType, used below to recurse (for multi-dimensional arrays).
467 DeclType = CAT->getElementType();
Steve Naroff371227d2007-09-04 02:20:04 +0000468 } else if (DeclType->isScalarType()) {
Anders Carlssonf0049e62007-12-03 01:01:28 +0000469 if (const VectorType *VT = DeclType->getAsVectorType())
470 maxElementsAtThisLevel = VT->getNumElements();
471 else {
472 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
473 IList->getSourceRange());
474 maxElementsAtThisLevel = 1;
475 }
Steve Naroff371227d2007-09-04 02:20:04 +0000476 }
477 // The empty init list "{ }" is treated specially below.
478 unsigned numInits = IList->getNumInits();
479 if (numInits) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000480 if (CheckForCharArrayInitializer(IList, ElementType,
481 maxElementsAtThisLevel,
482 true, hadError))
483 return;
484
Steve Naroff371227d2007-09-04 02:20:04 +0000485 for (unsigned i = 0; i < numInits; i++) {
486 Expr *expr = IList->getInit(i);
487
488 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
Steve Naroffd0091aa2008-01-10 22:15:12 +0000489 CheckConstantInitList(DeclType, InitList, ElementType,
Steve Naroff371227d2007-09-04 02:20:04 +0000490 totalInits, hadError);
491 } else {
Steve Naroffd0091aa2008-01-10 22:15:12 +0000492 hadError = CheckInitExpr(expr, IList, i, ElementType);
Steve Naroff371227d2007-09-04 02:20:04 +0000493 nInitsAtLevel++; // increment the number of initializers at this level.
494 totalInits--; // decrement the total number of initializers.
495
496 // Check if we have space for another initializer.
Anders Carlsson677cda12007-12-05 04:57:06 +0000497 if (((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0)))
Steve Naroff371227d2007-09-04 02:20:04 +0000498 Diag(expr->getLocStart(), diag::warn_excess_initializers,
499 expr->getSourceRange());
500 }
501 }
502 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
503 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
504 } else {
505 // we have an initializer list with no elements.
506 totalInits -= maxElementsAtThisLevel;
507 if (totalInits < 0)
508 Diag(IList->getLocStart(), diag::warn_excess_initializers,
509 IList->getSourceRange());
Steve Naroff6f9f3072007-09-02 15:34:30 +0000510 }
Steve Naroff6f9f3072007-09-02 15:34:30 +0000511}
512
Steve Naroffd0091aa2008-01-10 22:15:12 +0000513bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000514 bool hadError = false;
Anders Carlsson1a86b332007-10-17 00:52:43 +0000515
Steve Naroffca107302008-01-21 23:53:58 +0000516 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
517 // of unknown size ("[]") or an object type that is not a variable array type.
518 if (const VariableArrayType *VAT = DeclType->getAsVariablyModifiedType())
519 return Diag(VAT->getSizeExpr()->getLocStart(),
520 diag::err_variable_object_no_init,
521 VAT->getSizeExpr()->getSourceRange());
522
Steve Naroff2fdc3742007-12-10 22:44:33 +0000523 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
524 if (!InitList) {
525 if (StringLiteral *strLiteral = dyn_cast<StringLiteral>(Init)) {
526 const VariableArrayType *VAT = DeclType->getAsVariableArrayType();
527 // FIXME: Handle wide strings
528 if (VAT && VAT->getElementType()->isCharType()) {
529 // C99 6.7.8p14. We have an array of character type with unknown size
530 // being initialized to a string literal.
531 llvm::APSInt ConstVal(32);
532 ConstVal = strLiteral->getByteLength() + 1;
533 // Return a new array type (C99 6.7.8p22).
534 DeclType = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
535 ArrayType::Normal, 0);
Steve Naroff32150f32007-12-11 00:00:01 +0000536 // set type from "char *" to "constant array of char".
537 strLiteral->setType(DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000538 return hadError;
539 }
540 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
541 if (CAT && CAT->getElementType()->isCharType()) {
542 // C99 6.7.8p14. We have an array of character type with known size.
543 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements()) {
544 Diag(strLiteral->getSourceRange().getBegin(),
545 diag::warn_initializer_string_for_char_array_too_long,
546 strLiteral->getSourceRange());
547 }
Steve Naroff32150f32007-12-11 00:00:01 +0000548 // set type from "char *" to "constant array of char".
549 strLiteral->setType(DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000550 return hadError;
551 }
552 }
Steve Naroffd0091aa2008-01-10 22:15:12 +0000553 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000554 }
Steve Narofff0090632007-09-02 02:04:30 +0000555 // We have an InitListExpr, make sure we set the type.
556 Init->setType(DeclType);
Steve Naroffd35005e2007-09-03 01:24:23 +0000557
Steve Naroff38374b02007-09-02 20:30:18 +0000558 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
559 // of unknown size ("[]") or an object type that is not a variable array type.
Steve Naroffca107302008-01-21 23:53:58 +0000560 if (const VariableArrayType *VAT = DeclType->getAsIncompleteArrayType()) {
Steve Naroffd35005e2007-09-03 01:24:23 +0000561
Steve Naroff7cf8c442007-09-04 21:13:33 +0000562 // We have a VariableArrayType with unknown size. Note that only the first
563 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff371227d2007-09-04 02:20:04 +0000564 int numInits = 0;
Steve Naroff7cf8c442007-09-04 21:13:33 +0000565 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
Steve Naroffd0091aa2008-01-10 22:15:12 +0000566 numInits, hadError);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000567 llvm::APSInt ConstVal(32);
568
569 if (!hadError)
Steve Naroff371227d2007-09-04 02:20:04 +0000570 ConstVal = numInits;
Steve Naroff2fdc3742007-12-10 22:44:33 +0000571
572 // Return a new array type from the number of initializers (C99 6.7.8p22).
573
574 // Note that if there was an error, we will still set the decl type,
575 // to an array type with 0 elements.
576 // This is to avoid "incomplete type foo[]" errors when we've already
577 // reported the real cause of the error.
578 DeclType = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
579 ArrayType::Normal, 0);
Steve Naroffd35005e2007-09-03 01:24:23 +0000580 return hadError;
581 }
582 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000583 int maxElements = CAT->getMaximumElements();
584 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
Steve Naroffd0091aa2008-01-10 22:15:12 +0000585 maxElements, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000586 return hadError;
587 }
Anders Carlssonf0049e62007-12-03 01:01:28 +0000588 if (const VectorType *VT = DeclType->getAsVectorType()) {
589 int maxElements = VT->getNumElements();
590 CheckConstantInitList(DeclType, InitList, VT->getElementType(),
Steve Naroffd0091aa2008-01-10 22:15:12 +0000591 maxElements, hadError);
Anders Carlssonf0049e62007-12-03 01:01:28 +0000592 return hadError;
593 }
Steve Naroff371227d2007-09-04 02:20:04 +0000594 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
595 int maxElements = 1;
Steve Naroffd0091aa2008-01-10 22:15:12 +0000596 CheckConstantInitList(DeclType, InitList, DeclType, maxElements, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000597 return hadError;
Steve Naroff38374b02007-09-02 20:30:18 +0000598 }
Steve Naroffe6386392007-12-05 04:00:10 +0000599 // FIXME: Handle struct/union types, including those appearing in a
600 // CompoundLiteralExpr...
Steve Naroffd35005e2007-09-03 01:24:23 +0000601 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +0000602}
603
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000604Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000605Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000606 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000607 IdentifierInfo *II = D.getIdentifier();
608
Chris Lattnere80a59c2007-07-25 00:24:17 +0000609 // All of these full declarators require an identifier. If it doesn't have
610 // one, the ParsedFreeStandingDeclSpec action should be used.
611 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000612 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000613 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000614 D.getDeclSpec().getSourceRange(), D.getSourceRange());
615 return 0;
616 }
617
Chris Lattner31e05722007-08-26 06:24:45 +0000618 // The scope passed in may not be a decl scope. Zip up the scope tree until
619 // we find one that is.
620 while ((S->getFlags() & Scope::DeclScope) == 0)
621 S = S->getParent();
622
Reid Spencer5f016e22007-07-11 17:01:13 +0000623 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000624 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
625 D.getIdentifierLoc(), S);
Steve Naroffc752d042007-09-13 18:10:37 +0000626 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000627 bool InvalidDecl = false;
628
Chris Lattner41af0932007-11-14 06:34:38 +0000629 QualType R = GetTypeForDeclarator(D, S);
630 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
631
Reid Spencer5f016e22007-07-11 17:01:13 +0000632 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000633 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000634 if (!NewTD) return 0;
635
636 // Handle attributes prior to checking for duplicates in MergeVarDecl
637 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
638 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000639 // Merge the decl with the existing one if appropriate. If the decl is
640 // in an outer scope, it isn't the same thing.
641 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000642 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
643 if (NewTD == 0) return 0;
644 }
645 New = NewTD;
646 if (S->getParent() == 0) {
647 // C99 6.7.7p2: If a typedef name specifies a variably modified type
648 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000649 if (const VariableArrayType *VAT =
650 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
651 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
652 VAT->getSizeExpr()->getSourceRange());
653 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000654 }
655 }
Chris Lattner41af0932007-11-14 06:34:38 +0000656 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000657 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000658 switch (D.getDeclSpec().getStorageClassSpec()) {
659 default: assert(0 && "Unknown storage class!");
660 case DeclSpec::SCS_auto:
661 case DeclSpec::SCS_register:
662 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
663 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000664 InvalidDecl = true;
665 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000666 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
667 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
668 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
669 }
670
671 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000672 D.getDeclSpec().isInlineSpecified(),
Nate Begeman1b4e2512007-11-13 22:14:47 +0000673 LastDeclarator,
674 D.getDeclSpec().getAttributes());
675
676 // Transfer ownership of DeclSpec attributes to FunctionDecl
677 D.getDeclSpec().clearAttributes();
Reid Spencer5f016e22007-07-11 17:01:13 +0000678
Steve Naroffffce4d52008-01-09 23:34:55 +0000679 // Merge the decl with the existing one if appropriate. Since C functions
680 // are in a flat namespace, make sure we consider decls in outer scopes.
Reid Spencer5f016e22007-07-11 17:01:13 +0000681 if (PrevDecl) {
682 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
683 if (NewFD == 0) return 0;
684 }
685 New = NewFD;
686 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000687 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000688 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
689 D.getIdentifier()->getName());
690 InvalidDecl = true;
691 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000692
693 VarDecl *NewVD;
694 VarDecl::StorageClass SC;
695 switch (D.getDeclSpec().getStorageClassSpec()) {
696 default: assert(0 && "Unknown storage class!");
697 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
698 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
699 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
700 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
701 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
702 }
703 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000704 // C99 6.9p2: The storage-class specifiers auto and register shall not
705 // appear in the declaration specifiers in an external declaration.
706 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
707 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
708 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000709 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000710 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000711 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000712 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000713 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000714 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 // Handle attributes prior to checking for duplicates in MergeVarDecl
716 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
717 D.getAttributes());
718
Steve Naroffffce4d52008-01-09 23:34:55 +0000719 // Merge the decl with the existing one if appropriate. If the decl is
720 // in an outer scope, it isn't the same thing.
721 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000722 NewVD = MergeVarDecl(NewVD, PrevDecl);
723 if (NewVD == 0) return 0;
724 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 New = NewVD;
726 }
727
728 // If this has an identifier, add it to the scope stack.
729 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000730 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 II->setFETokenInfo(New);
732 S->AddDecl(New);
733 }
Steve Naroff5912a352007-08-28 20:14:24 +0000734 // If any semantic error occurred, mark the decl as invalid.
735 if (D.getInvalidType() || InvalidDecl)
736 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000737
738 return New;
739}
740
Steve Naroffd0091aa2008-01-10 22:15:12 +0000741bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
742 SourceLocation loc;
743 // FIXME: Remove the isReference check and handle assignment to a reference.
744 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
745 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
746 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
747 return true;
748 }
749 return false;
750}
751
Steve Naroffbb204692007-09-12 14:07:44 +0000752void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000753 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000754 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000755 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000756
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000757 // If there is no declaration, there was an error parsing it. Just ignore
758 // the initializer.
759 if (RealDecl == 0) {
760 delete Init;
761 return;
762 }
Steve Naroffbb204692007-09-12 14:07:44 +0000763
Steve Naroff410e3e22007-09-12 20:13:48 +0000764 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
765 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000766 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
767 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000768 RealDecl->setInvalidDecl();
769 return;
770 }
Steve Naroffbb204692007-09-12 14:07:44 +0000771 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +0000772 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000773 QualType DclT = VDecl->getType(), SavT = DclT;
774 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000775 VarDecl::StorageClass SC = BVD->getStorageClass();
776 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000777 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000778 BVD->setInvalidDecl();
779 } else if (!BVD->isInvalidDecl()) {
Steve Naroffd0091aa2008-01-10 22:15:12 +0000780 CheckInitializerTypes(Init, DclT);
781 if (SC == VarDecl::Static) // C99 6.7.8p4.
782 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000783 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000784 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000785 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000786 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000787 if (!FVD->isInvalidDecl())
Steve Naroffd0091aa2008-01-10 22:15:12 +0000788 CheckInitializerTypes(Init, DclT);
789
790 // C99 6.7.8p4. All file scoped initializers need to be constant.
791 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000792 }
793 // If the type changed, it means we had an incomplete type that was
794 // completed by the initializer. For example:
795 // int ary[] = { 1, 3, 5 };
796 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +0000797 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000798 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +0000799 Init->setType(DclT);
800 }
Steve Naroffbb204692007-09-12 14:07:44 +0000801
802 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000803 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000804 return;
805}
806
Reid Spencer5f016e22007-07-11 17:01:13 +0000807/// The declarators are chained together backwards, reverse the list.
808Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
809 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000810 Decl *GroupDecl = static_cast<Decl*>(group);
811 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000812 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000813
814 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
815 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000816 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000817 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000818 else { // reverse the list.
819 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000820 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000821 Group->setNextDeclarator(NewGroup);
822 NewGroup = Group;
823 Group = Next;
824 }
825 }
826 // Perform semantic analysis that depends on having fully processed both
827 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000828 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000829 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
830 if (!IDecl)
831 continue;
832 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
833 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
834 QualType T = IDecl->getType();
835
836 // C99 6.7.5.2p2: If an identifier is declared to be an object with
837 // static storage duration, it shall not have a variable length array.
838 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
839 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
840 if (VLA->getSizeExpr()) {
841 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
842 IDecl->setInvalidDecl();
843 }
844 }
845 }
846 // Block scope. C99 6.7p7: If an identifier for an object is declared with
847 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
848 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
849 if (T->isIncompleteType()) {
Chris Lattner8b1be772007-12-02 07:50:03 +0000850 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
851 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000852 IDecl->setInvalidDecl();
853 }
854 }
855 // File scope. C99 6.9.2p2: A declaration of an identifier for and
856 // object that has file scope without an initializer, and without a
857 // storage-class specifier or with the storage-class specifier "static",
858 // constitutes a tentative definition. Note: A tentative definition with
859 // external linkage is valid (C99 6.2.2p5).
Steve Naroffd3cd1e52008-01-18 00:39:39 +0000860 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
861 FVD->getStorageClass() == VarDecl::None)) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +0000862 const VariableArrayType *VAT = T->getAsVariableArrayType();
863
864 if (VAT && VAT->getSizeExpr() == 0) {
865 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
866 // array to be completed. Don't issue a diagnostic.
867 } else if (T->isIncompleteType()) {
868 // C99 6.9.2p3: If the declaration of an identifier for an object is
869 // a tentative definition and has internal linkage (C99 6.2.2p3), the
870 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +0000871 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
872 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000873 IDecl->setInvalidDecl();
874 }
875 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000876 }
877 return NewGroup;
878}
Steve Naroffe1223f72007-08-28 03:03:08 +0000879
880// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000881ParmVarDecl *
Nate Begemanbff5f5c2007-11-13 21:49:48 +0000882Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI, Scope *FnScope)
Steve Naroff66499922007-11-12 03:44:46 +0000883{
Reid Spencer5f016e22007-07-11 17:01:13 +0000884 IdentifierInfo *II = PI.Ident;
885 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
886 // Can this happen for params? We already checked that they don't conflict
887 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000888 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000889 PI.IdentLoc, FnScope)) {
890
891 }
892
893 // FIXME: Handle storage class (auto, register). No declarator?
894 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000895
896 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
897 // Doing the promotion here has a win and a loss. The win is the type for
898 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
899 // code generator). The loss is the orginal type isn't preserved. For example:
900 //
901 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
902 // int blockvardecl[5];
903 // sizeof(parmvardecl); // size == 4
904 // sizeof(blockvardecl); // size == 20
905 // }
906 //
907 // For expressions, all implicit conversions are captured using the
908 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
909 //
910 // FIXME: If a source translation tool needs to see the original type, then
911 // we need to consider storing both types (in ParmVarDecl)...
912 //
913 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattner529bd022008-01-02 22:50:48 +0000914 if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
915 // int x[restrict 4] -> int *restrict
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000916 parmDeclType = Context.getPointerType(AT->getElementType());
Chris Lattner529bd022008-01-02 22:50:48 +0000917 parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
918 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000919 parmDeclType = Context.getPointerType(parmDeclType);
920
921 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Nate Begeman1b4e2512007-11-13 22:14:47 +0000922 VarDecl::None, 0, PI.AttrList);
Steve Naroff53a32342007-08-28 18:45:29 +0000923 if (PI.InvalidType)
924 New->setInvalidDecl();
925
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 // If this has an identifier, add it to the scope stack.
927 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000928 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000929 II->setFETokenInfo(New);
930 FnScope->AddDecl(New);
931 }
932
933 return New;
934}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000935
Chris Lattnerb652cea2007-10-09 17:14:05 +0000936Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000937 assert(CurFunctionDecl == 0 && "Function parsing confused");
938 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
939 "Not a function declarator!");
940 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
941
942 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
943 // for a K&R function.
944 if (!FTI.hasPrototype) {
945 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
946 if (FTI.ArgInfo[i].TypeInfo == 0) {
947 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
948 FTI.ArgInfo[i].Ident->getName());
949 // Implicitly declare the argument as type 'int' for lack of a better
950 // type.
951 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
952 }
953 }
954
955 // Since this is a function definition, act as though we have information
956 // about the arguments.
957 FTI.hasPrototype = true;
958 } else {
959 // FIXME: Diagnose arguments without names in C.
960
961 }
962
963 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000964
965 // See if this is a redefinition.
966 ScopedDecl *PrevDcl = LookupScopedDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
967 D.getIdentifierLoc(), GlobalScope);
968 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
969 if (FD->getBody()) {
970 Diag(D.getIdentifierLoc(), diag::err_redefinition,
971 D.getIdentifier()->getName());
972 Diag(FD->getLocation(), diag::err_previous_definition);
973 }
974 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000975 FunctionDecl *FD =
Steve Naroff08d92e42007-09-15 18:49:24 +0000976 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000977 assert(FD != 0 && "ActOnDeclarator() didn't return a FunctionDecl");
Reid Spencer5f016e22007-07-11 17:01:13 +0000978 CurFunctionDecl = FD;
979
980 // Create Decl objects for each parameter, adding them to the FunctionDecl.
981 llvm::SmallVector<ParmVarDecl*, 16> Params;
982
983 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
984 // no arguments, not a function that takes a single void argument.
985 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb751c282007-11-28 18:51:29 +0000986 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getQualifiers() &&
987 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000988 // empty arg list, don't push any params.
989 } else {
Steve Naroff66499922007-11-12 03:44:46 +0000990 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begemanbff5f5c2007-11-13 21:49:48 +0000991 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroff66499922007-11-12 03:44:46 +0000992 FnBodyScope));
993 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000994 }
995
996 FD->setParams(&Params[0], Params.size());
997
998 return FD;
999}
1000
Steve Naroffd6d054d2007-11-11 23:20:51 +00001001Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1002 Decl *dcl = static_cast<Decl *>(D);
1003 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1004 FD->setBody((Stmt*)Body);
1005 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001006 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001007 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001008 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001009 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001010 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001011 // Verify and clean out per-function state.
1012
1013 // Check goto/label use.
1014 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1015 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1016 // Verify that we have no forward references left. If so, there was a goto
1017 // or address of a label taken, but no definition of it. Label fwd
1018 // definitions are indicated with a null substmt.
1019 if (I->second->getSubStmt() == 0) {
1020 LabelStmt *L = I->second;
1021 // Emit error.
1022 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1023
1024 // At this point, we have gotos that use the bogus label. Stitch it into
1025 // the function body so that they aren't leaked and that the AST is well
1026 // formed.
1027 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1028 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1029 }
1030 }
1031 LabelMap.clear();
1032
Steve Naroffd6d054d2007-11-11 23:20:51 +00001033 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001034}
1035
Reid Spencer5f016e22007-07-11 17:01:13 +00001036/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1037/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001038ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1039 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001040 if (getLangOptions().C99) // Extension in C99.
1041 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1042 else // Legal in C90, but warn about it.
1043 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1044
1045 // FIXME: handle stuff like:
1046 // void foo() { extern float X(); }
1047 // void bar() { X(); } <-- implicit decl for X in another scope.
1048
1049 // Set a Declarator for the implicit definition: int foo();
1050 const char *Dummy;
1051 DeclSpec DS;
1052 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1053 Error = Error; // Silence warning.
1054 assert(!Error && "Error setting up implicit decl!");
1055 Declarator D(DS, Declarator::BlockContext);
1056 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1057 D.SetIdentifier(&II, Loc);
1058
1059 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +00001060 if (Scope *FnS = S->getFnParent())
1061 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +00001062 while (S->getParent())
1063 S = S->getParent();
1064
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001065 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +00001066}
1067
1068
Chris Lattner41af0932007-11-14 06:34:38 +00001069TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001070 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001071 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001072 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001073
1074 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +00001075 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
1076 T, LastDeclarator);
1077 if (D.getInvalidType())
1078 NewTD->setInvalidDecl();
1079 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001080}
1081
Steve Naroff08d92e42007-09-15 18:49:24 +00001082/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001083/// former case, Name will be non-null. In the later case, Name will be null.
1084/// TagType indicates what kind of tag this is. TK indicates whether this is a
1085/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001086Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001087 SourceLocation KWLoc, IdentifierInfo *Name,
1088 SourceLocation NameLoc, AttributeList *Attr) {
1089 // If this is a use of an existing tag, it must have a name.
1090 assert((Name != 0 || TK == TK_Definition) &&
1091 "Nameless record must be a definition!");
1092
1093 Decl::Kind Kind;
1094 switch (TagType) {
1095 default: assert(0 && "Unknown tag type!");
1096 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1097 case DeclSpec::TST_union: Kind = Decl::Union; break;
1098//case DeclSpec::TST_class: Kind = Decl::Class; break;
1099 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1100 }
1101
1102 // If this is a named struct, check to see if there was a previous forward
1103 // declaration or definition.
1104 if (TagDecl *PrevDecl =
1105 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1106 NameLoc, S))) {
1107
1108 // If this is a use of a previous tag, or if the tag is already declared in
1109 // the same scope (so that the definition/declaration completes or
1110 // rementions the tag), reuse the decl.
1111 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1112 // Make sure that this wasn't declared as an enum and now used as a struct
1113 // or something similar.
1114 if (PrevDecl->getKind() != Kind) {
1115 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1116 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1117 }
1118
1119 // If this is a use or a forward declaration, we're good.
1120 if (TK != TK_Definition)
1121 return PrevDecl;
1122
1123 // Diagnose attempts to redefine a tag.
1124 if (PrevDecl->isDefinition()) {
1125 Diag(NameLoc, diag::err_redefinition, Name->getName());
1126 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1127 // If this is a redefinition, recover by making this struct be
1128 // anonymous, which will make any later references get the previous
1129 // definition.
1130 Name = 0;
1131 } else {
1132 // Okay, this is definition of a previously declared or referenced tag.
1133 // Move the location of the decl to be the definition site.
1134 PrevDecl->setLocation(NameLoc);
1135 return PrevDecl;
1136 }
1137 }
1138 // If we get here, this is a definition of a new struct type in a nested
1139 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1140 // type.
1141 }
1142
1143 // If there is an identifier, use the location of the identifier as the
1144 // location of the decl, otherwise use the location of the struct/union
1145 // keyword.
1146 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1147
1148 // Otherwise, if this is the first time we've seen this tag, create the decl.
1149 TagDecl *New;
1150 switch (Kind) {
1151 default: assert(0 && "Unknown tag kind!");
1152 case Decl::Enum:
1153 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1154 // enum X { A, B, C } D; D should chain to X.
1155 New = new EnumDecl(Loc, Name, 0);
1156 // If this is an undefined enum, warn.
1157 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1158 break;
1159 case Decl::Union:
1160 case Decl::Struct:
1161 case Decl::Class:
1162 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1163 // struct X { int A; } D; D should chain to X.
1164 New = new RecordDecl(Kind, Loc, Name, 0);
1165 break;
1166 }
1167
1168 // If this has an identifier, add it to the scope stack.
1169 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001170 // The scope passed in may not be a decl scope. Zip up the scope tree until
1171 // we find one that is.
1172 while ((S->getFlags() & Scope::DeclScope) == 0)
1173 S = S->getParent();
1174
1175 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001176 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001177 Name->setFETokenInfo(New);
1178 S->AddDecl(New);
1179 }
Steve Naroff1f644322007-11-28 22:54:11 +00001180
Reid Spencer5f016e22007-07-11 17:01:13 +00001181 return New;
1182}
1183
Steve Naroff08d92e42007-09-15 18:49:24 +00001184/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001185/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001186Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001187 SourceLocation DeclStart,
1188 Declarator &D, ExprTy *BitfieldWidth) {
1189 IdentifierInfo *II = D.getIdentifier();
1190 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 SourceLocation Loc = DeclStart;
1192 if (II) Loc = D.getIdentifierLoc();
1193
1194 // FIXME: Unnamed fields can be handled in various different ways, for
1195 // example, unnamed unions inject all members into the struct namespace!
1196
1197
1198 if (BitWidth) {
1199 // TODO: Validate.
1200 //printf("WARNING: BITFIELDS IGNORED!\n");
1201
1202 // 6.7.2.1p3
1203 // 6.7.2.1p4
1204
1205 } else {
1206 // Not a bitfield.
1207
1208 // validate II.
1209
1210 }
1211
1212 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001213 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1214 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001215
Reid Spencer5f016e22007-07-11 17:01:13 +00001216 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1217 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001218 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1219 Diag(Loc, diag::err_typecheck_illegal_vla,
1220 VAT->getSizeExpr()->getSourceRange());
1221 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001222 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001224 FieldDecl *NewFD;
1225
1226 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patel54e62352007-11-01 16:29:56 +00001227 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001228 else if (isa<ObjCInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1229 isa<ObjCImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
1230 isa<ObjCCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroffddd600f2007-11-14 14:15:31 +00001231 // FIXME: ivars are currently used to model properties, and
1232 // properties can appear within a protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001233 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1234 isa<ObjCProtocolDecl>(static_cast<Decl *>(TagDecl)))
1235 NewFD = new ObjCIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001236 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001237 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001238
Steve Naroff5912a352007-08-28 20:14:24 +00001239 if (D.getInvalidType() || InvalidDecl)
1240 NewFD->setInvalidDecl();
1241 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001242}
1243
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001244/// TranslateIvarVisibility - Translate visibility from a token ID to an
1245/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001246static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001247TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001248 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001249 case tok::objc_private: return ObjCIvarDecl::Private;
1250 case tok::objc_public: return ObjCIvarDecl::Public;
1251 case tok::objc_protected: return ObjCIvarDecl::Protected;
1252 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001253 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001254 }
1255}
1256
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001257void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001258 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001259 DeclTy **Fields, unsigned NumFields,
Steve Naroff60fccee2007-10-29 21:38:07 +00001260 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff08d92e42007-09-15 18:49:24 +00001261 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001262 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1263 assert(EnclosingDecl && "missing record or interface decl");
1264 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1265
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001266 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 // Diagnose code like:
1268 // struct S { struct S {} X; };
1269 // We discover this when we complete the outer S. Reject and ignore the
1270 // outer S.
1271 Diag(Record->getLocation(), diag::err_nested_redefinition,
1272 Record->getKindName());
1273 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001274 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 return;
1276 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001277 // Verify that all the fields are okay.
1278 unsigned NumNamedMembers = 0;
1279 llvm::SmallVector<FieldDecl*, 32> RecFields;
1280 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001281
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001283
Steve Naroff74216642007-09-14 22:20:54 +00001284 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1285 assert(FD && "missing field decl");
1286
1287 // Remember all fields.
1288 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001289
1290 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001291 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001292
Steve Narofff13271f2007-09-14 23:09:53 +00001293 // If we have visibility info, make sure the AST is set accordingly.
1294 if (visibility)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001295 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001296 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001297
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001299 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001300 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001302 FD->setInvalidDecl();
1303 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001304 continue;
1305 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1307 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001308 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001309 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001310 FD->setInvalidDecl();
1311 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001312 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001313 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 if (i != NumFields-1 || // ... that the last member ...
1315 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001316 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001318 FD->setInvalidDecl();
1319 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 continue;
1321 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001322 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001323 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1324 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001325 FD->setInvalidDecl();
1326 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 continue;
1328 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001330 if (Record)
1331 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001332 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001333 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1334 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001335 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001336 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1337 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001338 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 Record->setHasFlexibleArrayMember(true);
1340 } else {
1341 // If this is a struct/class and this is not the last element, reject
1342 // it. Note that GCC supports variable sized arrays in the middle of
1343 // structures.
1344 if (i != NumFields-1) {
1345 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1346 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001347 FD->setInvalidDecl();
1348 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 continue;
1350 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 // We support flexible arrays at the end of structs in other structs
1352 // as an extension.
1353 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1354 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001355 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001356 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 }
1358 }
1359 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001360 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001361 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001362 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1363 FD->getName());
1364 FD->setInvalidDecl();
1365 EnclosingDecl->setInvalidDecl();
1366 continue;
1367 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 // Keep track of the number of named members.
1369 if (IdentifierInfo *II = FD->getIdentifier()) {
1370 // Detect duplicate member names.
1371 if (!FieldIDs.insert(II)) {
1372 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1373 // Find the previous decl.
1374 SourceLocation PrevLoc;
1375 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1376 assert(i != e && "Didn't find previous def!");
1377 if (RecFields[i]->getIdentifier() == II) {
1378 PrevLoc = RecFields[i]->getLocation();
1379 break;
1380 }
1381 }
1382 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001383 FD->setInvalidDecl();
1384 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001385 continue;
1386 }
1387 ++NumNamedMembers;
1388 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 }
1390
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 // Okay, we successfully defined 'Record'.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001392 if (Record)
1393 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001394 else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001395 ObjCIvarDecl **ClsFields =
1396 reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1397 if (isa<ObjCInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1398 cast<ObjCInterfaceDecl>(static_cast<Decl*>(RecDecl))->
Steve Naroff60fccee2007-10-29 21:38:07 +00001399 addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001400 else if (isa<ObjCImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1401 ObjCImplementationDecl* IMPDecl =
1402 cast<ObjCImplementationDecl>(static_cast<Decl*>(RecDecl));
1403 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1404 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001405 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001406 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001407 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001408}
1409
Steve Naroff08d92e42007-09-15 18:49:24 +00001410Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 DeclTy *lastEnumConst,
1412 SourceLocation IdLoc, IdentifierInfo *Id,
1413 SourceLocation EqualLoc, ExprTy *val) {
1414 theEnumDecl = theEnumDecl; // silence unused warning.
1415 EnumConstantDecl *LastEnumConst =
1416 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1417 Expr *Val = static_cast<Expr*>(val);
1418
Chris Lattner31e05722007-08-26 06:24:45 +00001419 // The scope passed in may not be a decl scope. Zip up the scope tree until
1420 // we find one that is.
1421 while ((S->getFlags() & Scope::DeclScope) == 0)
1422 S = S->getParent();
1423
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 // Verify that there isn't already something declared with this name in this
1425 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001426 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1427 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 if (S->isDeclScope(PrevDecl)) {
1429 if (isa<EnumConstantDecl>(PrevDecl))
1430 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1431 else
1432 Diag(IdLoc, diag::err_redefinition, Id->getName());
1433 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1434 // FIXME: Don't leak memory: delete Val;
1435 return 0;
1436 }
1437 }
1438
1439 llvm::APSInt EnumVal(32);
1440 QualType EltTy;
1441 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001442 // Make sure to promote the operand type to int.
1443 UsualUnaryConversions(Val);
1444
Reid Spencer5f016e22007-07-11 17:01:13 +00001445 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1446 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001447 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001448 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1449 Id->getName());
1450 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001451 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001452 } else {
1453 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001454 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001455 }
1456
1457 if (!Val) {
1458 if (LastEnumConst) {
1459 // Assign the last value + 1.
1460 EnumVal = LastEnumConst->getInitVal();
1461 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001462
1463 // Check for overflow on increment.
1464 if (EnumVal < LastEnumConst->getInitVal())
1465 Diag(IdLoc, diag::warn_enum_value_overflow);
1466
Chris Lattnerb7416f92007-08-27 17:37:24 +00001467 EltTy = LastEnumConst->getType();
1468 } else {
1469 // First value, set to zero.
1470 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001471 EnumVal.zextOrTrunc(
1472 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001473 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001474 }
1475
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1477 LastEnumConst);
1478
1479 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001480 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001481 Id->setFETokenInfo(New);
1482 S->AddDecl(New);
1483 return New;
1484}
1485
Steve Naroff08d92e42007-09-15 18:49:24 +00001486void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 DeclTy **Elements, unsigned NumElements) {
1488 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1489 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1490
Chris Lattnere37f0be2007-08-28 05:10:31 +00001491 // TODO: If the result value doesn't fit in an int, it must be a long or long
1492 // long value. ISO C does not support this, but GCC does as an extension,
1493 // emit a warning.
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001494 unsigned IntWidth =
1495 Context.Target.getIntWidth(Context.getFullLoc(Enum->getLocation()));
Chris Lattnere37f0be2007-08-28 05:10:31 +00001496
1497
Chris Lattnerac609682007-08-28 06:15:15 +00001498 // Verify that all the values are okay, compute the size of the values, and
1499 // reverse the list.
1500 unsigned NumNegativeBits = 0;
1501 unsigned NumPositiveBits = 0;
1502
1503 // Keep track of whether all elements have type int.
1504 bool AllElementsInt = true;
1505
Reid Spencer5f016e22007-07-11 17:01:13 +00001506 EnumConstantDecl *EltList = 0;
1507 for (unsigned i = 0; i != NumElements; ++i) {
1508 EnumConstantDecl *ECD =
1509 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1510 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001511
1512 // If the enum value doesn't fit in an int, emit an extension warning.
1513 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1514 "Should have promoted value to int");
1515 const llvm::APSInt &InitVal = ECD->getInitVal();
1516 if (InitVal.getBitWidth() > IntWidth) {
1517 llvm::APSInt V(InitVal);
1518 V.trunc(IntWidth);
1519 V.extend(InitVal.getBitWidth());
1520 if (V != InitVal)
1521 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1522 InitVal.toString());
1523 }
Chris Lattnerac609682007-08-28 06:15:15 +00001524
1525 // Keep track of the size of positive and negative values.
1526 if (InitVal.isUnsigned() || !InitVal.isNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001527 NumPositiveBits = std::max(NumPositiveBits,
1528 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001529 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001530 NumNegativeBits = std::max(NumNegativeBits,
1531 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001532
Chris Lattnerac609682007-08-28 06:15:15 +00001533 // Keep track of whether every enum element has type int (very commmon).
1534 if (AllElementsInt)
1535 AllElementsInt = ECD->getType() == Context.IntTy;
1536
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 ECD->setNextDeclarator(EltList);
1538 EltList = ECD;
1539 }
1540
Chris Lattnerac609682007-08-28 06:15:15 +00001541 // Figure out the type that should be used for this enum.
1542 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1543 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001544 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001545
1546 if (NumNegativeBits) {
1547 // If there is a negative value, figure out the smallest integer type (of
1548 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001549 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001550 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001551 BestWidth = IntWidth;
1552 } else {
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001553 BestWidth =
1554 Context.Target.getLongWidth(Context.getFullLoc(Enum->getLocation()));
1555
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001556 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001557 BestType = Context.LongTy;
1558 else {
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001559 BestWidth = Context.Target.getLongLongWidth(
1560 Context.getFullLoc(Enum->getLocation()));
1561
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001562 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001563 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1564 BestType = Context.LongLongTy;
1565 }
1566 }
1567 } else {
1568 // If there is no negative value, figure out which of uint, ulong, ulonglong
1569 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001570 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001571 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001572 BestWidth = IntWidth;
1573 } else if (NumPositiveBits <=
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001574 (BestWidth = Context.Target.getLongWidth(
1575 Context.getFullLoc(Enum->getLocation()))))
1576
Chris Lattnerac609682007-08-28 06:15:15 +00001577 BestType = Context.UnsignedLongTy;
1578 else {
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001579 BestWidth =
1580 Context.Target.getLongLongWidth(Context.getFullLoc(Enum->getLocation()));
1581
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001582 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001583 "How could an initializer get larger than ULL?");
1584 BestType = Context.UnsignedLongLongTy;
1585 }
1586 }
1587
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001588 // Loop over all of the enumerator constants, changing their types to match
1589 // the type of the enum if needed.
1590 for (unsigned i = 0; i != NumElements; ++i) {
1591 EnumConstantDecl *ECD =
1592 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1593 if (!ECD) continue; // Already issued a diagnostic.
1594
1595 // Standard C says the enumerators have int type, but we allow, as an
1596 // extension, the enumerators to be larger than int size. If each
1597 // enumerator value fits in an int, type it as an int, otherwise type it the
1598 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1599 // that X has type 'int', not 'unsigned'.
1600 if (ECD->getType() == Context.IntTy)
1601 continue; // Already int type.
1602
1603 // Determine whether the value fits into an int.
1604 llvm::APSInt InitVal = ECD->getInitVal();
1605 bool FitsInInt;
1606 if (InitVal.isUnsigned() || !InitVal.isNegative())
1607 FitsInInt = InitVal.getActiveBits() < IntWidth;
1608 else
1609 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1610
1611 // If it fits into an integer type, force it. Otherwise force it to match
1612 // the enum decl type.
1613 QualType NewTy;
1614 unsigned NewWidth;
1615 bool NewSign;
1616 if (FitsInInt) {
1617 NewTy = Context.IntTy;
1618 NewWidth = IntWidth;
1619 NewSign = true;
1620 } else if (ECD->getType() == BestType) {
1621 // Already the right type!
1622 continue;
1623 } else {
1624 NewTy = BestType;
1625 NewWidth = BestWidth;
1626 NewSign = BestType->isSignedIntegerType();
1627 }
1628
1629 // Adjust the APSInt value.
1630 InitVal.extOrTrunc(NewWidth);
1631 InitVal.setIsSigned(NewSign);
1632 ECD->setInitVal(InitVal);
1633
1634 // Adjust the Expr initializer and type.
1635 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1636 ECD->setType(NewTy);
1637 }
Chris Lattnerac609682007-08-28 06:15:15 +00001638
Chris Lattnere00b18c2007-08-28 18:24:31 +00001639 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001640}
1641
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001642Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
1643 SourceLocation LBrace,
1644 SourceLocation RBrace,
1645 const char *Lang,
1646 unsigned StrSize,
1647 DeclTy *D) {
1648 LinkageSpecDecl::LanguageIDs Language;
1649 Decl *dcl = static_cast<Decl *>(D);
1650 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1651 Language = LinkageSpecDecl::lang_c;
1652 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1653 Language = LinkageSpecDecl::lang_cxx;
1654 else {
1655 Diag(Loc, diag::err_bad_language);
1656 return 0;
1657 }
1658
1659 // FIXME: Add all the various semantics of linkage specifications
1660 return new LinkageSpecDecl(Loc, Language, dcl);
1661}
1662
Reid Spencer5f016e22007-07-11 17:01:13 +00001663void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001664 const char *attrName = rawAttr->getAttributeName()->getName();
1665 unsigned attrLen = rawAttr->getAttributeName()->getLength();
1666
Anders Carlssonabf5ad02007-12-19 17:43:24 +00001667 // Normalize the attribute name, __foo__ becomes foo.
1668 if (attrLen > 4 && attrName[0] == '_' && attrName[1] == '_' &&
1669 attrName[attrLen - 2] == '_' && attrName[attrLen - 1] == '_') {
1670 attrName += 2;
1671 attrLen -= 4;
1672 }
1673
1674 if (attrLen == 11 && !memcmp(attrName, "vector_size", 11)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1676 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1677 if (!newType.isNull()) // install the new vector type into the decl
1678 vDecl->setType(newType);
1679 }
1680 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1681 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1682 rawAttr);
1683 if (!newType.isNull()) // install the new vector type into the decl
1684 tDecl->setUnderlyingType(newType);
1685 }
Anders Carlssonabf5ad02007-12-19 17:43:24 +00001686 } else if (attrLen == 15 && !memcmp(attrName, "ocu_vector_type", 15)) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001687 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1688 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1689 else
Steve Naroff73322922007-07-18 18:00:27 +00001690 Diag(rawAttr->getAttributeLoc(),
1691 diag::err_typecheck_ocu_vector_not_typedef);
Anders Carlsson78aaae92007-12-19 07:19:40 +00001692 } else if (attrLen == 7 && !memcmp(attrName, "aligned", 7)) {
1693 HandleAlignedAttribute(New, rawAttr);
Steve Naroff73322922007-07-18 18:00:27 +00001694 }
Anders Carlsson78aaae92007-12-19 07:19:40 +00001695
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 // FIXME: add other attributes...
1697}
1698
1699void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1700 AttributeList *declarator_postfix) {
1701 while (declspec_prefix) {
1702 HandleDeclAttribute(New, declspec_prefix);
1703 declspec_prefix = declspec_prefix->getNext();
1704 }
1705 while (declarator_postfix) {
1706 HandleDeclAttribute(New, declarator_postfix);
1707 declarator_postfix = declarator_postfix->getNext();
1708 }
1709}
1710
Steve Naroffbea0b342007-07-29 16:33:31 +00001711void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1712 AttributeList *rawAttr) {
1713 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00001714 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00001715 if (rawAttr->getNumArgs() != 1) {
1716 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1717 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001718 return;
Steve Naroff73322922007-07-18 18:00:27 +00001719 }
1720 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1721 llvm::APSInt vecSize(32);
1722 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1723 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1724 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001725 return;
Steve Naroff73322922007-07-18 18:00:27 +00001726 }
1727 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1728 // in conjunction with complex types (pointers, arrays, functions, etc.).
1729 Type *canonType = curType.getCanonicalType().getTypePtr();
1730 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1731 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1732 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001733 return;
Steve Naroff73322922007-07-18 18:00:27 +00001734 }
1735 // unlike gcc's vector_size attribute, the size is specified as the
1736 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001737 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001738
1739 if (vectorSize == 0) {
1740 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1741 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001742 return;
Steve Naroff73322922007-07-18 18:00:27 +00001743 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001744 // Instantiate/Install the vector type, the number of elements is > 0.
1745 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1746 // Remember this typedef decl, we will need it later for diagnostics.
1747 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001748}
1749
Reid Spencer5f016e22007-07-11 17:01:13 +00001750QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001751 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 // check the attribute arugments.
1753 if (rawAttr->getNumArgs() != 1) {
1754 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1755 std::string("1"));
1756 return QualType();
1757 }
1758 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1759 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001760 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001761 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1762 sizeExpr->getSourceRange());
1763 return QualType();
1764 }
1765 // navigate to the base type - we need to provide for vector pointers,
1766 // vector arrays, and functions returning vectors.
1767 Type *canonType = curType.getCanonicalType().getTypePtr();
1768
Steve Naroff73322922007-07-18 18:00:27 +00001769 if (canonType->isPointerType() || canonType->isArrayType() ||
1770 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00001771 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00001772 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1773 do {
1774 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1775 canonType = PT->getPointeeType().getTypePtr();
1776 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1777 canonType = AT->getElementType().getTypePtr();
1778 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1779 canonType = FT->getResultType().getTypePtr();
1780 } while (canonType->isPointerType() || canonType->isArrayType() ||
1781 canonType->isFunctionType());
1782 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001783 }
1784 // the base type must be integer or float.
1785 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1786 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1787 curType.getCanonicalType().getAsString());
1788 return QualType();
1789 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00001790 unsigned typeSize = static_cast<unsigned>(
1791 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001792 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001793 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00001794
1795 // the vector size needs to be an integral multiple of the type size.
1796 if (vectorSize % typeSize) {
1797 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1798 sizeExpr->getSourceRange());
1799 return QualType();
1800 }
1801 if (vectorSize == 0) {
1802 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1803 sizeExpr->getSourceRange());
1804 return QualType();
1805 }
1806 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1807 // the number of elements to be a power of two (unlike GCC).
1808 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00001809 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001810}
1811
Anders Carlsson78aaae92007-12-19 07:19:40 +00001812void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
1813{
1814 // check the attribute arguments.
Anders Carlssonabf5ad02007-12-19 17:43:24 +00001815 // FIXME: Handle the case where are no arguments.
Anders Carlsson78aaae92007-12-19 07:19:40 +00001816 if (rawAttr->getNumArgs() != 1) {
1817 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1818 std::string("1"));
1819 return;
1820 }
1821
1822 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
1823 llvm::APSInt alignment(32);
1824 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
1825 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1826 alignmentExpr->getSourceRange());
1827 return;
1828 }
1829}