blob: c2c66a20152a0df24b900e54c85c054be047d29b [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Builtins.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/Type.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/TargetInfo.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000024#include "llvm/ADT/SmallString.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian67907bd2007-10-05 18:00:57 +000026#include "llvm/ADT/DenseSet.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Chris Lattner4b009652007-07-25 00:24:17 +000029Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000030 Decl *IIDecl = II.getFETokenInfo<Decl>();
31 // Find first occurance of none-tagged declaration
32 while(IIDecl && IIDecl->getIdentifierNamespace() != Decl::IDNS_Ordinary)
33 IIDecl = cast<ScopedDecl>(IIDecl)->getNext();
34 if (!IIDecl)
35 return 0;
Ted Kremenek42730c52008-01-07 19:49:32 +000036 if (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000037 return IIDecl;
Ted Kremenek42730c52008-01-07 19:49:32 +000038 if (ObjCCompatibleAliasDecl *ADecl =
39 dyn_cast<ObjCCompatibleAliasDecl>(IIDecl))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000040 return ADecl->getClassInterface();
Steve Naroff81f1bba2007-09-06 21:24:23 +000041 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000042}
43
Steve Naroff9637a9b2007-10-09 22:01:59 +000044void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000045 if (S->decl_empty()) return;
46 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
47
Chris Lattner4b009652007-07-25 00:24:17 +000048 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
49 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +000050 Decl *TmpD = static_cast<Decl*>(*I);
51 assert(TmpD && "This decl didn't get pushed??");
52 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
53 assert(D && "This decl isn't a ScopedDecl?");
54
Chris Lattner4b009652007-07-25 00:24:17 +000055 IdentifierInfo *II = D->getIdentifier();
56 if (!II) continue;
57
58 // Unlink this decl from the identifier. Because the scope contains decls
59 // in an unordered collection, and because we have multiple identifier
60 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
61 if (II->getFETokenInfo<Decl>() == D) {
62 // Normal case, no multiple decls in different namespaces.
63 II->setFETokenInfo(D->getNext());
64 } else {
65 // Scan ahead. There are only three namespaces in C, so this loop can
66 // never execute more than 3 times.
Steve Naroffd21bc0d2007-09-13 18:10:37 +000067 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Chris Lattner4b009652007-07-25 00:24:17 +000068 while (SomeDecl->getNext() != D) {
69 SomeDecl = SomeDecl->getNext();
70 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
71 }
72 SomeDecl->setNext(D->getNext());
73 }
74
75 // This will have to be revisited for C++: there we want to nest stuff in
76 // namespace decls etc. Even for C, we might want a top-level translation
77 // unit decl or something.
78 if (!CurFunctionDecl)
79 continue;
80
81 // Chain this decl to the containing function, it now owns the memory for
82 // the decl.
83 D->setNext(CurFunctionDecl->getDeclChain());
84 CurFunctionDecl->setDeclChain(D);
85 }
86}
87
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +000088/// LookupInterfaceDecl - Lookup interface declaration in the scope chain.
89/// Return the first declaration found (which may or may not be a class
Fariborz Jahanian8eaeff52007-10-12 19:53:08 +000090/// declaration. Caller is responsible for handling the none-class case.
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +000091/// Bypassing the alias of a class by returning the aliased class.
92ScopedDecl *Sema::LookupInterfaceDecl(IdentifierInfo *ClassName) {
93 ScopedDecl *IDecl;
94 // Scan up the scope chain looking for a decl that matches this identifier
95 // that is in the appropriate namespace.
96 for (IDecl = ClassName->getFETokenInfo<ScopedDecl>(); IDecl;
97 IDecl = IDecl->getNext())
98 if (IDecl->getIdentifierNamespace() == Decl::IDNS_Ordinary)
99 break;
100
Ted Kremenek42730c52008-01-07 19:49:32 +0000101 if (ObjCCompatibleAliasDecl *ADecl =
102 dyn_cast_or_null<ObjCCompatibleAliasDecl>(IDecl))
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000103 return ADecl->getClassInterface();
104 return IDecl;
105}
106
Ted Kremenek42730c52008-01-07 19:49:32 +0000107/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +0000108/// return 0 if one not found.
Ted Kremenek42730c52008-01-07 19:49:32 +0000109ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000110 ScopedDecl *IdDecl = LookupInterfaceDecl(Id);
Ted Kremenek42730c52008-01-07 19:49:32 +0000111 return cast_or_null<ObjCInterfaceDecl>(IdDecl);
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +0000112}
113
Chris Lattner4b009652007-07-25 00:24:17 +0000114/// LookupScopedDecl - Look up the inner-most declaration in the specified
115/// namespace.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000116ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
117 SourceLocation IdLoc, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000118 if (II == 0) return 0;
119 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
120
121 // Scan up the scope chain looking for a decl that matches this identifier
122 // that is in the appropriate namespace. This search should not take long, as
123 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000124 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner4b009652007-07-25 00:24:17 +0000125 if (D->getIdentifierNamespace() == NS)
126 return D;
127
128 // If we didn't find a use of this identifier, and if the identifier
129 // corresponds to a compiler builtin, create the decl object for the builtin
130 // now, injecting it into translation unit scope, and return it.
131 if (NS == Decl::IDNS_Ordinary) {
132 // If this is a builtin on some other target, or if this builtin varies
133 // across targets (e.g. in type), emit a diagnostic and mark the translation
134 // unit non-portable for using it.
135 if (II->isNonPortableBuiltin()) {
136 // Only emit this diagnostic once for this builtin.
137 II->setNonPortableBuiltin(false);
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000138 Context.Target.DiagnoseNonPortability(Context.getFullLoc(IdLoc),
Chris Lattner4b009652007-07-25 00:24:17 +0000139 diag::port_target_builtin_use);
140 }
141 // If this is a builtin on this (or all) targets, create the decl.
142 if (unsigned BuiltinID = II->getBuiltinID())
143 return LazilyCreateBuiltin(II, BuiltinID, S);
144 }
145 return 0;
146}
147
Anders Carlsson36760332007-10-15 20:28:48 +0000148void Sema::InitBuiltinVaListType()
149{
150 if (!Context.getBuiltinVaListType().isNull())
151 return;
152
153 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
154 ScopedDecl *VaDecl = LookupScopedDecl(VaIdent, Decl::IDNS_Ordinary,
155 SourceLocation(), TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000156 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000157 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
158}
159
Chris Lattner4b009652007-07-25 00:24:17 +0000160/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
161/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000162ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
163 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000164 Builtin::ID BID = (Builtin::ID)bid;
165
Anders Carlsson36760332007-10-15 20:28:48 +0000166 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000167 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson36760332007-10-15 20:28:48 +0000168 BID == Builtin::BI__builtin_va_end)
169 InitBuiltinVaListType();
170
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000171 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner4b009652007-07-25 00:24:17 +0000172 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner987058a2007-08-26 04:02:13 +0000173 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000174
175 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000176 if (Scope *FnS = S->getFnParent())
177 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000178 while (S->getParent())
179 S = S->getParent();
180 S->AddDecl(New);
181
182 // Add this decl to the end of the identifier info.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000183 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000184 // Scan until we find the last (outermost) decl in the id chain.
185 while (LastDecl->getNext())
186 LastDecl = LastDecl->getNext();
187 // Insert before (outside) it.
188 LastDecl->setNext(New);
189 } else {
190 II->setFETokenInfo(New);
191 }
Chris Lattner4b009652007-07-25 00:24:17 +0000192 return New;
193}
194
195/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
196/// and scope as a previous declaration 'Old'. Figure out how to resolve this
197/// situation, merging decls or emitting diagnostics as appropriate.
198///
Steve Naroffcb597472007-09-13 21:41:19 +0000199TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000200 // Verify the old decl was also a typedef.
201 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
202 if (!Old) {
203 Diag(New->getLocation(), diag::err_redefinition_different_kind,
204 New->getName());
205 Diag(OldD->getLocation(), diag::err_previous_definition);
206 return New;
207 }
208
Steve Naroffae84af82007-10-31 18:42:27 +0000209 // Allow multiple definitions for ObjC built-in typedefs.
210 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek42730c52008-01-07 19:49:32 +0000211 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroffae84af82007-10-31 18:42:27 +0000212 return Old;
213
Chris Lattner4b009652007-07-25 00:24:17 +0000214 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
215 // TODO: This is totally simplistic. It should handle merging functions
216 // together etc, merging extern int X; int X; ...
217 Diag(New->getLocation(), diag::err_redefinition, New->getName());
218 Diag(Old->getLocation(), diag::err_previous_definition);
219 return New;
220}
221
222/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
223/// and scope as a previous declaration 'Old'. Figure out how to resolve this
224/// situation, merging decls or emitting diagnostics as appropriate.
225///
Steve Naroffcb597472007-09-13 21:41:19 +0000226FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000227 // Verify the old decl was also a function.
228 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
229 if (!Old) {
230 Diag(New->getLocation(), diag::err_redefinition_different_kind,
231 New->getName());
232 Diag(OldD->getLocation(), diag::err_previous_definition);
233 return New;
234 }
235
Chris Lattner60476ff2007-11-20 19:04:50 +0000236 QualType OldQType = Old->getCanonicalType();
237 QualType NewQType = New->getCanonicalType();
238
239 // This is not right, but it's a start.
240 // If Old is a function prototype with no defined arguments we only compare
241 // the return type; If arguments are defined on the prototype we validate the
242 // entire function type.
243 // FIXME: We should link up decl objects here.
244 if (Old->getBody() == 0) {
245 if (OldQType.getTypePtr()->getTypeClass() == Type::FunctionNoProto &&
246 Old->getResultType() == New->getResultType())
247 return New;
Chris Lattner4b009652007-07-25 00:24:17 +0000248 }
Steve Naroff1d5bd642008-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 Lattner1470b072007-11-06 06:07:26 +0000253
Steve Naroff6c9e7922008-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
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroff6c9e7922008-01-16 15:01:34 +0000262 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
263 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000264 return New;
265}
266
Chris Lattnerf9167d12007-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
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffcb597472007-09-13 21:41:19 +0000313VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroff83c13012007-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 }
Chris Lattner4b009652007-07-25 00:24:17 +0000333 // Verify the types match.
Chris Lattnerf9167d12007-11-06 04:28:31 +0000334 if (Old->getCanonicalType() != New->getCanonicalType() &&
335 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffedafc0b2007-11-17 21:37:36 +0000355 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000356}
357
Steve Narofff0b23542008-01-10 22:15:12 +0000358bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000359 // Get the type before calling CheckSingleAssignmentConstraints(), since
360 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000361 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000362
Chris Lattner005ed752008-01-04 18:04:52 +0000363 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
364 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
365 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000366}
367
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000368bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Narofff0b23542008-01-10 22:15:12 +0000369 QualType ElementType) {
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000370 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Narofff0b23542008-01-10 22:15:12 +0000371 if (CheckSingleInitializer(expr, ElementType))
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000372 return true; // types weren't compatible.
373
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000374 if (savExpr != expr) // The type was promoted, update initializer list.
375 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000376 return false;
377}
378
379void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
Steve Narofff0b23542008-01-10 22:15:12 +0000380 QualType ElementType,
Steve Naroff509d0b52007-09-04 02:20:04 +0000381 int &nInitializers, bool &hadError) {
Steve Naroffcb69fb72007-12-10 22:44:33 +0000382 unsigned numInits = IList->getNumInits();
383
384 if (numInits) {
385 if (CheckForCharArrayInitializer(IList, ElementType, nInitializers,
386 false, hadError))
387 return;
388
389 for (unsigned i = 0; i < numInits; i++) {
390 Expr *expr = IList->getInit(i);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000391
Steve Naroffcb69fb72007-12-10 22:44:33 +0000392 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
393 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
394 int maxElements = CAT->getMaximumElements();
Steve Narofff0b23542008-01-10 22:15:12 +0000395 CheckConstantInitList(DeclType, InitList, ElementType,
Steve Naroffcb69fb72007-12-10 22:44:33 +0000396 maxElements, hadError);
397 }
398 } else {
Steve Narofff0b23542008-01-10 22:15:12 +0000399 hadError = CheckInitExpr(expr, IList, i, ElementType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000400 }
401 nInitializers++;
402 }
403 } else {
404 Diag(IList->getLocStart(),
405 diag::err_at_least_one_initializer_needed_to_size_array);
406 hadError = true;
407 }
408}
409
410bool Sema::CheckForCharArrayInitializer(InitListExpr *IList,
411 QualType ElementType,
412 int &nInitializers, bool isConstant,
413 bool &hadError)
414{
415 if (ElementType->isPointerType())
416 return false;
417
418 if (StringLiteral *literal = dyn_cast<StringLiteral>(IList->getInit(0))) {
419 // FIXME: Handle wide strings
420 if (ElementType->isCharType()) {
421 if (isConstant) {
422 if (literal->getByteLength() > (unsigned)nInitializers) {
423 Diag(literal->getSourceRange().getBegin(),
424 diag::warn_initializer_string_for_char_array_too_long,
425 literal->getSourceRange());
426 }
427 } else {
428 nInitializers = literal->getByteLength() + 1;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000429 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000430 } else {
Steve Naroffcb69fb72007-12-10 22:44:33 +0000431 // FIXME: It might be better if we could point to the declaration
432 // here, instead of the string literal.
433 Diag(literal->getSourceRange().getBegin(),
434 diag::array_of_wrong_type_initialized_from_string,
435 ElementType.getAsString());
436 hadError = true;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000437 }
Steve Naroffcb69fb72007-12-10 22:44:33 +0000438
439 // Check for excess initializers
440 for (unsigned i = 1; i < IList->getNumInits(); i++) {
441 Expr *expr = IList->getInit(i);
442 Diag(expr->getLocStart(),
443 diag::err_excess_initializers_in_char_array_initializer,
444 expr->getSourceRange());
445 }
446
447 return true;
Steve Naroff509d0b52007-09-04 02:20:04 +0000448 }
Steve Naroffcb69fb72007-12-10 22:44:33 +0000449
450 return false;
Steve Naroff509d0b52007-09-04 02:20:04 +0000451}
452
453// FIXME: Doesn't deal with arrays of structures yet.
454void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
Steve Narofff0b23542008-01-10 22:15:12 +0000455 QualType ElementType,
Steve Naroff509d0b52007-09-04 02:20:04 +0000456 int &totalInits, bool &hadError) {
457 int maxElementsAtThisLevel = 0;
458 int nInitsAtLevel = 0;
459
Steve Naroff4a4b2062007-12-07 21:12:53 +0000460 if (ElementType->isRecordType()) // FIXME: until we support structures...
461 return;
462
Steve Naroff509d0b52007-09-04 02:20:04 +0000463 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
464 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff4f910992007-09-04 21:13:33 +0000465 maxElementsAtThisLevel = CAT->getMaximumElements();
466 // Set DeclType, used below to recurse (for multi-dimensional arrays).
467 DeclType = CAT->getElementType();
Steve Naroff509d0b52007-09-04 02:20:04 +0000468 } else if (DeclType->isScalarType()) {
Anders Carlsson9864a512007-12-03 01:01:28 +0000469 if (const VectorType *VT = DeclType->getAsVectorType())
470 maxElementsAtThisLevel = VT->getNumElements();
471 else {
472 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
473 IList->getSourceRange());
474 maxElementsAtThisLevel = 1;
475 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000476 }
477 // The empty init list "{ }" is treated specially below.
478 unsigned numInits = IList->getNumInits();
479 if (numInits) {
Steve Naroffcb69fb72007-12-10 22:44:33 +0000480 if (CheckForCharArrayInitializer(IList, ElementType,
481 maxElementsAtThisLevel,
482 true, hadError))
483 return;
484
Steve Naroff509d0b52007-09-04 02:20:04 +0000485 for (unsigned i = 0; i < numInits; i++) {
486 Expr *expr = IList->getInit(i);
487
488 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
Steve Narofff0b23542008-01-10 22:15:12 +0000489 CheckConstantInitList(DeclType, InitList, ElementType,
Steve Naroff509d0b52007-09-04 02:20:04 +0000490 totalInits, hadError);
491 } else {
Steve Narofff0b23542008-01-10 22:15:12 +0000492 hadError = CheckInitExpr(expr, IList, i, ElementType);
Steve Naroff509d0b52007-09-04 02:20:04 +0000493 nInitsAtLevel++; // increment the number of initializers at this level.
494 totalInits--; // decrement the total number of initializers.
495
496 // Check if we have space for another initializer.
Anders Carlsson463f7ce2007-12-05 04:57:06 +0000497 if (((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0)))
Steve Naroff509d0b52007-09-04 02:20:04 +0000498 Diag(expr->getLocStart(), diag::warn_excess_initializers,
499 expr->getSourceRange());
500 }
501 }
502 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
503 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
504 } else {
505 // we have an initializer list with no elements.
506 totalInits -= maxElementsAtThisLevel;
507 if (totalInits < 0)
508 Diag(IList->getLocStart(), diag::warn_excess_initializers,
509 IList->getSourceRange());
Steve Naroff9091f3f2007-09-02 15:34:30 +0000510 }
Steve Naroff9091f3f2007-09-02 15:34:30 +0000511}
512
Steve Narofff0b23542008-01-10 22:15:12 +0000513bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffcb69fb72007-12-10 22:44:33 +0000514 bool hadError = false;
Anders Carlsson855d78d2007-10-17 00:52:43 +0000515
Steve Naroffcb69fb72007-12-10 22:44:33 +0000516 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
517 if (!InitList) {
518 if (StringLiteral *strLiteral = dyn_cast<StringLiteral>(Init)) {
519 const VariableArrayType *VAT = DeclType->getAsVariableArrayType();
520 // FIXME: Handle wide strings
521 if (VAT && VAT->getElementType()->isCharType()) {
522 // C99 6.7.8p14. We have an array of character type with unknown size
523 // being initialized to a string literal.
524 llvm::APSInt ConstVal(32);
525 ConstVal = strLiteral->getByteLength() + 1;
526 // Return a new array type (C99 6.7.8p22).
527 DeclType = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
528 ArrayType::Normal, 0);
Steve Naroff6a2c3802007-12-11 00:00:01 +0000529 // set type from "char *" to "constant array of char".
530 strLiteral->setType(DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000531 return hadError;
532 }
533 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
534 if (CAT && CAT->getElementType()->isCharType()) {
535 // C99 6.7.8p14. We have an array of character type with known size.
536 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements()) {
537 Diag(strLiteral->getSourceRange().getBegin(),
538 diag::warn_initializer_string_for_char_array_too_long,
539 strLiteral->getSourceRange());
540 }
Steve Naroff6a2c3802007-12-11 00:00:01 +0000541 // set type from "char *" to "constant array of char".
542 strLiteral->setType(DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000543 return hadError;
544 }
545 }
Steve Narofff0b23542008-01-10 22:15:12 +0000546 return CheckSingleInitializer(Init, DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000547 }
Steve Naroffe14e5542007-09-02 02:04:30 +0000548 // We have an InitListExpr, make sure we set the type.
549 Init->setType(DeclType);
Steve Naroff1c9de712007-09-03 01:24:23 +0000550
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000551 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
552 // of unknown size ("[]") or an object type that is not a variable array type.
553 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
Chris Lattner6df93592007-12-18 07:02:56 +0000554 if (const Expr *expr = VAT->getSizeExpr())
Steve Naroff1c9de712007-09-03 01:24:23 +0000555 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
556 expr->getSourceRange());
557
Steve Naroff4f910992007-09-04 21:13:33 +0000558 // We have a VariableArrayType with unknown size. Note that only the first
559 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff509d0b52007-09-04 02:20:04 +0000560 int numInits = 0;
Steve Naroff4f910992007-09-04 21:13:33 +0000561 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
Steve Narofff0b23542008-01-10 22:15:12 +0000562 numInits, hadError);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000563 llvm::APSInt ConstVal(32);
564
565 if (!hadError)
Steve Naroff509d0b52007-09-04 02:20:04 +0000566 ConstVal = numInits;
Steve Naroffcb69fb72007-12-10 22:44:33 +0000567
568 // Return a new array type from the number of initializers (C99 6.7.8p22).
569
570 // Note that if there was an error, we will still set the decl type,
571 // to an array type with 0 elements.
572 // This is to avoid "incomplete type foo[]" errors when we've already
573 // reported the real cause of the error.
574 DeclType = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
575 ArrayType::Normal, 0);
Steve Naroff1c9de712007-09-03 01:24:23 +0000576 return hadError;
577 }
578 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000579 int maxElements = CAT->getMaximumElements();
580 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
Steve Narofff0b23542008-01-10 22:15:12 +0000581 maxElements, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000582 return hadError;
583 }
Anders Carlsson9864a512007-12-03 01:01:28 +0000584 if (const VectorType *VT = DeclType->getAsVectorType()) {
585 int maxElements = VT->getNumElements();
586 CheckConstantInitList(DeclType, InitList, VT->getElementType(),
Steve Narofff0b23542008-01-10 22:15:12 +0000587 maxElements, hadError);
Anders Carlsson9864a512007-12-03 01:01:28 +0000588 return hadError;
589 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000590 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
591 int maxElements = 1;
Steve Narofff0b23542008-01-10 22:15:12 +0000592 CheckConstantInitList(DeclType, InitList, DeclType, maxElements, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000593 return hadError;
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000594 }
Steve Naroffc7c66532007-12-05 04:00:10 +0000595 // FIXME: Handle struct/union types, including those appearing in a
596 // CompoundLiteralExpr...
Steve Naroff1c9de712007-09-03 01:24:23 +0000597 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +0000598}
599
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000600Sema::DeclTy *
Steve Naroff0acc9c92007-09-15 18:49:24 +0000601Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000602 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000603 IdentifierInfo *II = D.getIdentifier();
604
605 // All of these full declarators require an identifier. If it doesn't have
606 // one, the ParsedFreeStandingDeclSpec action should be used.
607 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000608 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000609 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000610 D.getDeclSpec().getSourceRange(), D.getSourceRange());
611 return 0;
612 }
613
Chris Lattnera7549902007-08-26 06:24:45 +0000614 // The scope passed in may not be a decl scope. Zip up the scope tree until
615 // we find one that is.
616 while ((S->getFlags() & Scope::DeclScope) == 0)
617 S = S->getParent();
618
Chris Lattner4b009652007-07-25 00:24:17 +0000619 // See if this is a redefinition of a variable in the same scope.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000620 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
621 D.getIdentifierLoc(), S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000622 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000623 bool InvalidDecl = false;
624
Chris Lattner82bb4792007-11-14 06:34:38 +0000625 QualType R = GetTypeForDeclarator(D, S);
626 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
627
Chris Lattner4b009652007-07-25 00:24:17 +0000628 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner82bb4792007-11-14 06:34:38 +0000629 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000630 if (!NewTD) return 0;
631
632 // Handle attributes prior to checking for duplicates in MergeVarDecl
633 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
634 D.getAttributes());
Steve Narofff8a09432008-01-09 23:34:55 +0000635 // Merge the decl with the existing one if appropriate. If the decl is
636 // in an outer scope, it isn't the same thing.
637 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000638 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
639 if (NewTD == 0) return 0;
640 }
641 New = NewTD;
642 if (S->getParent() == 0) {
643 // C99 6.7.7p2: If a typedef name specifies a variably modified type
644 // then it shall have block scope.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000645 if (const VariableArrayType *VAT =
646 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
647 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
648 VAT->getSizeExpr()->getSourceRange());
649 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000650 }
651 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000652 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000653 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000654 switch (D.getDeclSpec().getStorageClassSpec()) {
655 default: assert(0 && "Unknown storage class!");
656 case DeclSpec::SCS_auto:
657 case DeclSpec::SCS_register:
658 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
659 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000660 InvalidDecl = true;
661 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000662 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
663 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
664 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
665 }
666
667 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000668 D.getDeclSpec().isInlineSpecified(),
Nate Begeman84079d72007-11-13 22:14:47 +0000669 LastDeclarator,
670 D.getDeclSpec().getAttributes());
671
672 // Transfer ownership of DeclSpec attributes to FunctionDecl
673 D.getDeclSpec().clearAttributes();
Chris Lattner4b009652007-07-25 00:24:17 +0000674
Steve Narofff8a09432008-01-09 23:34:55 +0000675 // Merge the decl with the existing one if appropriate. Since C functions
676 // are in a flat namespace, make sure we consider decls in outer scopes.
Chris Lattner4b009652007-07-25 00:24:17 +0000677 if (PrevDecl) {
678 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
679 if (NewFD == 0) return 0;
680 }
681 New = NewFD;
682 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +0000683 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000684 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
685 D.getIdentifier()->getName());
686 InvalidDecl = true;
687 }
Chris Lattner4b009652007-07-25 00:24:17 +0000688
689 VarDecl *NewVD;
690 VarDecl::StorageClass SC;
691 switch (D.getDeclSpec().getStorageClassSpec()) {
692 default: assert(0 && "Unknown storage class!");
693 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
694 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
695 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
696 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
697 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
698 }
699 if (S->getParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000700 // C99 6.9p2: The storage-class specifiers auto and register shall not
701 // appear in the declaration specifiers in an external declaration.
702 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
703 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
704 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000705 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000706 }
Chris Lattner4b009652007-07-25 00:24:17 +0000707 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000708 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000709 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000710 }
Chris Lattner4b009652007-07-25 00:24:17 +0000711 // Handle attributes prior to checking for duplicates in MergeVarDecl
712 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
713 D.getAttributes());
714
Steve Narofff8a09432008-01-09 23:34:55 +0000715 // Merge the decl with the existing one if appropriate. If the decl is
716 // in an outer scope, it isn't the same thing.
717 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000718 NewVD = MergeVarDecl(NewVD, PrevDecl);
719 if (NewVD == 0) return 0;
720 }
Chris Lattner4b009652007-07-25 00:24:17 +0000721 New = NewVD;
722 }
723
724 // If this has an identifier, add it to the scope stack.
725 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000726 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000727 II->setFETokenInfo(New);
728 S->AddDecl(New);
729 }
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000730 // If any semantic error occurred, mark the decl as invalid.
731 if (D.getInvalidType() || InvalidDecl)
732 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000733
734 return New;
735}
736
Steve Narofff0b23542008-01-10 22:15:12 +0000737bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
738 SourceLocation loc;
739 // FIXME: Remove the isReference check and handle assignment to a reference.
740 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
741 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
742 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
743 return true;
744 }
745 return false;
746}
747
Steve Naroff6a0e2092007-09-12 14:07:44 +0000748void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000749 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000750 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +0000751 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +0000752
Chris Lattnerf31a2fb2007-10-19 20:10:30 +0000753 // If there is no declaration, there was an error parsing it. Just ignore
754 // the initializer.
755 if (RealDecl == 0) {
756 delete Init;
757 return;
758 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000759
Steve Naroff420d0f52007-09-12 20:13:48 +0000760 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
761 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +0000762 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
763 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +0000764 RealDecl->setInvalidDecl();
765 return;
766 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000767 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +0000768 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +0000769 QualType DclT = VDecl->getType(), SavT = DclT;
770 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000771 VarDecl::StorageClass SC = BVD->getStorageClass();
772 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +0000773 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000774 BVD->setInvalidDecl();
775 } else if (!BVD->isInvalidDecl()) {
Steve Narofff0b23542008-01-10 22:15:12 +0000776 CheckInitializerTypes(Init, DclT);
777 if (SC == VarDecl::Static) // C99 6.7.8p4.
778 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000779 }
Steve Naroff420d0f52007-09-12 20:13:48 +0000780 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000781 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +0000782 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000783 if (!FVD->isInvalidDecl())
Steve Narofff0b23542008-01-10 22:15:12 +0000784 CheckInitializerTypes(Init, DclT);
785
786 // C99 6.7.8p4. All file scoped initializers need to be constant.
787 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000788 }
789 // If the type changed, it means we had an incomplete type that was
790 // completed by the initializer. For example:
791 // int ary[] = { 1, 3, 5 };
792 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +0000793 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000794 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +0000795 Init->setType(DclT);
796 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000797
798 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +0000799 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000800 return;
801}
802
Chris Lattner4b009652007-07-25 00:24:17 +0000803/// The declarators are chained together backwards, reverse the list.
804Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
805 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000806 Decl *GroupDecl = static_cast<Decl*>(group);
807 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +0000808 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +0000809
810 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
811 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000812 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000813 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000814 else { // reverse the list.
815 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000816 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +0000817 Group->setNextDeclarator(NewGroup);
818 NewGroup = Group;
819 Group = Next;
820 }
821 }
822 // Perform semantic analysis that depends on having fully processed both
823 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000824 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000825 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
826 if (!IDecl)
827 continue;
828 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
829 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
830 QualType T = IDecl->getType();
831
832 // C99 6.7.5.2p2: If an identifier is declared to be an object with
833 // static storage duration, it shall not have a variable length array.
834 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
835 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
836 if (VLA->getSizeExpr()) {
837 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
838 IDecl->setInvalidDecl();
839 }
840 }
841 }
842 // Block scope. C99 6.7p7: If an identifier for an object is declared with
843 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
844 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
845 if (T->isIncompleteType()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +0000846 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
847 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +0000848 IDecl->setInvalidDecl();
849 }
850 }
851 // File scope. C99 6.9.2p2: A declaration of an identifier for and
852 // object that has file scope without an initializer, and without a
853 // storage-class specifier or with the storage-class specifier "static",
854 // constitutes a tentative definition. Note: A tentative definition with
855 // external linkage is valid (C99 6.2.2p5).
Steve Narofffef2f052008-01-18 00:39:39 +0000856 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
857 FVD->getStorageClass() == VarDecl::None)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000858 // C99 6.9.2p3: If the declaration of an identifier for an object is
859 // a tentative definition and has internal linkage (C99 6.2.2p3), the
860 // declared type shall not be an incomplete type.
861 if (T->isIncompleteType()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +0000862 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
863 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +0000864 IDecl->setInvalidDecl();
865 }
866 }
Chris Lattner4b009652007-07-25 00:24:17 +0000867 }
868 return NewGroup;
869}
Steve Naroff91b03f72007-08-28 03:03:08 +0000870
871// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000872ParmVarDecl *
Nate Begeman2240f542007-11-13 21:49:48 +0000873Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI, Scope *FnScope)
Steve Naroff434fa8d2007-11-12 03:44:46 +0000874{
Chris Lattner4b009652007-07-25 00:24:17 +0000875 IdentifierInfo *II = PI.Ident;
876 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
877 // Can this happen for params? We already checked that they don't conflict
878 // among each other. Here they can only shadow globals, which is ok.
879 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
880 PI.IdentLoc, FnScope)) {
881
882 }
883
884 // FIXME: Handle storage class (auto, register). No declarator?
885 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000886
887 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
888 // Doing the promotion here has a win and a loss. The win is the type for
889 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
890 // code generator). The loss is the orginal type isn't preserved. For example:
891 //
892 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
893 // int blockvardecl[5];
894 // sizeof(parmvardecl); // size == 4
895 // sizeof(blockvardecl); // size == 20
896 // }
897 //
898 // For expressions, all implicit conversions are captured using the
899 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
900 //
901 // FIXME: If a source translation tool needs to see the original type, then
902 // we need to consider storing both types (in ParmVarDecl)...
903 //
904 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattnerc08564a2008-01-02 22:50:48 +0000905 if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
906 // int x[restrict 4] -> int *restrict
Steve Naroff94cd93f2007-08-07 22:44:21 +0000907 parmDeclType = Context.getPointerType(AT->getElementType());
Chris Lattnerc08564a2008-01-02 22:50:48 +0000908 parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
909 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +0000910 parmDeclType = Context.getPointerType(parmDeclType);
911
912 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Nate Begeman84079d72007-11-13 22:14:47 +0000913 VarDecl::None, 0, PI.AttrList);
Steve Naroffcae537d2007-08-28 18:45:29 +0000914 if (PI.InvalidType)
915 New->setInvalidDecl();
916
Chris Lattner4b009652007-07-25 00:24:17 +0000917 // If this has an identifier, add it to the scope stack.
918 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000919 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000920 II->setFETokenInfo(New);
921 FnScope->AddDecl(New);
922 }
923
924 return New;
925}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000926
Chris Lattnerea148702007-10-09 17:14:05 +0000927Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000928 assert(CurFunctionDecl == 0 && "Function parsing confused");
929 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
930 "Not a function declarator!");
931 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
932
933 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
934 // for a K&R function.
935 if (!FTI.hasPrototype) {
936 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
937 if (FTI.ArgInfo[i].TypeInfo == 0) {
938 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
939 FTI.ArgInfo[i].Ident->getName());
940 // Implicitly declare the argument as type 'int' for lack of a better
941 // type.
942 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
943 }
944 }
945
946 // Since this is a function definition, act as though we have information
947 // about the arguments.
948 FTI.hasPrototype = true;
949 } else {
950 // FIXME: Diagnose arguments without names in C.
951
952 }
953
954 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +0000955
956 // See if this is a redefinition.
957 ScopedDecl *PrevDcl = LookupScopedDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
958 D.getIdentifierLoc(), GlobalScope);
959 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
960 if (FD->getBody()) {
961 Diag(D.getIdentifierLoc(), diag::err_redefinition,
962 D.getIdentifier()->getName());
963 Diag(FD->getLocation(), diag::err_previous_definition);
964 }
965 }
Chris Lattner4b009652007-07-25 00:24:17 +0000966 FunctionDecl *FD =
Steve Naroff0acc9c92007-09-15 18:49:24 +0000967 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Steve Naroff1d5bd642008-01-14 20:51:29 +0000968 assert(FD != 0 && "ActOnDeclarator() didn't return a FunctionDecl");
Chris Lattner4b009652007-07-25 00:24:17 +0000969 CurFunctionDecl = FD;
970
971 // Create Decl objects for each parameter, adding them to the FunctionDecl.
972 llvm::SmallVector<ParmVarDecl*, 16> Params;
973
974 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
975 // no arguments, not a function that takes a single void argument.
976 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnereee2f2b2007-11-28 18:51:29 +0000977 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getQualifiers() &&
978 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000979 // empty arg list, don't push any params.
980 } else {
Steve Naroff434fa8d2007-11-12 03:44:46 +0000981 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begeman2240f542007-11-13 21:49:48 +0000982 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroff434fa8d2007-11-12 03:44:46 +0000983 FnBodyScope));
984 }
Chris Lattner4b009652007-07-25 00:24:17 +0000985 }
986
987 FD->setParams(&Params[0], Params.size());
988
989 return FD;
990}
991
Steve Naroff99ee4302007-11-11 23:20:51 +0000992Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
993 Decl *dcl = static_cast<Decl *>(D);
994 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
995 FD->setBody((Stmt*)Body);
996 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff8ba51142007-12-13 18:18:56 +0000997 CurFunctionDecl = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +0000998 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +0000999 MD->setBody((Stmt*)Body);
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001000 CurMethodDecl = 0;
Steve Naroff8ba51142007-12-13 18:18:56 +00001001 }
Chris Lattner4b009652007-07-25 00:24:17 +00001002 // Verify and clean out per-function state.
1003
1004 // Check goto/label use.
1005 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1006 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1007 // Verify that we have no forward references left. If so, there was a goto
1008 // or address of a label taken, but no definition of it. Label fwd
1009 // definitions are indicated with a null substmt.
1010 if (I->second->getSubStmt() == 0) {
1011 LabelStmt *L = I->second;
1012 // Emit error.
1013 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1014
1015 // At this point, we have gotos that use the bogus label. Stitch it into
1016 // the function body so that they aren't leaked and that the AST is well
1017 // formed.
1018 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1019 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1020 }
1021 }
1022 LabelMap.clear();
1023
Steve Naroff99ee4302007-11-11 23:20:51 +00001024 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001025}
1026
Chris Lattner4b009652007-07-25 00:24:17 +00001027/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1028/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001029ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1030 IdentifierInfo &II, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +00001031 if (getLangOptions().C99) // Extension in C99.
1032 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1033 else // Legal in C90, but warn about it.
1034 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1035
1036 // FIXME: handle stuff like:
1037 // void foo() { extern float X(); }
1038 // void bar() { X(); } <-- implicit decl for X in another scope.
1039
1040 // Set a Declarator for the implicit definition: int foo();
1041 const char *Dummy;
1042 DeclSpec DS;
1043 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1044 Error = Error; // Silence warning.
1045 assert(!Error && "Error setting up implicit decl!");
1046 Declarator D(DS, Declarator::BlockContext);
1047 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1048 D.SetIdentifier(&II, Loc);
1049
1050 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +00001051 if (Scope *FnS = S->getFnParent())
1052 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +00001053 while (S->getParent())
1054 S = S->getParent();
1055
Steve Narofff0c31dd2007-09-16 16:16:00 +00001056 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattner4b009652007-07-25 00:24:17 +00001057}
1058
1059
Chris Lattner82bb4792007-11-14 06:34:38 +00001060TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001061 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001062 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001063 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001064
1065 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001066 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
1067 T, LastDeclarator);
1068 if (D.getInvalidType())
1069 NewTD->setInvalidDecl();
1070 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001071}
1072
Steve Naroff0acc9c92007-09-15 18:49:24 +00001073/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001074/// former case, Name will be non-null. In the later case, Name will be null.
1075/// TagType indicates what kind of tag this is. TK indicates whether this is a
1076/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001077Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001078 SourceLocation KWLoc, IdentifierInfo *Name,
1079 SourceLocation NameLoc, AttributeList *Attr) {
1080 // If this is a use of an existing tag, it must have a name.
1081 assert((Name != 0 || TK == TK_Definition) &&
1082 "Nameless record must be a definition!");
1083
1084 Decl::Kind Kind;
1085 switch (TagType) {
1086 default: assert(0 && "Unknown tag type!");
1087 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1088 case DeclSpec::TST_union: Kind = Decl::Union; break;
1089//case DeclSpec::TST_class: Kind = Decl::Class; break;
1090 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1091 }
1092
1093 // If this is a named struct, check to see if there was a previous forward
1094 // declaration or definition.
1095 if (TagDecl *PrevDecl =
1096 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1097 NameLoc, S))) {
1098
1099 // If this is a use of a previous tag, or if the tag is already declared in
1100 // the same scope (so that the definition/declaration completes or
1101 // rementions the tag), reuse the decl.
1102 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1103 // Make sure that this wasn't declared as an enum and now used as a struct
1104 // or something similar.
1105 if (PrevDecl->getKind() != Kind) {
1106 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1107 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1108 }
1109
1110 // If this is a use or a forward declaration, we're good.
1111 if (TK != TK_Definition)
1112 return PrevDecl;
1113
1114 // Diagnose attempts to redefine a tag.
1115 if (PrevDecl->isDefinition()) {
1116 Diag(NameLoc, diag::err_redefinition, Name->getName());
1117 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1118 // If this is a redefinition, recover by making this struct be
1119 // anonymous, which will make any later references get the previous
1120 // definition.
1121 Name = 0;
1122 } else {
1123 // Okay, this is definition of a previously declared or referenced tag.
1124 // Move the location of the decl to be the definition site.
1125 PrevDecl->setLocation(NameLoc);
1126 return PrevDecl;
1127 }
1128 }
1129 // If we get here, this is a definition of a new struct type in a nested
1130 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1131 // type.
1132 }
1133
1134 // If there is an identifier, use the location of the identifier as the
1135 // location of the decl, otherwise use the location of the struct/union
1136 // keyword.
1137 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1138
1139 // Otherwise, if this is the first time we've seen this tag, create the decl.
1140 TagDecl *New;
1141 switch (Kind) {
1142 default: assert(0 && "Unknown tag kind!");
1143 case Decl::Enum:
1144 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1145 // enum X { A, B, C } D; D should chain to X.
1146 New = new EnumDecl(Loc, Name, 0);
1147 // If this is an undefined enum, warn.
1148 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1149 break;
1150 case Decl::Union:
1151 case Decl::Struct:
1152 case Decl::Class:
1153 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1154 // struct X { int A; } D; D should chain to X.
1155 New = new RecordDecl(Kind, Loc, Name, 0);
1156 break;
1157 }
1158
1159 // If this has an identifier, add it to the scope stack.
1160 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001161 // The scope passed in may not be a decl scope. Zip up the scope tree until
1162 // we find one that is.
1163 while ((S->getFlags() & Scope::DeclScope) == 0)
1164 S = S->getParent();
1165
1166 // Add it to the decl chain.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001167 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001168 Name->setFETokenInfo(New);
1169 S->AddDecl(New);
1170 }
Steve Naroff6fd865b2007-11-28 22:54:11 +00001171
Chris Lattner4b009652007-07-25 00:24:17 +00001172 return New;
1173}
1174
Steve Naroff0acc9c92007-09-15 18:49:24 +00001175/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001176/// to create a FieldDecl object for it.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001177Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001178 SourceLocation DeclStart,
1179 Declarator &D, ExprTy *BitfieldWidth) {
1180 IdentifierInfo *II = D.getIdentifier();
1181 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001182 SourceLocation Loc = DeclStart;
1183 if (II) Loc = D.getIdentifierLoc();
1184
1185 // FIXME: Unnamed fields can be handled in various different ways, for
1186 // example, unnamed unions inject all members into the struct namespace!
1187
1188
1189 if (BitWidth) {
1190 // TODO: Validate.
1191 //printf("WARNING: BITFIELDS IGNORED!\n");
1192
1193 // 6.7.2.1p3
1194 // 6.7.2.1p4
1195
1196 } else {
1197 // Not a bitfield.
1198
1199 // validate II.
1200
1201 }
1202
1203 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001204 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1205 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001206
Chris Lattner4b009652007-07-25 00:24:17 +00001207 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1208 // than a variably modified type.
Steve Naroff5eb879b2007-08-31 17:20:07 +00001209 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1210 Diag(Loc, diag::err_typecheck_illegal_vla,
1211 VAT->getSizeExpr()->getSourceRange());
1212 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001213 }
Chris Lattner4b009652007-07-25 00:24:17 +00001214 // FIXME: Chain fielddecls together.
Steve Naroff75494892007-09-11 21:17:26 +00001215 FieldDecl *NewFD;
1216
1217 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patelf616a242007-11-01 16:29:56 +00001218 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Ted Kremenek42730c52008-01-07 19:49:32 +00001219 else if (isa<ObjCInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1220 isa<ObjCImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
1221 isa<ObjCCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroff4fbfb452007-11-14 14:15:31 +00001222 // FIXME: ivars are currently used to model properties, and
1223 // properties can appear within a protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00001224 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1225 isa<ObjCProtocolDecl>(static_cast<Decl *>(TagDecl)))
1226 NewFD = new ObjCIvarDecl(Loc, II, T);
Steve Naroff75494892007-09-11 21:17:26 +00001227 else
Steve Naroff0acc9c92007-09-15 18:49:24 +00001228 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff75494892007-09-11 21:17:26 +00001229
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001230 if (D.getInvalidType() || InvalidDecl)
1231 NewFD->setInvalidDecl();
1232 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001233}
1234
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001235/// TranslateIvarVisibility - Translate visibility from a token ID to an
1236/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00001237static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001238TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001239 switch (ivarVisibility) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001240 case tok::objc_private: return ObjCIvarDecl::Private;
1241 case tok::objc_public: return ObjCIvarDecl::Public;
1242 case tok::objc_protected: return ObjCIvarDecl::Protected;
1243 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001244 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001245 }
1246}
1247
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00001248void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001249 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001250 DeclTy **Fields, unsigned NumFields,
Steve Naroff1a7fa7b2007-10-29 21:38:07 +00001251 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001252 tok::ObjCKeywordKind *visibility) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001253 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1254 assert(EnclosingDecl && "missing record or interface decl");
1255 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1256
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001257 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001258 // Diagnose code like:
1259 // struct S { struct S {} X; };
1260 // We discover this when we complete the outer S. Reject and ignore the
1261 // outer S.
1262 Diag(Record->getLocation(), diag::err_nested_redefinition,
1263 Record->getKindName());
1264 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001265 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001266 return;
1267 }
Chris Lattner4b009652007-07-25 00:24:17 +00001268 // Verify that all the fields are okay.
1269 unsigned NumNamedMembers = 0;
1270 llvm::SmallVector<FieldDecl*, 32> RecFields;
1271 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00001272
Chris Lattner4b009652007-07-25 00:24:17 +00001273 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001274
Steve Naroff9bb759f2007-09-14 22:20:54 +00001275 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1276 assert(FD && "missing field decl");
1277
1278 // Remember all fields.
1279 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00001280
1281 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001282 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +00001283
Steve Naroffffeaa552007-09-14 23:09:53 +00001284 // If we have visibility info, make sure the AST is set accordingly.
1285 if (visibility)
Ted Kremenek42730c52008-01-07 19:49:32 +00001286 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001287 TranslateIvarVisibility(visibility[i]));
Steve Naroffffeaa552007-09-14 23:09:53 +00001288
Chris Lattner4b009652007-07-25 00:24:17 +00001289 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001290 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001291 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00001292 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001293 FD->setInvalidDecl();
1294 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001295 continue;
1296 }
Chris Lattner4b009652007-07-25 00:24:17 +00001297 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1298 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001299 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001300 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001301 FD->setInvalidDecl();
1302 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001303 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001304 }
Chris Lattner4b009652007-07-25 00:24:17 +00001305 if (i != NumFields-1 || // ... that the last member ...
1306 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001307 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001308 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001309 FD->setInvalidDecl();
1310 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001311 continue;
1312 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001313 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00001314 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1315 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001316 FD->setInvalidDecl();
1317 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001318 continue;
1319 }
Chris Lattner4b009652007-07-25 00:24:17 +00001320 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001321 if (Record)
1322 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001323 }
Chris Lattner4b009652007-07-25 00:24:17 +00001324 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1325 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001326 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001327 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1328 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001329 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner4b009652007-07-25 00:24:17 +00001330 Record->setHasFlexibleArrayMember(true);
1331 } else {
1332 // If this is a struct/class and this is not the last element, reject
1333 // it. Note that GCC supports variable sized arrays in the middle of
1334 // structures.
1335 if (i != NumFields-1) {
1336 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1337 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001338 FD->setInvalidDecl();
1339 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001340 continue;
1341 }
Chris Lattner4b009652007-07-25 00:24:17 +00001342 // We support flexible arrays at the end of structs in other structs
1343 // as an extension.
1344 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1345 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001346 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001347 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001348 }
1349 }
1350 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001351 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00001352 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001353 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1354 FD->getName());
1355 FD->setInvalidDecl();
1356 EnclosingDecl->setInvalidDecl();
1357 continue;
1358 }
Chris Lattner4b009652007-07-25 00:24:17 +00001359 // Keep track of the number of named members.
1360 if (IdentifierInfo *II = FD->getIdentifier()) {
1361 // Detect duplicate member names.
1362 if (!FieldIDs.insert(II)) {
1363 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1364 // Find the previous decl.
1365 SourceLocation PrevLoc;
1366 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1367 assert(i != e && "Didn't find previous def!");
1368 if (RecFields[i]->getIdentifier() == II) {
1369 PrevLoc = RecFields[i]->getLocation();
1370 break;
1371 }
1372 }
1373 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001374 FD->setInvalidDecl();
1375 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001376 continue;
1377 }
1378 ++NumNamedMembers;
1379 }
Chris Lattner4b009652007-07-25 00:24:17 +00001380 }
1381
Chris Lattner4b009652007-07-25 00:24:17 +00001382 // Okay, we successfully defined 'Record'.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001383 if (Record)
1384 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001385 else {
Ted Kremenek42730c52008-01-07 19:49:32 +00001386 ObjCIvarDecl **ClsFields =
1387 reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1388 if (isa<ObjCInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1389 cast<ObjCInterfaceDecl>(static_cast<Decl*>(RecDecl))->
Steve Naroff1a7fa7b2007-10-29 21:38:07 +00001390 addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Ted Kremenek42730c52008-01-07 19:49:32 +00001391 else if (isa<ObjCImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1392 ObjCImplementationDecl* IMPDecl =
1393 cast<ObjCImplementationDecl>(static_cast<Decl*>(RecDecl));
1394 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1395 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00001396 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001397 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001398 }
Chris Lattner4b009652007-07-25 00:24:17 +00001399}
1400
Steve Naroff0acc9c92007-09-15 18:49:24 +00001401Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001402 DeclTy *lastEnumConst,
1403 SourceLocation IdLoc, IdentifierInfo *Id,
1404 SourceLocation EqualLoc, ExprTy *val) {
1405 theEnumDecl = theEnumDecl; // silence unused warning.
1406 EnumConstantDecl *LastEnumConst =
1407 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1408 Expr *Val = static_cast<Expr*>(val);
1409
Chris Lattnera7549902007-08-26 06:24:45 +00001410 // The scope passed in may not be a decl scope. Zip up the scope tree until
1411 // we find one that is.
1412 while ((S->getFlags() & Scope::DeclScope) == 0)
1413 S = S->getParent();
1414
Chris Lattner4b009652007-07-25 00:24:17 +00001415 // Verify that there isn't already something declared with this name in this
1416 // scope.
Steve Naroffcb597472007-09-13 21:41:19 +00001417 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1418 IdLoc, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001419 if (S->isDeclScope(PrevDecl)) {
1420 if (isa<EnumConstantDecl>(PrevDecl))
1421 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1422 else
1423 Diag(IdLoc, diag::err_redefinition, Id->getName());
1424 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1425 // FIXME: Don't leak memory: delete Val;
1426 return 0;
1427 }
1428 }
1429
1430 llvm::APSInt EnumVal(32);
1431 QualType EltTy;
1432 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001433 // Make sure to promote the operand type to int.
1434 UsualUnaryConversions(Val);
1435
Chris Lattner4b009652007-07-25 00:24:17 +00001436 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1437 SourceLocation ExpLoc;
1438 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1439 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1440 Id->getName());
1441 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001442 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001443 } else {
1444 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001445 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001446 }
1447
1448 if (!Val) {
1449 if (LastEnumConst) {
1450 // Assign the last value + 1.
1451 EnumVal = LastEnumConst->getInitVal();
1452 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001453
1454 // Check for overflow on increment.
1455 if (EnumVal < LastEnumConst->getInitVal())
1456 Diag(IdLoc, diag::warn_enum_value_overflow);
1457
Chris Lattnere7f53a42007-08-27 17:37:24 +00001458 EltTy = LastEnumConst->getType();
1459 } else {
1460 // First value, set to zero.
1461 EltTy = Context.IntTy;
Chris Lattner3496d522007-09-04 02:45:27 +00001462 EnumVal.zextOrTrunc(
1463 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001464 }
Chris Lattner4b009652007-07-25 00:24:17 +00001465 }
1466
Chris Lattner4b009652007-07-25 00:24:17 +00001467 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1468 LastEnumConst);
1469
1470 // Register this decl in the current scope stack.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001471 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001472 Id->setFETokenInfo(New);
1473 S->AddDecl(New);
1474 return New;
1475}
1476
Steve Naroff0acc9c92007-09-15 18:49:24 +00001477void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00001478 DeclTy **Elements, unsigned NumElements) {
1479 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1480 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1481
Chris Lattner435c3fd2007-08-28 05:10:31 +00001482 // TODO: If the result value doesn't fit in an int, it must be a long or long
1483 // long value. ISO C does not support this, but GCC does as an extension,
1484 // emit a warning.
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001485 unsigned IntWidth =
1486 Context.Target.getIntWidth(Context.getFullLoc(Enum->getLocation()));
Chris Lattner435c3fd2007-08-28 05:10:31 +00001487
1488
Chris Lattner206754a2007-08-28 06:15:15 +00001489 // Verify that all the values are okay, compute the size of the values, and
1490 // reverse the list.
1491 unsigned NumNegativeBits = 0;
1492 unsigned NumPositiveBits = 0;
1493
1494 // Keep track of whether all elements have type int.
1495 bool AllElementsInt = true;
1496
Chris Lattner4b009652007-07-25 00:24:17 +00001497 EnumConstantDecl *EltList = 0;
1498 for (unsigned i = 0; i != NumElements; ++i) {
1499 EnumConstantDecl *ECD =
1500 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1501 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001502
1503 // If the enum value doesn't fit in an int, emit an extension warning.
1504 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1505 "Should have promoted value to int");
1506 const llvm::APSInt &InitVal = ECD->getInitVal();
1507 if (InitVal.getBitWidth() > IntWidth) {
1508 llvm::APSInt V(InitVal);
1509 V.trunc(IntWidth);
1510 V.extend(InitVal.getBitWidth());
1511 if (V != InitVal)
1512 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1513 InitVal.toString());
1514 }
Chris Lattner206754a2007-08-28 06:15:15 +00001515
1516 // Keep track of the size of positive and negative values.
1517 if (InitVal.isUnsigned() || !InitVal.isNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00001518 NumPositiveBits = std::max(NumPositiveBits,
1519 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00001520 else
Chris Lattneraff63f02008-01-14 21:47:29 +00001521 NumNegativeBits = std::max(NumNegativeBits,
1522 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001523
Chris Lattner206754a2007-08-28 06:15:15 +00001524 // Keep track of whether every enum element has type int (very commmon).
1525 if (AllElementsInt)
1526 AllElementsInt = ECD->getType() == Context.IntTy;
1527
Chris Lattner4b009652007-07-25 00:24:17 +00001528 ECD->setNextDeclarator(EltList);
1529 EltList = ECD;
1530 }
1531
Chris Lattner206754a2007-08-28 06:15:15 +00001532 // Figure out the type that should be used for this enum.
1533 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1534 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001535 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001536
1537 if (NumNegativeBits) {
1538 // If there is a negative value, figure out the smallest integer type (of
1539 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001540 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001541 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001542 BestWidth = IntWidth;
1543 } else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001544 BestWidth =
1545 Context.Target.getLongWidth(Context.getFullLoc(Enum->getLocation()));
1546
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001547 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001548 BestType = Context.LongTy;
1549 else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001550 BestWidth = Context.Target.getLongLongWidth(
1551 Context.getFullLoc(Enum->getLocation()));
1552
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001553 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001554 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1555 BestType = Context.LongLongTy;
1556 }
1557 }
1558 } else {
1559 // If there is no negative value, figure out which of uint, ulong, ulonglong
1560 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001561 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001562 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001563 BestWidth = IntWidth;
1564 } else if (NumPositiveBits <=
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001565 (BestWidth = Context.Target.getLongWidth(
1566 Context.getFullLoc(Enum->getLocation()))))
1567
Chris Lattner206754a2007-08-28 06:15:15 +00001568 BestType = Context.UnsignedLongTy;
1569 else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001570 BestWidth =
1571 Context.Target.getLongLongWidth(Context.getFullLoc(Enum->getLocation()));
1572
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001573 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001574 "How could an initializer get larger than ULL?");
1575 BestType = Context.UnsignedLongLongTy;
1576 }
1577 }
1578
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001579 // Loop over all of the enumerator constants, changing their types to match
1580 // the type of the enum if needed.
1581 for (unsigned i = 0; i != NumElements; ++i) {
1582 EnumConstantDecl *ECD =
1583 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1584 if (!ECD) continue; // Already issued a diagnostic.
1585
1586 // Standard C says the enumerators have int type, but we allow, as an
1587 // extension, the enumerators to be larger than int size. If each
1588 // enumerator value fits in an int, type it as an int, otherwise type it the
1589 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1590 // that X has type 'int', not 'unsigned'.
1591 if (ECD->getType() == Context.IntTy)
1592 continue; // Already int type.
1593
1594 // Determine whether the value fits into an int.
1595 llvm::APSInt InitVal = ECD->getInitVal();
1596 bool FitsInInt;
1597 if (InitVal.isUnsigned() || !InitVal.isNegative())
1598 FitsInInt = InitVal.getActiveBits() < IntWidth;
1599 else
1600 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1601
1602 // If it fits into an integer type, force it. Otherwise force it to match
1603 // the enum decl type.
1604 QualType NewTy;
1605 unsigned NewWidth;
1606 bool NewSign;
1607 if (FitsInInt) {
1608 NewTy = Context.IntTy;
1609 NewWidth = IntWidth;
1610 NewSign = true;
1611 } else if (ECD->getType() == BestType) {
1612 // Already the right type!
1613 continue;
1614 } else {
1615 NewTy = BestType;
1616 NewWidth = BestWidth;
1617 NewSign = BestType->isSignedIntegerType();
1618 }
1619
1620 // Adjust the APSInt value.
1621 InitVal.extOrTrunc(NewWidth);
1622 InitVal.setIsSigned(NewSign);
1623 ECD->setInitVal(InitVal);
1624
1625 // Adjust the Expr initializer and type.
1626 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1627 ECD->setType(NewTy);
1628 }
Chris Lattner206754a2007-08-28 06:15:15 +00001629
Chris Lattner90a018d2007-08-28 18:24:31 +00001630 Enum->defineElements(EltList, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00001631}
1632
Chris Lattner806a5f52008-01-12 07:05:38 +00001633Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
1634 SourceLocation LBrace,
1635 SourceLocation RBrace,
1636 const char *Lang,
1637 unsigned StrSize,
1638 DeclTy *D) {
1639 LinkageSpecDecl::LanguageIDs Language;
1640 Decl *dcl = static_cast<Decl *>(D);
1641 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1642 Language = LinkageSpecDecl::lang_c;
1643 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1644 Language = LinkageSpecDecl::lang_cxx;
1645 else {
1646 Diag(Loc, diag::err_bad_language);
1647 return 0;
1648 }
1649
1650 // FIXME: Add all the various semantics of linkage specifications
1651 return new LinkageSpecDecl(Loc, Language, dcl);
1652}
1653
Chris Lattner4b009652007-07-25 00:24:17 +00001654void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
Anders Carlsson28e34e32007-12-19 06:16:30 +00001655 const char *attrName = rawAttr->getAttributeName()->getName();
1656 unsigned attrLen = rawAttr->getAttributeName()->getLength();
1657
Anders Carlsson5f558b52007-12-19 17:43:24 +00001658 // Normalize the attribute name, __foo__ becomes foo.
1659 if (attrLen > 4 && attrName[0] == '_' && attrName[1] == '_' &&
1660 attrName[attrLen - 2] == '_' && attrName[attrLen - 1] == '_') {
1661 attrName += 2;
1662 attrLen -= 4;
1663 }
1664
1665 if (attrLen == 11 && !memcmp(attrName, "vector_size", 11)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001666 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1667 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1668 if (!newType.isNull()) // install the new vector type into the decl
1669 vDecl->setType(newType);
1670 }
1671 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1672 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1673 rawAttr);
1674 if (!newType.isNull()) // install the new vector type into the decl
1675 tDecl->setUnderlyingType(newType);
1676 }
Anders Carlsson5f558b52007-12-19 17:43:24 +00001677 } else if (attrLen == 15 && !memcmp(attrName, "ocu_vector_type", 15)) {
Steve Naroff82113e32007-07-29 16:33:31 +00001678 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1679 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1680 else
Chris Lattner4b009652007-07-25 00:24:17 +00001681 Diag(rawAttr->getAttributeLoc(),
1682 diag::err_typecheck_ocu_vector_not_typedef);
Anders Carlssonc8b44122007-12-19 07:19:40 +00001683 } else if (attrLen == 7 && !memcmp(attrName, "aligned", 7)) {
1684 HandleAlignedAttribute(New, rawAttr);
Chris Lattner4b009652007-07-25 00:24:17 +00001685 }
Anders Carlssonc8b44122007-12-19 07:19:40 +00001686
Chris Lattner4b009652007-07-25 00:24:17 +00001687 // FIXME: add other attributes...
1688}
1689
1690void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1691 AttributeList *declarator_postfix) {
1692 while (declspec_prefix) {
1693 HandleDeclAttribute(New, declspec_prefix);
1694 declspec_prefix = declspec_prefix->getNext();
1695 }
1696 while (declarator_postfix) {
1697 HandleDeclAttribute(New, declarator_postfix);
1698 declarator_postfix = declarator_postfix->getNext();
1699 }
1700}
1701
Steve Naroff82113e32007-07-29 16:33:31 +00001702void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1703 AttributeList *rawAttr) {
1704 QualType curType = tDecl->getUnderlyingType();
Anders Carlssonc8b44122007-12-19 07:19:40 +00001705 // check the attribute arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001706 if (rawAttr->getNumArgs() != 1) {
1707 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1708 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001709 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001710 }
1711 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1712 llvm::APSInt vecSize(32);
1713 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1714 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1715 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001716 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001717 }
1718 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1719 // in conjunction with complex types (pointers, arrays, functions, etc.).
1720 Type *canonType = curType.getCanonicalType().getTypePtr();
1721 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1722 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1723 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001724 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001725 }
1726 // unlike gcc's vector_size attribute, the size is specified as the
1727 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00001728 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00001729
1730 if (vectorSize == 0) {
1731 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1732 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001733 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001734 }
Steve Naroff82113e32007-07-29 16:33:31 +00001735 // Instantiate/Install the vector type, the number of elements is > 0.
1736 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1737 // Remember this typedef decl, we will need it later for diagnostics.
1738 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001739}
1740
1741QualType Sema::HandleVectorTypeAttribute(QualType curType,
1742 AttributeList *rawAttr) {
1743 // check the attribute arugments.
1744 if (rawAttr->getNumArgs() != 1) {
1745 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1746 std::string("1"));
1747 return QualType();
1748 }
1749 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1750 llvm::APSInt vecSize(32);
1751 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1752 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1753 sizeExpr->getSourceRange());
1754 return QualType();
1755 }
1756 // navigate to the base type - we need to provide for vector pointers,
1757 // vector arrays, and functions returning vectors.
1758 Type *canonType = curType.getCanonicalType().getTypePtr();
1759
1760 if (canonType->isPointerType() || canonType->isArrayType() ||
1761 canonType->isFunctionType()) {
Chris Lattner5b5e1982007-12-19 05:38:06 +00001762 assert(0 && "HandleVector(): Complex type construction unimplemented");
Chris Lattner4b009652007-07-25 00:24:17 +00001763 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1764 do {
1765 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1766 canonType = PT->getPointeeType().getTypePtr();
1767 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1768 canonType = AT->getElementType().getTypePtr();
1769 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1770 canonType = FT->getResultType().getTypePtr();
1771 } while (canonType->isPointerType() || canonType->isArrayType() ||
1772 canonType->isFunctionType());
1773 */
1774 }
1775 // the base type must be integer or float.
1776 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1777 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1778 curType.getCanonicalType().getAsString());
1779 return QualType();
1780 }
Chris Lattner3496d522007-09-04 02:45:27 +00001781 unsigned typeSize = static_cast<unsigned>(
1782 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Chris Lattner4b009652007-07-25 00:24:17 +00001783 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00001784 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00001785
1786 // the vector size needs to be an integral multiple of the type size.
1787 if (vectorSize % typeSize) {
1788 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1789 sizeExpr->getSourceRange());
1790 return QualType();
1791 }
1792 if (vectorSize == 0) {
1793 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1794 sizeExpr->getSourceRange());
1795 return QualType();
1796 }
1797 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1798 // the number of elements to be a power of two (unlike GCC).
1799 // Instantiate the vector type, the number of elements is > 0.
1800 return Context.getVectorType(curType, vectorSize/typeSize);
1801}
1802
Anders Carlssonc8b44122007-12-19 07:19:40 +00001803void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
1804{
1805 // check the attribute arguments.
Anders Carlsson5f558b52007-12-19 17:43:24 +00001806 // FIXME: Handle the case where are no arguments.
Anders Carlssonc8b44122007-12-19 07:19:40 +00001807 if (rawAttr->getNumArgs() != 1) {
1808 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1809 std::string("1"));
1810 return;
1811 }
1812
1813 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
1814 llvm::APSInt alignment(32);
1815 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
1816 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1817 alignmentExpr->getSourceRange());
1818 return;
1819 }
1820}