blob: 7c089ee37b45ec51690cff758e5c6bad30d82065 [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
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000379bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
380 if (const VariableArrayType *VAT = DeclT->getAsIncompleteArrayType()) {
381 // C99 6.7.8p14. We have an array of character type with unknown size
382 // being initialized to a string literal.
383 llvm::APSInt ConstVal(32);
384 ConstVal = strLiteral->getByteLength() + 1;
385 // Return a new array type (C99 6.7.8p22).
386 DeclT = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
387 ArrayType::Normal, 0);
388 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
389 // C99 6.7.8p14. We have an array of character type with known size.
390 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
391 Diag(strLiteral->getSourceRange().getBegin(),
392 diag::warn_initializer_string_for_char_array_too_long,
393 strLiteral->getSourceRange());
394 } else {
395 assert(0 && "HandleStringLiteralInit(): Invalid array type");
396 }
397 // Set type from "char *" to "constant array of char".
398 strLiteral->setType(DeclT);
399 // For now, we always return false (meaning success).
400 return false;
401}
402
403StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000404 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000405 if (AT && AT->getElementType()->isCharType()) {
406 return dyn_cast<StringLiteral>(Init);
407 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000408 return 0;
409}
410
Steve Naroffa9960332008-01-25 00:51:06 +0000411// CheckInitializerListTypes - Checks the types of elements of an initializer
412// list. This function is recursive: it calls itself to initialize subelements
413// of aggregate types. Note that the topLevel parameter essentially refers to
414// whether this expression "owns" the initializer list passed in, or if this
415// initialization is taking elements out of a parent initializer. Each
416// call to this function adds zero or more to startIndex, reports any errors,
417// and returns true if it found any inconsistent types.
418bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
419 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000420 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000421
422 if (DeclType->isScalarType()) {
423 // The simplest case: initializing a single scalar
424 if (topLevel) {
425 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
426 IList->getSourceRange());
427 }
428 if (startIndex < IList->getNumInits()) {
429 Expr* expr = IList->getInit(startIndex);
430 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
431 // FIXME: Should an error be reported here instead?
432 unsigned newIndex = 0;
433 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
434 } else {
435 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
436 }
437 ++startIndex;
438 }
439 // FIXME: Should an error be reported for empty initializer list + scalar?
440 } else if (DeclType->isVectorType()) {
441 if (startIndex < IList->getNumInits()) {
442 const VectorType *VT = DeclType->getAsVectorType();
443 int maxElements = VT->getNumElements();
444 QualType elementType = VT->getElementType();
445
446 for (int i = 0; i < maxElements; ++i) {
447 // Don't attempt to go past the end of the init list
448 if (startIndex >= IList->getNumInits())
449 break;
450 Expr* expr = IList->getInit(startIndex);
451 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
452 unsigned newIndex = 0;
453 hadError |= CheckInitializerListTypes(SubInitList, elementType,
454 true, newIndex);
455 ++startIndex;
456 } else {
457 hadError |= CheckInitializerListTypes(IList, elementType,
458 false, startIndex);
459 }
460 }
461 }
462 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
463 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000464 if (startIndex < IList->getNumInits() && !topLevel &&
465 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
466 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000467 // We found a compatible struct; per the standard, this initializes the
468 // struct. (The C standard technically says that this only applies for
469 // initializers for declarations with automatic scope; however, this
470 // construct is unambiguous anyway because a struct cannot contain
471 // a type compatible with itself. We'll output an error when we check
472 // if the initializer is constant.)
473 // FIXME: Is a call to CheckSingleInitializer required here?
474 ++startIndex;
475 } else {
476 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
477 // If structDecl is a forward declaration, this loop won't do anything;
478 // That's okay, because an error should get printed out elsewhere. It
479 // might be worthwhile to skip over the rest of the initializer, though.
480 int numMembers = structDecl->getNumMembers() -
481 structDecl->hasFlexibleArrayMember();
482 for (int i = 0; i < numMembers; i++) {
483 // Don't attempt to go past the end of the init list
484 if (startIndex >= IList->getNumInits())
485 break;
486 FieldDecl * curField = structDecl->getMember(i);
487 if (!curField->getIdentifier()) {
488 // Don't initialize unnamed fields, e.g. "int : 20;"
489 continue;
490 }
491 QualType fieldType = curField->getType();
492 Expr* expr = IList->getInit(startIndex);
493 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
494 unsigned newStart = 0;
495 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
496 true, newStart);
497 ++startIndex;
498 } else {
499 hadError |= CheckInitializerListTypes(IList, fieldType,
500 false, startIndex);
501 }
502 if (DeclType->isUnionType())
503 break;
504 }
505 // FIXME: Implement flexible array initialization GCC extension (it's a
506 // really messy extension to implement, unfortunately...the necessary
507 // information isn't actually even here!)
508 }
509 } else if (DeclType->isArrayType()) {
510 // Check for the special-case of initializing an array with a string.
511 if (startIndex < IList->getNumInits()) {
512 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
513 DeclType)) {
514 CheckStringLiteralInit(lit, DeclType);
515 ++startIndex;
516 if (topLevel && startIndex < IList->getNumInits()) {
517 // We have leftover initializers; warn
518 Diag(IList->getInit(startIndex)->getLocStart(),
519 diag::err_excess_initializers_in_char_array_initializer,
520 IList->getInit(startIndex)->getSourceRange());
521 }
522 return false;
523 }
524 }
525 int maxElements;
526 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
527 // FIXME: use a proper constant
528 maxElements = 0x7FFFFFFF;
529 // Check for VLAs; in standard C it would be possible to check this
530 // earlier, but I don't know where clang accepts VLAs (gcc accepts
531 // them in all sorts of strange places).
532 if (const Expr *expr = VAT->getSizeExpr()) {
533 Diag(expr->getLocStart(), diag::err_variable_object_no_init,
534 expr->getSourceRange());
535 hadError = true;
536 }
537 } else {
538 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
539 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
540 }
541 QualType elementType = DeclType->getAsArrayType()->getElementType();
542 int numElements = 0;
543 for (int i = 0; i < maxElements; ++i, ++numElements) {
544 // Don't attempt to go past the end of the init list
545 if (startIndex >= IList->getNumInits())
546 break;
547 Expr* expr = IList->getInit(startIndex);
548 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
549 unsigned newIndex = 0;
550 hadError |= CheckInitializerListTypes(SubInitList, elementType,
551 true, newIndex);
552 ++startIndex;
553 } else {
554 hadError |= CheckInitializerListTypes(IList, elementType,
555 false, startIndex);
556 }
557 }
558 if (DeclType->getAsVariableArrayType()) {
559 // If this is an incomplete array type, the actual type needs to
560 // be calculated here
561 if (numElements == 0) {
562 // Sizing an array implicitly to zero is not allowed
563 // (It could in theory be allowed, but it doesn't really matter.)
564 Diag(IList->getLocStart(),
565 diag::err_at_least_one_initializer_needed_to_size_array);
566 hadError = true;
567 } else {
568 llvm::APSInt ConstVal(32);
569 ConstVal = numElements;
570 DeclType = Context.getConstantArrayType(elementType, ConstVal,
571 ArrayType::Normal, 0);
572 }
573 }
574 } else {
575 assert(0 && "Aggregate that isn't a function or array?!");
576 }
577 } else {
578 // In C, all types are either scalars or aggregates, but
579 // additional handling is needed here for C++ (and possibly others?).
580 assert(0 && "Unsupported initializer type");
581 }
582
583 // If this init list is a base list, we set the type; an initializer doesn't
584 // fundamentally have a type, but this makes the ASTs a bit easier to read
585 if (topLevel)
586 IList->setType(DeclType);
587
588 if (topLevel && startIndex < IList->getNumInits()) {
589 // We have leftover initializers; warn
590 Diag(IList->getInit(startIndex)->getLocStart(),
591 diag::warn_excess_initializers,
592 IList->getInit(startIndex)->getSourceRange());
593 }
594 return hadError;
595}
596
597bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000598 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
599 // of unknown size ("[]") or an object type that is not a variable array type.
600 if (const VariableArrayType *VAT = DeclType->getAsVariablyModifiedType())
601 return Diag(VAT->getSizeExpr()->getLocStart(),
602 diag::err_variable_object_no_init,
603 VAT->getSizeExpr()->getSourceRange());
604
Steve Naroff2fdc3742007-12-10 22:44:33 +0000605 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
606 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000607 // FIXME: Handle wide strings
608 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
609 return CheckStringLiteralInit(strLiteral, DeclType);
Steve Naroffd0091aa2008-01-10 22:15:12 +0000610 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000611 }
Steve Naroffa9960332008-01-25 00:51:06 +0000612 unsigned newIndex = 0;
613 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Narofff0090632007-09-02 02:04:30 +0000614}
615
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000616Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000617Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000618 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000619 IdentifierInfo *II = D.getIdentifier();
620
Chris Lattnere80a59c2007-07-25 00:24:17 +0000621 // All of these full declarators require an identifier. If it doesn't have
622 // one, the ParsedFreeStandingDeclSpec action should be used.
623 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000624 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000625 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000626 D.getDeclSpec().getSourceRange(), D.getSourceRange());
627 return 0;
628 }
629
Chris Lattner31e05722007-08-26 06:24:45 +0000630 // The scope passed in may not be a decl scope. Zip up the scope tree until
631 // we find one that is.
632 while ((S->getFlags() & Scope::DeclScope) == 0)
633 S = S->getParent();
634
Reid Spencer5f016e22007-07-11 17:01:13 +0000635 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000636 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
637 D.getIdentifierLoc(), S);
Steve Naroffc752d042007-09-13 18:10:37 +0000638 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000639 bool InvalidDecl = false;
640
Chris Lattner41af0932007-11-14 06:34:38 +0000641 QualType R = GetTypeForDeclarator(D, S);
642 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
643
Reid Spencer5f016e22007-07-11 17:01:13 +0000644 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000645 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000646 if (!NewTD) return 0;
647
648 // Handle attributes prior to checking for duplicates in MergeVarDecl
649 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
650 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000651 // Merge the decl with the existing one if appropriate. If the decl is
652 // in an outer scope, it isn't the same thing.
653 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000654 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
655 if (NewTD == 0) return 0;
656 }
657 New = NewTD;
658 if (S->getParent() == 0) {
659 // C99 6.7.7p2: If a typedef name specifies a variably modified type
660 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000661 if (const VariableArrayType *VAT =
662 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
663 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
664 VAT->getSizeExpr()->getSourceRange());
665 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000666 }
667 }
Chris Lattner41af0932007-11-14 06:34:38 +0000668 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000669 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000670 switch (D.getDeclSpec().getStorageClassSpec()) {
671 default: assert(0 && "Unknown storage class!");
672 case DeclSpec::SCS_auto:
673 case DeclSpec::SCS_register:
674 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
675 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000676 InvalidDecl = true;
677 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000678 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
679 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
680 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000681 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000682 }
683
684 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000685 D.getDeclSpec().isInlineSpecified(),
Nate Begeman1b4e2512007-11-13 22:14:47 +0000686 LastDeclarator,
687 D.getDeclSpec().getAttributes());
688
689 // Transfer ownership of DeclSpec attributes to FunctionDecl
690 D.getDeclSpec().clearAttributes();
Reid Spencer5f016e22007-07-11 17:01:13 +0000691
Steve Naroffffce4d52008-01-09 23:34:55 +0000692 // Merge the decl with the existing one if appropriate. Since C functions
693 // are in a flat namespace, make sure we consider decls in outer scopes.
Reid Spencer5f016e22007-07-11 17:01:13 +0000694 if (PrevDecl) {
695 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
696 if (NewFD == 0) return 0;
697 }
698 New = NewFD;
699 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000700 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000701 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
702 D.getIdentifier()->getName());
703 InvalidDecl = true;
704 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000705
706 VarDecl *NewVD;
707 VarDecl::StorageClass SC;
708 switch (D.getDeclSpec().getStorageClassSpec()) {
709 default: assert(0 && "Unknown storage class!");
Steve Naroffd6326c62008-01-25 22:14:40 +0000710 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
711 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
712 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
713 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
714 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
715 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000716 }
717 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000718 // C99 6.9p2: The storage-class specifiers auto and register shall not
719 // appear in the declaration specifiers in an external declaration.
720 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
721 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
722 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000723 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000724 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000726 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000728 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000729 // Handle attributes prior to checking for duplicates in MergeVarDecl
730 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
731 D.getAttributes());
732
Steve Naroffffce4d52008-01-09 23:34:55 +0000733 // Merge the decl with the existing one if appropriate. If the decl is
734 // in an outer scope, it isn't the same thing.
735 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000736 NewVD = MergeVarDecl(NewVD, PrevDecl);
737 if (NewVD == 0) return 0;
738 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000739 New = NewVD;
740 }
741
742 // If this has an identifier, add it to the scope stack.
743 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000744 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 II->setFETokenInfo(New);
746 S->AddDecl(New);
747 }
Steve Naroff5912a352007-08-28 20:14:24 +0000748 // If any semantic error occurred, mark the decl as invalid.
749 if (D.getInvalidType() || InvalidDecl)
750 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000751
752 return New;
753}
754
Steve Naroffd0091aa2008-01-10 22:15:12 +0000755bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
756 SourceLocation loc;
757 // FIXME: Remove the isReference check and handle assignment to a reference.
758 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
759 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
760 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
761 return true;
762 }
763 return false;
764}
765
Steve Naroffbb204692007-09-12 14:07:44 +0000766void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000767 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000768 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000769 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000770
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000771 // If there is no declaration, there was an error parsing it. Just ignore
772 // the initializer.
773 if (RealDecl == 0) {
774 delete Init;
775 return;
776 }
Steve Naroffbb204692007-09-12 14:07:44 +0000777
Steve Naroff410e3e22007-09-12 20:13:48 +0000778 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
779 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000780 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
781 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000782 RealDecl->setInvalidDecl();
783 return;
784 }
Steve Naroffbb204692007-09-12 14:07:44 +0000785 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +0000786 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000787 QualType DclT = VDecl->getType(), SavT = DclT;
788 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000789 VarDecl::StorageClass SC = BVD->getStorageClass();
790 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000791 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000792 BVD->setInvalidDecl();
793 } else if (!BVD->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000794 if (CheckInitializerTypes(Init, DclT))
795 BVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000796 if (SC == VarDecl::Static) // C99 6.7.8p4.
797 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000798 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000799 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000800 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000801 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000802 if (!FVD->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +0000803 if (CheckInitializerTypes(Init, DclT))
804 FVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000805
806 // C99 6.7.8p4. All file scoped initializers need to be constant.
807 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000808 }
809 // If the type changed, it means we had an incomplete type that was
810 // completed by the initializer. For example:
811 // int ary[] = { 1, 3, 5 };
812 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +0000813 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000814 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +0000815 Init->setType(DclT);
816 }
Steve Naroffbb204692007-09-12 14:07:44 +0000817
818 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000819 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000820 return;
821}
822
Reid Spencer5f016e22007-07-11 17:01:13 +0000823/// The declarators are chained together backwards, reverse the list.
824Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
825 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000826 Decl *GroupDecl = static_cast<Decl*>(group);
827 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000828 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000829
830 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
831 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000832 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000833 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000834 else { // reverse the list.
835 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000836 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000837 Group->setNextDeclarator(NewGroup);
838 NewGroup = Group;
839 Group = Next;
840 }
841 }
842 // Perform semantic analysis that depends on having fully processed both
843 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000844 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000845 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
846 if (!IDecl)
847 continue;
848 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
849 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
850 QualType T = IDecl->getType();
851
852 // C99 6.7.5.2p2: If an identifier is declared to be an object with
853 // static storage duration, it shall not have a variable length array.
854 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
855 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
856 if (VLA->getSizeExpr()) {
857 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
858 IDecl->setInvalidDecl();
859 }
860 }
861 }
862 // Block scope. C99 6.7p7: If an identifier for an object is declared with
863 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
864 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
865 if (T->isIncompleteType()) {
Chris Lattner8b1be772007-12-02 07:50:03 +0000866 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
867 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000868 IDecl->setInvalidDecl();
869 }
870 }
871 // File scope. C99 6.9.2p2: A declaration of an identifier for and
872 // object that has file scope without an initializer, and without a
873 // storage-class specifier or with the storage-class specifier "static",
874 // constitutes a tentative definition. Note: A tentative definition with
875 // external linkage is valid (C99 6.2.2p5).
Steve Naroffd3cd1e52008-01-18 00:39:39 +0000876 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
877 FVD->getStorageClass() == VarDecl::None)) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +0000878 const VariableArrayType *VAT = T->getAsVariableArrayType();
879
880 if (VAT && VAT->getSizeExpr() == 0) {
881 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
882 // array to be completed. Don't issue a diagnostic.
883 } else if (T->isIncompleteType()) {
884 // C99 6.9.2p3: If the declaration of an identifier for an object is
885 // a tentative definition and has internal linkage (C99 6.2.2p3), the
886 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +0000887 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
888 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000889 IDecl->setInvalidDecl();
890 }
891 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000892 }
893 return NewGroup;
894}
Steve Naroffe1223f72007-08-28 03:03:08 +0000895
896// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000897ParmVarDecl *
Nate Begemanbff5f5c2007-11-13 21:49:48 +0000898Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI, Scope *FnScope)
Steve Naroff66499922007-11-12 03:44:46 +0000899{
Reid Spencer5f016e22007-07-11 17:01:13 +0000900 IdentifierInfo *II = PI.Ident;
901 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
902 // Can this happen for params? We already checked that they don't conflict
903 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000904 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000905 PI.IdentLoc, FnScope)) {
906
907 }
908
909 // FIXME: Handle storage class (auto, register). No declarator?
910 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000911
912 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
913 // Doing the promotion here has a win and a loss. The win is the type for
914 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
915 // code generator). The loss is the orginal type isn't preserved. For example:
916 //
917 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
918 // int blockvardecl[5];
919 // sizeof(parmvardecl); // size == 4
920 // sizeof(blockvardecl); // size == 20
921 // }
922 //
923 // For expressions, all implicit conversions are captured using the
924 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
925 //
926 // FIXME: If a source translation tool needs to see the original type, then
927 // we need to consider storing both types (in ParmVarDecl)...
928 //
929 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattner529bd022008-01-02 22:50:48 +0000930 if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
931 // int x[restrict 4] -> int *restrict
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000932 parmDeclType = Context.getPointerType(AT->getElementType());
Chris Lattner529bd022008-01-02 22:50:48 +0000933 parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
934 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000935 parmDeclType = Context.getPointerType(parmDeclType);
936
937 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Nate Begeman1b4e2512007-11-13 22:14:47 +0000938 VarDecl::None, 0, PI.AttrList);
Steve Naroff53a32342007-08-28 18:45:29 +0000939 if (PI.InvalidType)
940 New->setInvalidDecl();
941
Reid Spencer5f016e22007-07-11 17:01:13 +0000942 // If this has an identifier, add it to the scope stack.
943 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000944 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000945 II->setFETokenInfo(New);
946 FnScope->AddDecl(New);
947 }
948
949 return New;
950}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000951
Chris Lattnerb652cea2007-10-09 17:14:05 +0000952Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000953 assert(CurFunctionDecl == 0 && "Function parsing confused");
954 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
955 "Not a function declarator!");
956 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
957
958 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
959 // for a K&R function.
960 if (!FTI.hasPrototype) {
961 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
962 if (FTI.ArgInfo[i].TypeInfo == 0) {
963 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
964 FTI.ArgInfo[i].Ident->getName());
965 // Implicitly declare the argument as type 'int' for lack of a better
966 // type.
967 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
968 }
969 }
970
971 // Since this is a function definition, act as though we have information
972 // about the arguments.
973 FTI.hasPrototype = true;
974 } else {
975 // FIXME: Diagnose arguments without names in C.
976
977 }
978
979 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000980
981 // See if this is a redefinition.
982 ScopedDecl *PrevDcl = LookupScopedDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
983 D.getIdentifierLoc(), GlobalScope);
984 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
985 if (FD->getBody()) {
986 Diag(D.getIdentifierLoc(), diag::err_redefinition,
987 D.getIdentifier()->getName());
988 Diag(FD->getLocation(), diag::err_previous_definition);
989 }
990 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000991 FunctionDecl *FD =
Steve Naroff08d92e42007-09-15 18:49:24 +0000992 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000993 assert(FD != 0 && "ActOnDeclarator() didn't return a FunctionDecl");
Reid Spencer5f016e22007-07-11 17:01:13 +0000994 CurFunctionDecl = FD;
995
996 // Create Decl objects for each parameter, adding them to the FunctionDecl.
997 llvm::SmallVector<ParmVarDecl*, 16> Params;
998
999 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1000 // no arguments, not a function that takes a single void argument.
1001 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb751c282007-11-28 18:51:29 +00001002 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getQualifiers() &&
1003 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001004 // empty arg list, don't push any params.
1005 } else {
Steve Naroff66499922007-11-12 03:44:46 +00001006 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begemanbff5f5c2007-11-13 21:49:48 +00001007 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroff66499922007-11-12 03:44:46 +00001008 FnBodyScope));
1009 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001010 }
1011
1012 FD->setParams(&Params[0], Params.size());
1013
1014 return FD;
1015}
1016
Steve Naroffd6d054d2007-11-11 23:20:51 +00001017Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1018 Decl *dcl = static_cast<Decl *>(D);
1019 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1020 FD->setBody((Stmt*)Body);
1021 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001022 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001023 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001024 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001025 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001026 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001027 // Verify and clean out per-function state.
1028
1029 // Check goto/label use.
1030 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1031 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1032 // Verify that we have no forward references left. If so, there was a goto
1033 // or address of a label taken, but no definition of it. Label fwd
1034 // definitions are indicated with a null substmt.
1035 if (I->second->getSubStmt() == 0) {
1036 LabelStmt *L = I->second;
1037 // Emit error.
1038 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1039
1040 // At this point, we have gotos that use the bogus label. Stitch it into
1041 // the function body so that they aren't leaked and that the AST is well
1042 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001043 if (Body) {
1044 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1045 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1046 } else {
1047 // The whole function wasn't parsed correctly, just delete this.
1048 delete L;
1049 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001050 }
1051 }
1052 LabelMap.clear();
1053
Steve Naroffd6d054d2007-11-11 23:20:51 +00001054 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001055}
1056
Reid Spencer5f016e22007-07-11 17:01:13 +00001057/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1058/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001059ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1060 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001061 if (getLangOptions().C99) // Extension in C99.
1062 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1063 else // Legal in C90, but warn about it.
1064 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1065
1066 // FIXME: handle stuff like:
1067 // void foo() { extern float X(); }
1068 // void bar() { X(); } <-- implicit decl for X in another scope.
1069
1070 // Set a Declarator for the implicit definition: int foo();
1071 const char *Dummy;
1072 DeclSpec DS;
1073 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1074 Error = Error; // Silence warning.
1075 assert(!Error && "Error setting up implicit decl!");
1076 Declarator D(DS, Declarator::BlockContext);
1077 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1078 D.SetIdentifier(&II, Loc);
1079
1080 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +00001081 if (Scope *FnS = S->getFnParent())
1082 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 while (S->getParent())
1084 S = S->getParent();
1085
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001086 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +00001087}
1088
1089
Chris Lattner41af0932007-11-14 06:34:38 +00001090TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001091 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001093 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001094
1095 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +00001096 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
1097 T, LastDeclarator);
1098 if (D.getInvalidType())
1099 NewTD->setInvalidDecl();
1100 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001101}
1102
Steve Naroff08d92e42007-09-15 18:49:24 +00001103/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001104/// former case, Name will be non-null. In the later case, Name will be null.
1105/// TagType indicates what kind of tag this is. TK indicates whether this is a
1106/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001107Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001108 SourceLocation KWLoc, IdentifierInfo *Name,
1109 SourceLocation NameLoc, AttributeList *Attr) {
1110 // If this is a use of an existing tag, it must have a name.
1111 assert((Name != 0 || TK == TK_Definition) &&
1112 "Nameless record must be a definition!");
1113
1114 Decl::Kind Kind;
1115 switch (TagType) {
1116 default: assert(0 && "Unknown tag type!");
1117 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1118 case DeclSpec::TST_union: Kind = Decl::Union; break;
1119//case DeclSpec::TST_class: Kind = Decl::Class; break;
1120 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1121 }
1122
1123 // If this is a named struct, check to see if there was a previous forward
1124 // declaration or definition.
1125 if (TagDecl *PrevDecl =
1126 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1127 NameLoc, S))) {
1128
1129 // If this is a use of a previous tag, or if the tag is already declared in
1130 // the same scope (so that the definition/declaration completes or
1131 // rementions the tag), reuse the decl.
1132 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1133 // Make sure that this wasn't declared as an enum and now used as a struct
1134 // or something similar.
1135 if (PrevDecl->getKind() != Kind) {
1136 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1137 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1138 }
1139
1140 // If this is a use or a forward declaration, we're good.
1141 if (TK != TK_Definition)
1142 return PrevDecl;
1143
1144 // Diagnose attempts to redefine a tag.
1145 if (PrevDecl->isDefinition()) {
1146 Diag(NameLoc, diag::err_redefinition, Name->getName());
1147 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1148 // If this is a redefinition, recover by making this struct be
1149 // anonymous, which will make any later references get the previous
1150 // definition.
1151 Name = 0;
1152 } else {
1153 // Okay, this is definition of a previously declared or referenced tag.
1154 // Move the location of the decl to be the definition site.
1155 PrevDecl->setLocation(NameLoc);
1156 return PrevDecl;
1157 }
1158 }
1159 // If we get here, this is a definition of a new struct type in a nested
1160 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1161 // type.
1162 }
1163
1164 // If there is an identifier, use the location of the identifier as the
1165 // location of the decl, otherwise use the location of the struct/union
1166 // keyword.
1167 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1168
1169 // Otherwise, if this is the first time we've seen this tag, create the decl.
1170 TagDecl *New;
1171 switch (Kind) {
1172 default: assert(0 && "Unknown tag kind!");
1173 case Decl::Enum:
1174 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1175 // enum X { A, B, C } D; D should chain to X.
1176 New = new EnumDecl(Loc, Name, 0);
1177 // If this is an undefined enum, warn.
1178 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1179 break;
1180 case Decl::Union:
1181 case Decl::Struct:
1182 case Decl::Class:
1183 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1184 // struct X { int A; } D; D should chain to X.
1185 New = new RecordDecl(Kind, Loc, Name, 0);
1186 break;
1187 }
1188
1189 // If this has an identifier, add it to the scope stack.
1190 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001191 // The scope passed in may not be a decl scope. Zip up the scope tree until
1192 // we find one that is.
1193 while ((S->getFlags() & Scope::DeclScope) == 0)
1194 S = S->getParent();
1195
1196 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001197 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001198 Name->setFETokenInfo(New);
1199 S->AddDecl(New);
1200 }
Steve Naroff1f644322007-11-28 22:54:11 +00001201
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 return New;
1203}
1204
Steve Naroff08d92e42007-09-15 18:49:24 +00001205/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001206/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001207Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 SourceLocation DeclStart,
1209 Declarator &D, ExprTy *BitfieldWidth) {
1210 IdentifierInfo *II = D.getIdentifier();
1211 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 SourceLocation Loc = DeclStart;
1213 if (II) Loc = D.getIdentifierLoc();
1214
1215 // FIXME: Unnamed fields can be handled in various different ways, for
1216 // example, unnamed unions inject all members into the struct namespace!
1217
1218
1219 if (BitWidth) {
1220 // TODO: Validate.
1221 //printf("WARNING: BITFIELDS IGNORED!\n");
1222
1223 // 6.7.2.1p3
1224 // 6.7.2.1p4
1225
1226 } else {
1227 // Not a bitfield.
1228
1229 // validate II.
1230
1231 }
1232
1233 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001234 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1235 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001236
Reid Spencer5f016e22007-07-11 17:01:13 +00001237 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1238 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001239 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1240 Diag(Loc, diag::err_typecheck_illegal_vla,
1241 VAT->getSizeExpr()->getSourceRange());
1242 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001243 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001244 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001245 FieldDecl *NewFD;
1246
1247 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patel54e62352007-11-01 16:29:56 +00001248 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001249 else if (isa<ObjCInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1250 isa<ObjCImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
1251 isa<ObjCCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroffddd600f2007-11-14 14:15:31 +00001252 // FIXME: ivars are currently used to model properties, and
1253 // properties can appear within a protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001254 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1255 isa<ObjCProtocolDecl>(static_cast<Decl *>(TagDecl)))
1256 NewFD = new ObjCIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001257 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001258 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001259
Steve Naroff5912a352007-08-28 20:14:24 +00001260 if (D.getInvalidType() || InvalidDecl)
1261 NewFD->setInvalidDecl();
1262 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001263}
1264
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001265/// TranslateIvarVisibility - Translate visibility from a token ID to an
1266/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001267static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001268TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001269 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001270 case tok::objc_private: return ObjCIvarDecl::Private;
1271 case tok::objc_public: return ObjCIvarDecl::Public;
1272 case tok::objc_protected: return ObjCIvarDecl::Protected;
1273 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001274 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001275 }
1276}
1277
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001278void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001279 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001280 DeclTy **Fields, unsigned NumFields,
Steve Naroff60fccee2007-10-29 21:38:07 +00001281 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff08d92e42007-09-15 18:49:24 +00001282 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001283 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1284 assert(EnclosingDecl && "missing record or interface decl");
1285 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1286
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001287 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001288 // Diagnose code like:
1289 // struct S { struct S {} X; };
1290 // We discover this when we complete the outer S. Reject and ignore the
1291 // outer S.
1292 Diag(Record->getLocation(), diag::err_nested_redefinition,
1293 Record->getKindName());
1294 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001295 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 return;
1297 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 // Verify that all the fields are okay.
1299 unsigned NumNamedMembers = 0;
1300 llvm::SmallVector<FieldDecl*, 32> RecFields;
1301 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001302
Reid Spencer5f016e22007-07-11 17:01:13 +00001303 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001304
Steve Naroff74216642007-09-14 22:20:54 +00001305 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1306 assert(FD && "missing field decl");
1307
1308 // Remember all fields.
1309 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001310
1311 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001312 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001313
Steve Narofff13271f2007-09-14 23:09:53 +00001314 // If we have visibility info, make sure the AST is set accordingly.
1315 if (visibility)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001316 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001317 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001318
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001320 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001321 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001322 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001323 FD->setInvalidDecl();
1324 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001325 continue;
1326 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1328 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001329 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001330 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001331 FD->setInvalidDecl();
1332 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001333 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001334 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001335 if (i != NumFields-1 || // ... that the last member ...
1336 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001337 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001339 FD->setInvalidDecl();
1340 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 continue;
1342 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001343 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1345 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001346 FD->setInvalidDecl();
1347 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001348 continue;
1349 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001351 if (Record)
1352 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001354 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1355 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001356 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1358 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001359 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 Record->setHasFlexibleArrayMember(true);
1361 } else {
1362 // If this is a struct/class and this is not the last element, reject
1363 // it. Note that GCC supports variable sized arrays in the middle of
1364 // structures.
1365 if (i != NumFields-1) {
1366 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1367 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001368 FD->setInvalidDecl();
1369 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001370 continue;
1371 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001372 // We support flexible arrays at the end of structs in other structs
1373 // as an extension.
1374 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1375 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001376 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001377 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 }
1379 }
1380 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001381 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001382 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001383 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1384 FD->getName());
1385 FD->setInvalidDecl();
1386 EnclosingDecl->setInvalidDecl();
1387 continue;
1388 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 // Keep track of the number of named members.
1390 if (IdentifierInfo *II = FD->getIdentifier()) {
1391 // Detect duplicate member names.
1392 if (!FieldIDs.insert(II)) {
1393 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1394 // Find the previous decl.
1395 SourceLocation PrevLoc;
1396 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1397 assert(i != e && "Didn't find previous def!");
1398 if (RecFields[i]->getIdentifier() == II) {
1399 PrevLoc = RecFields[i]->getLocation();
1400 break;
1401 }
1402 }
1403 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001404 FD->setInvalidDecl();
1405 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 continue;
1407 }
1408 ++NumNamedMembers;
1409 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001410 }
1411
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 // Okay, we successfully defined 'Record'.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001413 if (Record)
1414 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001415 else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001416 ObjCIvarDecl **ClsFields =
1417 reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1418 if (isa<ObjCInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1419 cast<ObjCInterfaceDecl>(static_cast<Decl*>(RecDecl))->
Steve Naroff60fccee2007-10-29 21:38:07 +00001420 addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001421 else if (isa<ObjCImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1422 ObjCImplementationDecl* IMPDecl =
1423 cast<ObjCImplementationDecl>(static_cast<Decl*>(RecDecl));
1424 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1425 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001426 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001427 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001428 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001429}
1430
Steve Naroff08d92e42007-09-15 18:49:24 +00001431Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001432 DeclTy *lastEnumConst,
1433 SourceLocation IdLoc, IdentifierInfo *Id,
1434 SourceLocation EqualLoc, ExprTy *val) {
1435 theEnumDecl = theEnumDecl; // silence unused warning.
1436 EnumConstantDecl *LastEnumConst =
1437 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1438 Expr *Val = static_cast<Expr*>(val);
1439
Chris Lattner31e05722007-08-26 06:24:45 +00001440 // The scope passed in may not be a decl scope. Zip up the scope tree until
1441 // we find one that is.
1442 while ((S->getFlags() & Scope::DeclScope) == 0)
1443 S = S->getParent();
1444
Reid Spencer5f016e22007-07-11 17:01:13 +00001445 // Verify that there isn't already something declared with this name in this
1446 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001447 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1448 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 if (S->isDeclScope(PrevDecl)) {
1450 if (isa<EnumConstantDecl>(PrevDecl))
1451 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1452 else
1453 Diag(IdLoc, diag::err_redefinition, Id->getName());
1454 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1455 // FIXME: Don't leak memory: delete Val;
1456 return 0;
1457 }
1458 }
1459
1460 llvm::APSInt EnumVal(32);
1461 QualType EltTy;
1462 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001463 // Make sure to promote the operand type to int.
1464 UsualUnaryConversions(Val);
1465
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1467 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001468 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001469 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1470 Id->getName());
1471 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001472 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001473 } else {
1474 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001476 }
1477
1478 if (!Val) {
1479 if (LastEnumConst) {
1480 // Assign the last value + 1.
1481 EnumVal = LastEnumConst->getInitVal();
1482 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001483
1484 // Check for overflow on increment.
1485 if (EnumVal < LastEnumConst->getInitVal())
1486 Diag(IdLoc, diag::warn_enum_value_overflow);
1487
Chris Lattnerb7416f92007-08-27 17:37:24 +00001488 EltTy = LastEnumConst->getType();
1489 } else {
1490 // First value, set to zero.
1491 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001492 EnumVal.zextOrTrunc(
1493 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001494 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 }
1496
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1498 LastEnumConst);
1499
1500 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001501 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 Id->setFETokenInfo(New);
1503 S->AddDecl(New);
1504 return New;
1505}
1506
Steve Naroff08d92e42007-09-15 18:49:24 +00001507void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001508 DeclTy **Elements, unsigned NumElements) {
1509 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1510 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1511
Chris Lattnere37f0be2007-08-28 05:10:31 +00001512 // TODO: If the result value doesn't fit in an int, it must be a long or long
1513 // long value. ISO C does not support this, but GCC does as an extension,
1514 // emit a warning.
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001515 unsigned IntWidth =
1516 Context.Target.getIntWidth(Context.getFullLoc(Enum->getLocation()));
Chris Lattnere37f0be2007-08-28 05:10:31 +00001517
1518
Chris Lattnerac609682007-08-28 06:15:15 +00001519 // Verify that all the values are okay, compute the size of the values, and
1520 // reverse the list.
1521 unsigned NumNegativeBits = 0;
1522 unsigned NumPositiveBits = 0;
1523
1524 // Keep track of whether all elements have type int.
1525 bool AllElementsInt = true;
1526
Reid Spencer5f016e22007-07-11 17:01:13 +00001527 EnumConstantDecl *EltList = 0;
1528 for (unsigned i = 0; i != NumElements; ++i) {
1529 EnumConstantDecl *ECD =
1530 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1531 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001532
1533 // If the enum value doesn't fit in an int, emit an extension warning.
1534 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1535 "Should have promoted value to int");
1536 const llvm::APSInt &InitVal = ECD->getInitVal();
1537 if (InitVal.getBitWidth() > IntWidth) {
1538 llvm::APSInt V(InitVal);
1539 V.trunc(IntWidth);
1540 V.extend(InitVal.getBitWidth());
1541 if (V != InitVal)
1542 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1543 InitVal.toString());
1544 }
Chris Lattnerac609682007-08-28 06:15:15 +00001545
1546 // Keep track of the size of positive and negative values.
1547 if (InitVal.isUnsigned() || !InitVal.isNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001548 NumPositiveBits = std::max(NumPositiveBits,
1549 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001550 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001551 NumNegativeBits = std::max(NumNegativeBits,
1552 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001553
Chris Lattnerac609682007-08-28 06:15:15 +00001554 // Keep track of whether every enum element has type int (very commmon).
1555 if (AllElementsInt)
1556 AllElementsInt = ECD->getType() == Context.IntTy;
1557
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 ECD->setNextDeclarator(EltList);
1559 EltList = ECD;
1560 }
1561
Chris Lattnerac609682007-08-28 06:15:15 +00001562 // Figure out the type that should be used for this enum.
1563 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1564 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001565 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001566
1567 if (NumNegativeBits) {
1568 // If there is a negative value, figure out the smallest integer type (of
1569 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001570 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001571 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001572 BestWidth = IntWidth;
1573 } else {
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001574 BestWidth =
1575 Context.Target.getLongWidth(Context.getFullLoc(Enum->getLocation()));
1576
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001577 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001578 BestType = Context.LongTy;
1579 else {
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001580 BestWidth = Context.Target.getLongLongWidth(
1581 Context.getFullLoc(Enum->getLocation()));
1582
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001583 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001584 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1585 BestType = Context.LongLongTy;
1586 }
1587 }
1588 } else {
1589 // If there is no negative value, figure out which of uint, ulong, ulonglong
1590 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001591 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001592 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001593 BestWidth = IntWidth;
1594 } else if (NumPositiveBits <=
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001595 (BestWidth = Context.Target.getLongWidth(
1596 Context.getFullLoc(Enum->getLocation()))))
1597
Chris Lattnerac609682007-08-28 06:15:15 +00001598 BestType = Context.UnsignedLongTy;
1599 else {
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001600 BestWidth =
1601 Context.Target.getLongLongWidth(Context.getFullLoc(Enum->getLocation()));
1602
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001603 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001604 "How could an initializer get larger than ULL?");
1605 BestType = Context.UnsignedLongLongTy;
1606 }
1607 }
1608
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001609 // Loop over all of the enumerator constants, changing their types to match
1610 // the type of the enum if needed.
1611 for (unsigned i = 0; i != NumElements; ++i) {
1612 EnumConstantDecl *ECD =
1613 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1614 if (!ECD) continue; // Already issued a diagnostic.
1615
1616 // Standard C says the enumerators have int type, but we allow, as an
1617 // extension, the enumerators to be larger than int size. If each
1618 // enumerator value fits in an int, type it as an int, otherwise type it the
1619 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1620 // that X has type 'int', not 'unsigned'.
1621 if (ECD->getType() == Context.IntTy)
1622 continue; // Already int type.
1623
1624 // Determine whether the value fits into an int.
1625 llvm::APSInt InitVal = ECD->getInitVal();
1626 bool FitsInInt;
1627 if (InitVal.isUnsigned() || !InitVal.isNegative())
1628 FitsInInt = InitVal.getActiveBits() < IntWidth;
1629 else
1630 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1631
1632 // If it fits into an integer type, force it. Otherwise force it to match
1633 // the enum decl type.
1634 QualType NewTy;
1635 unsigned NewWidth;
1636 bool NewSign;
1637 if (FitsInInt) {
1638 NewTy = Context.IntTy;
1639 NewWidth = IntWidth;
1640 NewSign = true;
1641 } else if (ECD->getType() == BestType) {
1642 // Already the right type!
1643 continue;
1644 } else {
1645 NewTy = BestType;
1646 NewWidth = BestWidth;
1647 NewSign = BestType->isSignedIntegerType();
1648 }
1649
1650 // Adjust the APSInt value.
1651 InitVal.extOrTrunc(NewWidth);
1652 InitVal.setIsSigned(NewSign);
1653 ECD->setInitVal(InitVal);
1654
1655 // Adjust the Expr initializer and type.
1656 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1657 ECD->setType(NewTy);
1658 }
Chris Lattnerac609682007-08-28 06:15:15 +00001659
Chris Lattnere00b18c2007-08-28 18:24:31 +00001660 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001661}
1662
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001663Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
1664 SourceLocation LBrace,
1665 SourceLocation RBrace,
1666 const char *Lang,
1667 unsigned StrSize,
1668 DeclTy *D) {
1669 LinkageSpecDecl::LanguageIDs Language;
1670 Decl *dcl = static_cast<Decl *>(D);
1671 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1672 Language = LinkageSpecDecl::lang_c;
1673 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1674 Language = LinkageSpecDecl::lang_cxx;
1675 else {
1676 Diag(Loc, diag::err_bad_language);
1677 return 0;
1678 }
1679
1680 // FIXME: Add all the various semantics of linkage specifications
1681 return new LinkageSpecDecl(Loc, Language, dcl);
1682}
1683
Reid Spencer5f016e22007-07-11 17:01:13 +00001684void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001685 const char *attrName = rawAttr->getAttributeName()->getName();
1686 unsigned attrLen = rawAttr->getAttributeName()->getLength();
1687
Anders Carlssonabf5ad02007-12-19 17:43:24 +00001688 // Normalize the attribute name, __foo__ becomes foo.
1689 if (attrLen > 4 && attrName[0] == '_' && attrName[1] == '_' &&
1690 attrName[attrLen - 2] == '_' && attrName[attrLen - 1] == '_') {
1691 attrName += 2;
1692 attrLen -= 4;
1693 }
1694
1695 if (attrLen == 11 && !memcmp(attrName, "vector_size", 11)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1697 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1698 if (!newType.isNull()) // install the new vector type into the decl
1699 vDecl->setType(newType);
1700 }
1701 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1702 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1703 rawAttr);
1704 if (!newType.isNull()) // install the new vector type into the decl
1705 tDecl->setUnderlyingType(newType);
1706 }
Anders Carlssonabf5ad02007-12-19 17:43:24 +00001707 } else if (attrLen == 15 && !memcmp(attrName, "ocu_vector_type", 15)) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001708 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1709 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1710 else
Steve Naroff73322922007-07-18 18:00:27 +00001711 Diag(rawAttr->getAttributeLoc(),
1712 diag::err_typecheck_ocu_vector_not_typedef);
Anders Carlsson78aaae92007-12-19 07:19:40 +00001713 } else if (attrLen == 7 && !memcmp(attrName, "aligned", 7)) {
1714 HandleAlignedAttribute(New, rawAttr);
Steve Naroff73322922007-07-18 18:00:27 +00001715 }
Anders Carlsson78aaae92007-12-19 07:19:40 +00001716
Reid Spencer5f016e22007-07-11 17:01:13 +00001717 // FIXME: add other attributes...
1718}
1719
1720void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1721 AttributeList *declarator_postfix) {
1722 while (declspec_prefix) {
1723 HandleDeclAttribute(New, declspec_prefix);
1724 declspec_prefix = declspec_prefix->getNext();
1725 }
1726 while (declarator_postfix) {
1727 HandleDeclAttribute(New, declarator_postfix);
1728 declarator_postfix = declarator_postfix->getNext();
1729 }
1730}
1731
Steve Naroffbea0b342007-07-29 16:33:31 +00001732void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1733 AttributeList *rawAttr) {
1734 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00001735 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00001736 if (rawAttr->getNumArgs() != 1) {
1737 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1738 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001739 return;
Steve Naroff73322922007-07-18 18:00:27 +00001740 }
1741 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1742 llvm::APSInt vecSize(32);
1743 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1744 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1745 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001746 return;
Steve Naroff73322922007-07-18 18:00:27 +00001747 }
1748 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1749 // in conjunction with complex types (pointers, arrays, functions, etc.).
1750 Type *canonType = curType.getCanonicalType().getTypePtr();
1751 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1752 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1753 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001754 return;
Steve Naroff73322922007-07-18 18:00:27 +00001755 }
1756 // unlike gcc's vector_size attribute, the size is specified as the
1757 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001758 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001759
1760 if (vectorSize == 0) {
1761 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1762 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001763 return;
Steve Naroff73322922007-07-18 18:00:27 +00001764 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001765 // Instantiate/Install the vector type, the number of elements is > 0.
1766 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1767 // Remember this typedef decl, we will need it later for diagnostics.
1768 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001769}
1770
Reid Spencer5f016e22007-07-11 17:01:13 +00001771QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001772 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001773 // check the attribute arugments.
1774 if (rawAttr->getNumArgs() != 1) {
1775 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1776 std::string("1"));
1777 return QualType();
1778 }
1779 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1780 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001781 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001782 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1783 sizeExpr->getSourceRange());
1784 return QualType();
1785 }
1786 // navigate to the base type - we need to provide for vector pointers,
1787 // vector arrays, and functions returning vectors.
1788 Type *canonType = curType.getCanonicalType().getTypePtr();
1789
Steve Naroff73322922007-07-18 18:00:27 +00001790 if (canonType->isPointerType() || canonType->isArrayType() ||
1791 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00001792 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00001793 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1794 do {
1795 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1796 canonType = PT->getPointeeType().getTypePtr();
1797 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1798 canonType = AT->getElementType().getTypePtr();
1799 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1800 canonType = FT->getResultType().getTypePtr();
1801 } while (canonType->isPointerType() || canonType->isArrayType() ||
1802 canonType->isFunctionType());
1803 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001804 }
1805 // the base type must be integer or float.
1806 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1807 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1808 curType.getCanonicalType().getAsString());
1809 return QualType();
1810 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00001811 unsigned typeSize = static_cast<unsigned>(
1812 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001813 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001814 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00001815
1816 // the vector size needs to be an integral multiple of the type size.
1817 if (vectorSize % typeSize) {
1818 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1819 sizeExpr->getSourceRange());
1820 return QualType();
1821 }
1822 if (vectorSize == 0) {
1823 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1824 sizeExpr->getSourceRange());
1825 return QualType();
1826 }
1827 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1828 // the number of elements to be a power of two (unlike GCC).
1829 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00001830 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001831}
1832
Anders Carlsson78aaae92007-12-19 07:19:40 +00001833void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
1834{
1835 // check the attribute arguments.
Anders Carlssonabf5ad02007-12-19 17:43:24 +00001836 // FIXME: Handle the case where are no arguments.
Anders Carlsson78aaae92007-12-19 07:19:40 +00001837 if (rawAttr->getNumArgs() != 1) {
1838 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1839 std::string("1"));
1840 return;
1841 }
1842
1843 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
1844 llvm::APSInt alignment(32);
1845 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
1846 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1847 alignmentExpr->getSourceRange());
1848 return;
1849 }
1850}