blob: f21ba70c76079d429e696437ae1c25e0bec61a97 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Anders Carlssonf78915f2008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/Builtins.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Type.h"
22#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Basic/SourceManager.h"
27// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000028#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000029#include "clang/Lex/HeaderSearch.h"
Steve Naroff563477d2007-09-18 23:55:05 +000030#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000032#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
34
Reid Spencer5f016e22007-07-11 17:01:13 +000035Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000036 Decl *IIDecl = II.getFETokenInfo<Decl>();
37 // Find first occurance of none-tagged declaration
38 while(IIDecl && IIDecl->getIdentifierNamespace() != Decl::IDNS_Ordinary)
39 IIDecl = cast<ScopedDecl>(IIDecl)->getNext();
40 if (!IIDecl)
41 return 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000042 if (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000043 return IIDecl;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000044 if (ObjCCompatibleAliasDecl *ADecl =
45 dyn_cast<ObjCCompatibleAliasDecl>(IIDecl))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000046 return ADecl->getClassInterface();
Steve Naroff3536b442007-09-06 21:24:23 +000047 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000048}
49
Steve Naroffb216c882007-10-09 22:01:59 +000050void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000051 if (S->decl_empty()) return;
52 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
53
Reid Spencer5f016e22007-07-11 17:01:13 +000054 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
55 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000056 Decl *TmpD = static_cast<Decl*>(*I);
57 assert(TmpD && "This decl didn't get pushed??");
58 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
59 assert(D && "This decl isn't a ScopedDecl?");
60
Reid Spencer5f016e22007-07-11 17:01:13 +000061 IdentifierInfo *II = D->getIdentifier();
62 if (!II) continue;
63
64 // Unlink this decl from the identifier. Because the scope contains decls
65 // in an unordered collection, and because we have multiple identifier
66 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
67 if (II->getFETokenInfo<Decl>() == D) {
68 // Normal case, no multiple decls in different namespaces.
69 II->setFETokenInfo(D->getNext());
70 } else {
71 // Scan ahead. There are only three namespaces in C, so this loop can
72 // never execute more than 3 times.
Steve Naroffc752d042007-09-13 18:10:37 +000073 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +000074 while (SomeDecl->getNext() != D) {
75 SomeDecl = SomeDecl->getNext();
76 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
77 }
78 SomeDecl->setNext(D->getNext());
79 }
80
81 // This will have to be revisited for C++: there we want to nest stuff in
82 // namespace decls etc. Even for C, we might want a top-level translation
83 // unit decl or something.
84 if (!CurFunctionDecl)
85 continue;
86
87 // Chain this decl to the containing function, it now owns the memory for
88 // the decl.
89 D->setNext(CurFunctionDecl->getDeclChain());
90 CurFunctionDecl->setDeclChain(D);
91 }
92}
93
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +000094/// LookupInterfaceDecl - Lookup interface declaration in the scope chain.
95/// Return the first declaration found (which may or may not be a class
Fariborz Jahanian3fe44e42007-10-12 19:53:08 +000096/// declaration. Caller is responsible for handling the none-class case.
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +000097/// Bypassing the alias of a class by returning the aliased class.
98ScopedDecl *Sema::LookupInterfaceDecl(IdentifierInfo *ClassName) {
99 ScopedDecl *IDecl;
100 // Scan up the scope chain looking for a decl that matches this identifier
101 // that is in the appropriate namespace.
102 for (IDecl = ClassName->getFETokenInfo<ScopedDecl>(); IDecl;
103 IDecl = IDecl->getNext())
104 if (IDecl->getIdentifierNamespace() == Decl::IDNS_Ordinary)
105 break;
106
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000107 if (ObjCCompatibleAliasDecl *ADecl =
108 dyn_cast_or_null<ObjCCompatibleAliasDecl>(IDecl))
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000109 return ADecl->getClassInterface();
110 return IDecl;
111}
112
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000113/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +0000114/// return 0 if one not found.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000115ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000116 ScopedDecl *IdDecl = LookupInterfaceDecl(Id);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000117 return cast_or_null<ObjCInterfaceDecl>(IdDecl);
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +0000118}
119
Reid Spencer5f016e22007-07-11 17:01:13 +0000120/// LookupScopedDecl - Look up the inner-most declaration in the specified
121/// namespace.
Steve Naroffc752d042007-09-13 18:10:37 +0000122ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
123 SourceLocation IdLoc, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000124 if (II == 0) return 0;
125 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
126
127 // Scan up the scope chain looking for a decl that matches this identifier
128 // that is in the appropriate namespace. This search should not take long, as
129 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffc752d042007-09-13 18:10:37 +0000130 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +0000131 if (D->getIdentifierNamespace() == NS)
132 return D;
133
134 // If we didn't find a use of this identifier, and if the identifier
135 // corresponds to a compiler builtin, create the decl object for the builtin
136 // now, injecting it into translation unit scope, and return it.
137 if (NS == Decl::IDNS_Ordinary) {
138 // If this is a builtin on some other target, or if this builtin varies
139 // across targets (e.g. in type), emit a diagnostic and mark the translation
140 // unit non-portable for using it.
141 if (II->isNonPortableBuiltin()) {
142 // Only emit this diagnostic once for this builtin.
143 II->setNonPortableBuiltin(false);
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000144 Context.Target.DiagnoseNonPortability(Context.getFullLoc(IdLoc),
Reid Spencer5f016e22007-07-11 17:01:13 +0000145 diag::port_target_builtin_use);
146 }
147 // If this is a builtin on this (or all) targets, create the decl.
148 if (unsigned BuiltinID = II->getBuiltinID())
149 return LazilyCreateBuiltin(II, BuiltinID, S);
150 }
151 return 0;
152}
153
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000154void Sema::InitBuiltinVaListType()
155{
156 if (!Context.getBuiltinVaListType().isNull())
157 return;
158
159 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
160 ScopedDecl *VaDecl = LookupScopedDecl(VaIdent, Decl::IDNS_Ordinary,
161 SourceLocation(), TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000162 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000163 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
164}
165
Reid Spencer5f016e22007-07-11 17:01:13 +0000166/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
167/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000168ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
169 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000170 Builtin::ID BID = (Builtin::ID)bid;
171
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000172 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson793680e2007-10-12 23:56:29 +0000173 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000174 BID == Builtin::BI__builtin_va_end)
175 InitBuiltinVaListType();
176
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000177 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Reid Spencer5f016e22007-07-11 17:01:13 +0000178 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000179 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000180
181 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000182 if (Scope *FnS = S->getFnParent())
183 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 while (S->getParent())
185 S = S->getParent();
186 S->AddDecl(New);
187
188 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000189 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 // Scan until we find the last (outermost) decl in the id chain.
191 while (LastDecl->getNext())
192 LastDecl = LastDecl->getNext();
193 // Insert before (outside) it.
194 LastDecl->setNext(New);
195 } else {
196 II->setFETokenInfo(New);
197 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 return New;
199}
200
201/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
202/// and scope as a previous declaration 'Old'. Figure out how to resolve this
203/// situation, merging decls or emitting diagnostics as appropriate.
204///
Steve Naroff8e74c932007-09-13 21:41:19 +0000205TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 // Verify the old decl was also a typedef.
207 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
208 if (!Old) {
209 Diag(New->getLocation(), diag::err_redefinition_different_kind,
210 New->getName());
211 Diag(OldD->getLocation(), diag::err_previous_definition);
212 return New;
213 }
214
Steve Naroff8ee529b2007-10-31 18:42:27 +0000215 // Allow multiple definitions for ObjC built-in typedefs.
216 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000217 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000218 return Old;
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000219
220 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
221 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
222 // *either* declaration is in a system header. The code below implements
223 // this adhoc compatibility rule. FIXME: The following code will not
224 // work properly when compiling ".i" files (containing preprocessed output).
225 SourceManager &SrcMgr = Context.getSourceManager();
226 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
227 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
228 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
229 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
230 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
231
Steve Naroffd62701b2008-02-07 03:50:06 +0000232 if ((OldDirType == DirectoryLookup::ExternCSystemHeaderDir ||
233 NewDirType == DirectoryLookup::ExternCSystemHeaderDir) ||
234 getLangOptions().Microsoft)
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000235 return New;
Steve Naroff8ee529b2007-10-31 18:42:27 +0000236
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
238 // TODO: This is totally simplistic. It should handle merging functions
239 // together etc, merging extern int X; int X; ...
240 Diag(New->getLocation(), diag::err_redefinition, New->getName());
241 Diag(Old->getLocation(), diag::err_previous_definition);
242 return New;
243}
244
245/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
246/// and scope as a previous declaration 'Old'. Figure out how to resolve this
247/// situation, merging decls or emitting diagnostics as appropriate.
248///
Steve Naroff8e74c932007-09-13 21:41:19 +0000249FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000250 // Verify the old decl was also a function.
251 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
252 if (!Old) {
253 Diag(New->getLocation(), diag::err_redefinition_different_kind,
254 New->getName());
255 Diag(OldD->getLocation(), diag::err_previous_definition);
256 return New;
257 }
258
Chris Lattner55196442007-11-20 19:04:50 +0000259 QualType OldQType = Old->getCanonicalType();
260 QualType NewQType = New->getCanonicalType();
261
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000262 // Function types need to be compatible, not identical. This handles
263 // duplicate function decls like "void f(int); void f(enum X);" properly.
264 if (Context.functionTypesAreCompatible(OldQType, NewQType))
265 return New;
Chris Lattnere3995fe2007-11-06 06:07:26 +0000266
Steve Naroff837618c2008-01-16 15:01:34 +0000267 // A function that has already been declared has been redeclared or defined
268 // with a different type- show appropriate diagnostic
269 diag::kind PrevDiag = Old->getBody() ? diag::err_previous_definition :
270 diag::err_previous_declaration;
271
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
273 // TODO: This is totally simplistic. It should handle merging functions
274 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000275 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
276 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 return New;
278}
279
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000280
281/// hasUndefinedLength - Used by equivalentArrayTypes to determine whether the
282/// the outermost VariableArrayType has no size defined.
283static bool hasUndefinedLength(const ArrayType *Array) {
284 const VariableArrayType *VAT = Array->getAsVariableArrayType();
285 return VAT && !VAT->getSizeExpr();
286}
287
288/// equivalentArrayTypes - Used to determine whether two array types are
289/// equivalent.
290/// We need to check this explicitly as an incomplete array definition is
291/// considered a VariableArrayType, so will not match a complete array
292/// definition that would be otherwise equivalent.
293static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
294 const ArrayType *NewAT = NewQType->getAsArrayType();
295 const ArrayType *OldAT = OldQType->getAsArrayType();
296
297 if (!NewAT || !OldAT)
298 return false;
299
300 // If either (or both) array types in incomplete we need to strip off the
301 // outer VariableArrayType. Once the outer VAT is removed the remaining
302 // types must be identical if the array types are to be considered
303 // equivalent.
304 // eg. int[][1] and int[1][1] become
305 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
306 // removing the outermost VAT gives
307 // CAT(1, int) and CAT(1, int)
308 // which are equal, therefore the array types are equivalent.
309 if (hasUndefinedLength(NewAT) || hasUndefinedLength(OldAT)) {
310 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
311 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000312 NewQType = NewAT->getElementType().getCanonicalType();
313 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000314 }
315
316 return NewQType == OldQType;
317}
318
Reid Spencer5f016e22007-07-11 17:01:13 +0000319/// MergeVarDecl - We just parsed a variable 'New' which has the same name
320/// and scope as a previous declaration 'Old'. Figure out how to resolve this
321/// situation, merging decls or emitting diagnostics as appropriate.
322///
323/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
324/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
325///
Steve Naroff8e74c932007-09-13 21:41:19 +0000326VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000327 // Verify the old decl was also a variable.
328 VarDecl *Old = dyn_cast<VarDecl>(OldD);
329 if (!Old) {
330 Diag(New->getLocation(), diag::err_redefinition_different_kind,
331 New->getName());
332 Diag(OldD->getLocation(), diag::err_previous_definition);
333 return New;
334 }
335 // Verify the types match.
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000336 if (Old->getCanonicalType() != New->getCanonicalType() &&
337 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 Diag(New->getLocation(), diag::err_redefinition, New->getName());
339 Diag(Old->getLocation(), diag::err_previous_definition);
340 return New;
341 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000342 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
343 if (New->getStorageClass() == VarDecl::Static &&
344 (Old->getStorageClass() == VarDecl::None ||
345 Old->getStorageClass() == VarDecl::Extern)) {
346 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
347 Diag(Old->getLocation(), diag::err_previous_definition);
348 return New;
349 }
350 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
351 if (New->getStorageClass() != VarDecl::Static &&
352 Old->getStorageClass() == VarDecl::Static) {
353 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
354 Diag(Old->getLocation(), diag::err_previous_definition);
355 return New;
356 }
357 // We've verified the types match, now handle "tentative" definitions.
358 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
359 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
360
361 if (OldFSDecl && NewFSDecl) {
362 // Handle C "tentative" external object definitions (C99 6.9.2).
363 bool OldIsTentative = false;
364 bool NewIsTentative = false;
365
366 if (!OldFSDecl->getInit() &&
367 (OldFSDecl->getStorageClass() == VarDecl::None ||
368 OldFSDecl->getStorageClass() == VarDecl::Static))
369 OldIsTentative = true;
370
371 // FIXME: this check doesn't work (since the initializer hasn't been
372 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
373 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
374 // thrown out the old decl.
375 if (!NewFSDecl->getInit() &&
376 (NewFSDecl->getStorageClass() == VarDecl::None ||
377 NewFSDecl->getStorageClass() == VarDecl::Static))
378 ; // change to NewIsTentative = true; once the code is moved.
379
380 if (NewIsTentative || OldIsTentative)
381 return New;
382 }
383 if (Old->getStorageClass() != VarDecl::Extern &&
384 New->getStorageClass() != VarDecl::Extern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000385 Diag(New->getLocation(), diag::err_redefinition, New->getName());
386 Diag(Old->getLocation(), diag::err_previous_definition);
387 }
388 return New;
389}
390
391/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
392/// no declarator (e.g. "struct foo;") is parsed.
393Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
394 // TODO: emit error on 'int;' or 'const enum foo;'.
395 // TODO: emit error on 'typedef int;'
396 // if (!DS.isMissingDeclaratorOk()) Diag(...);
397
Steve Naroff92199282007-11-17 21:37:36 +0000398 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000399}
400
Steve Naroffd0091aa2008-01-10 22:15:12 +0000401bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000402 // Get the type before calling CheckSingleAssignmentConstraints(), since
403 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000404 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000405
Chris Lattner5cf216b2008-01-04 18:04:52 +0000406 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
407 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
408 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000409}
410
Steve Naroff9e8925e2007-09-04 14:36:54 +0000411bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000412 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000413 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000414 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000415 return true; // types weren't compatible.
416
Steve Naroff9e8925e2007-09-04 14:36:54 +0000417 if (savExpr != expr) // The type was promoted, update initializer list.
418 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000419 return false;
420}
421
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000422bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
423 if (const VariableArrayType *VAT = DeclT->getAsIncompleteArrayType()) {
424 // C99 6.7.8p14. We have an array of character type with unknown size
425 // being initialized to a string literal.
426 llvm::APSInt ConstVal(32);
427 ConstVal = strLiteral->getByteLength() + 1;
428 // Return a new array type (C99 6.7.8p22).
429 DeclT = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
430 ArrayType::Normal, 0);
431 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
432 // C99 6.7.8p14. We have an array of character type with known size.
433 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
434 Diag(strLiteral->getSourceRange().getBegin(),
435 diag::warn_initializer_string_for_char_array_too_long,
436 strLiteral->getSourceRange());
437 } else {
438 assert(0 && "HandleStringLiteralInit(): Invalid array type");
439 }
440 // Set type from "char *" to "constant array of char".
441 strLiteral->setType(DeclT);
442 // For now, we always return false (meaning success).
443 return false;
444}
445
446StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000447 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000448 if (AT && AT->getElementType()->isCharType()) {
449 return dyn_cast<StringLiteral>(Init);
450 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000451 return 0;
452}
453
Steve Naroffa9960332008-01-25 00:51:06 +0000454// CheckInitializerListTypes - Checks the types of elements of an initializer
455// list. This function is recursive: it calls itself to initialize subelements
456// of aggregate types. Note that the topLevel parameter essentially refers to
457// whether this expression "owns" the initializer list passed in, or if this
458// initialization is taking elements out of a parent initializer. Each
459// call to this function adds zero or more to startIndex, reports any errors,
460// and returns true if it found any inconsistent types.
461bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
462 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000463 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000464
465 if (DeclType->isScalarType()) {
466 // The simplest case: initializing a single scalar
467 if (topLevel) {
468 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
469 IList->getSourceRange());
470 }
471 if (startIndex < IList->getNumInits()) {
472 Expr* expr = IList->getInit(startIndex);
473 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
474 // FIXME: Should an error be reported here instead?
475 unsigned newIndex = 0;
476 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
477 } else {
478 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
479 }
480 ++startIndex;
481 }
482 // FIXME: Should an error be reported for empty initializer list + scalar?
483 } else if (DeclType->isVectorType()) {
484 if (startIndex < IList->getNumInits()) {
485 const VectorType *VT = DeclType->getAsVectorType();
486 int maxElements = VT->getNumElements();
487 QualType elementType = VT->getElementType();
488
489 for (int i = 0; i < maxElements; ++i) {
490 // Don't attempt to go past the end of the init list
491 if (startIndex >= IList->getNumInits())
492 break;
493 Expr* expr = IList->getInit(startIndex);
494 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
495 unsigned newIndex = 0;
496 hadError |= CheckInitializerListTypes(SubInitList, elementType,
497 true, newIndex);
498 ++startIndex;
499 } else {
500 hadError |= CheckInitializerListTypes(IList, elementType,
501 false, startIndex);
502 }
503 }
504 }
505 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
506 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000507 if (startIndex < IList->getNumInits() && !topLevel &&
508 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
509 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000510 // We found a compatible struct; per the standard, this initializes the
511 // struct. (The C standard technically says that this only applies for
512 // initializers for declarations with automatic scope; however, this
513 // construct is unambiguous anyway because a struct cannot contain
514 // a type compatible with itself. We'll output an error when we check
515 // if the initializer is constant.)
516 // FIXME: Is a call to CheckSingleInitializer required here?
517 ++startIndex;
518 } else {
519 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffb43eaa52008-02-11 00:06:17 +0000520
Steve Naroff406db932008-02-11 21:52:37 +0000521 // If the record is invalid, some of it's members are invalid. To avoid
522 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffb43eaa52008-02-11 00:06:17 +0000523 if (structDecl->isInvalidDecl())
524 return true;
525
Steve Naroffa9960332008-01-25 00:51:06 +0000526 // If structDecl is a forward declaration, this loop won't do anything;
527 // That's okay, because an error should get printed out elsewhere. It
528 // might be worthwhile to skip over the rest of the initializer, though.
529 int numMembers = structDecl->getNumMembers() -
530 structDecl->hasFlexibleArrayMember();
531 for (int i = 0; i < numMembers; i++) {
532 // Don't attempt to go past the end of the init list
533 if (startIndex >= IList->getNumInits())
534 break;
535 FieldDecl * curField = structDecl->getMember(i);
536 if (!curField->getIdentifier()) {
537 // Don't initialize unnamed fields, e.g. "int : 20;"
538 continue;
539 }
540 QualType fieldType = curField->getType();
541 Expr* expr = IList->getInit(startIndex);
542 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
543 unsigned newStart = 0;
544 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
545 true, newStart);
546 ++startIndex;
547 } else {
548 hadError |= CheckInitializerListTypes(IList, fieldType,
549 false, startIndex);
550 }
551 if (DeclType->isUnionType())
552 break;
553 }
554 // FIXME: Implement flexible array initialization GCC extension (it's a
555 // really messy extension to implement, unfortunately...the necessary
556 // information isn't actually even here!)
557 }
558 } else if (DeclType->isArrayType()) {
559 // Check for the special-case of initializing an array with a string.
560 if (startIndex < IList->getNumInits()) {
561 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
562 DeclType)) {
563 CheckStringLiteralInit(lit, DeclType);
564 ++startIndex;
565 if (topLevel && startIndex < IList->getNumInits()) {
566 // We have leftover initializers; warn
567 Diag(IList->getInit(startIndex)->getLocStart(),
568 diag::err_excess_initializers_in_char_array_initializer,
569 IList->getInit(startIndex)->getSourceRange());
570 }
571 return false;
572 }
573 }
574 int maxElements;
575 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
576 // FIXME: use a proper constant
577 maxElements = 0x7FFFFFFF;
578 // Check for VLAs; in standard C it would be possible to check this
579 // earlier, but I don't know where clang accepts VLAs (gcc accepts
580 // them in all sorts of strange places).
581 if (const Expr *expr = VAT->getSizeExpr()) {
582 Diag(expr->getLocStart(), diag::err_variable_object_no_init,
583 expr->getSourceRange());
584 hadError = true;
585 }
586 } else {
587 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
588 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
589 }
590 QualType elementType = DeclType->getAsArrayType()->getElementType();
591 int numElements = 0;
592 for (int i = 0; i < maxElements; ++i, ++numElements) {
593 // Don't attempt to go past the end of the init list
594 if (startIndex >= IList->getNumInits())
595 break;
596 Expr* expr = IList->getInit(startIndex);
597 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
598 unsigned newIndex = 0;
599 hadError |= CheckInitializerListTypes(SubInitList, elementType,
600 true, newIndex);
601 ++startIndex;
602 } else {
603 hadError |= CheckInitializerListTypes(IList, elementType,
604 false, startIndex);
605 }
606 }
607 if (DeclType->getAsVariableArrayType()) {
608 // If this is an incomplete array type, the actual type needs to
609 // be calculated here
610 if (numElements == 0) {
611 // Sizing an array implicitly to zero is not allowed
612 // (It could in theory be allowed, but it doesn't really matter.)
613 Diag(IList->getLocStart(),
614 diag::err_at_least_one_initializer_needed_to_size_array);
615 hadError = true;
616 } else {
617 llvm::APSInt ConstVal(32);
618 ConstVal = numElements;
619 DeclType = Context.getConstantArrayType(elementType, ConstVal,
620 ArrayType::Normal, 0);
621 }
622 }
623 } else {
624 assert(0 && "Aggregate that isn't a function or array?!");
625 }
626 } else {
627 // In C, all types are either scalars or aggregates, but
628 // additional handling is needed here for C++ (and possibly others?).
629 assert(0 && "Unsupported initializer type");
630 }
631
632 // If this init list is a base list, we set the type; an initializer doesn't
633 // fundamentally have a type, but this makes the ASTs a bit easier to read
634 if (topLevel)
635 IList->setType(DeclType);
636
637 if (topLevel && startIndex < IList->getNumInits()) {
638 // We have leftover initializers; warn
639 Diag(IList->getInit(startIndex)->getLocStart(),
640 diag::warn_excess_initializers,
641 IList->getInit(startIndex)->getSourceRange());
642 }
643 return hadError;
644}
645
646bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000647 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
648 // of unknown size ("[]") or an object type that is not a variable array type.
649 if (const VariableArrayType *VAT = DeclType->getAsVariablyModifiedType())
650 return Diag(VAT->getSizeExpr()->getLocStart(),
651 diag::err_variable_object_no_init,
652 VAT->getSizeExpr()->getSourceRange());
653
Steve Naroff2fdc3742007-12-10 22:44:33 +0000654 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
655 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000656 // FIXME: Handle wide strings
657 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
658 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000659
660 if (DeclType->isArrayType())
661 return Diag(Init->getLocStart(),
662 diag::err_array_init_list_required,
663 Init->getSourceRange());
664
Steve Naroffd0091aa2008-01-10 22:15:12 +0000665 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000666 }
Steve Naroffa9960332008-01-25 00:51:06 +0000667 unsigned newIndex = 0;
668 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Narofff0090632007-09-02 02:04:30 +0000669}
670
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000671Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000672Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000673 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000674 IdentifierInfo *II = D.getIdentifier();
675
Chris Lattnere80a59c2007-07-25 00:24:17 +0000676 // All of these full declarators require an identifier. If it doesn't have
677 // one, the ParsedFreeStandingDeclSpec action should be used.
678 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000679 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000680 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000681 D.getDeclSpec().getSourceRange(), D.getSourceRange());
682 return 0;
683 }
684
Chris Lattner31e05722007-08-26 06:24:45 +0000685 // The scope passed in may not be a decl scope. Zip up the scope tree until
686 // we find one that is.
687 while ((S->getFlags() & Scope::DeclScope) == 0)
688 S = S->getParent();
689
Reid Spencer5f016e22007-07-11 17:01:13 +0000690 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000691 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
692 D.getIdentifierLoc(), S);
Steve Naroffc752d042007-09-13 18:10:37 +0000693 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000694 bool InvalidDecl = false;
695
Chris Lattner41af0932007-11-14 06:34:38 +0000696 QualType R = GetTypeForDeclarator(D, S);
697 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
698
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000700 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 if (!NewTD) return 0;
702
703 // Handle attributes prior to checking for duplicates in MergeVarDecl
704 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
705 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000706 // Merge the decl with the existing one if appropriate. If the decl is
707 // in an outer scope, it isn't the same thing.
708 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
710 if (NewTD == 0) return 0;
711 }
712 New = NewTD;
713 if (S->getParent() == 0) {
714 // C99 6.7.7p2: If a typedef name specifies a variably modified type
715 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000716 if (const VariableArrayType *VAT =
717 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
718 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
719 VAT->getSizeExpr()->getSourceRange());
720 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000721 }
722 }
Chris Lattner41af0932007-11-14 06:34:38 +0000723 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000724 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 switch (D.getDeclSpec().getStorageClassSpec()) {
726 default: assert(0 && "Unknown storage class!");
727 case DeclSpec::SCS_auto:
728 case DeclSpec::SCS_register:
729 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
730 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000731 InvalidDecl = true;
732 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000733 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
734 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
735 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000736 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 }
738
739 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000740 D.getDeclSpec().isInlineSpecified(),
Anders Carlssonf78915f2008-02-15 07:04:12 +0000741 LastDeclarator);
742 // FIXME: Handle attributes.
Nate Begeman1b4e2512007-11-13 22:14:47 +0000743 D.getDeclSpec().clearAttributes();
Reid Spencer5f016e22007-07-11 17:01:13 +0000744
Steve Naroffffce4d52008-01-09 23:34:55 +0000745 // Merge the decl with the existing one if appropriate. Since C functions
746 // are in a flat namespace, make sure we consider decls in outer scopes.
Reid Spencer5f016e22007-07-11 17:01:13 +0000747 if (PrevDecl) {
748 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
749 if (NewFD == 0) return 0;
750 }
751 New = NewFD;
752 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000753 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000754 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
755 D.getIdentifier()->getName());
756 InvalidDecl = true;
757 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000758
759 VarDecl *NewVD;
760 VarDecl::StorageClass SC;
761 switch (D.getDeclSpec().getStorageClassSpec()) {
762 default: assert(0 && "Unknown storage class!");
Steve Naroffd6326c62008-01-25 22:14:40 +0000763 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
764 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
765 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
766 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
767 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
768 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000769 }
770 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000771 // C99 6.9p2: The storage-class specifiers auto and register shall not
772 // appear in the declaration specifiers in an external declaration.
773 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
774 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
775 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000776 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000777 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000778 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000779 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000780 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000781 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000782 // Handle attributes prior to checking for duplicates in MergeVarDecl
783 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
784 D.getAttributes());
785
Steve Naroffffce4d52008-01-09 23:34:55 +0000786 // Merge the decl with the existing one if appropriate. If the decl is
787 // in an outer scope, it isn't the same thing.
788 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000789 NewVD = MergeVarDecl(NewVD, PrevDecl);
790 if (NewVD == 0) return 0;
791 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000792 New = NewVD;
793 }
794
795 // If this has an identifier, add it to the scope stack.
796 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000797 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000798 II->setFETokenInfo(New);
799 S->AddDecl(New);
800 }
Steve Naroff5912a352007-08-28 20:14:24 +0000801 // If any semantic error occurred, mark the decl as invalid.
802 if (D.getInvalidType() || InvalidDecl)
803 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000804
805 return New;
806}
807
Steve Naroffd0091aa2008-01-10 22:15:12 +0000808bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
809 SourceLocation loc;
810 // FIXME: Remove the isReference check and handle assignment to a reference.
811 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
812 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
813 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
814 return true;
815 }
816 return false;
817}
818
Steve Naroffbb204692007-09-12 14:07:44 +0000819void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000820 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000821 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000822 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000823
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000824 // If there is no declaration, there was an error parsing it. Just ignore
825 // the initializer.
826 if (RealDecl == 0) {
827 delete Init;
828 return;
829 }
Steve Naroffbb204692007-09-12 14:07:44 +0000830
Steve Naroff410e3e22007-09-12 20:13:48 +0000831 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
832 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000833 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
834 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000835 RealDecl->setInvalidDecl();
836 return;
837 }
Steve Naroffbb204692007-09-12 14:07:44 +0000838 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +0000839 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000840 QualType DclT = VDecl->getType(), SavT = DclT;
841 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000842 VarDecl::StorageClass SC = BVD->getStorageClass();
843 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000844 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000845 BVD->setInvalidDecl();
846 } else if (!BVD->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000847 if (CheckInitializerTypes(Init, DclT))
848 BVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000849 if (SC == VarDecl::Static) // C99 6.7.8p4.
850 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000851 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000852 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000853 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000854 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000855 if (!FVD->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +0000856 if (CheckInitializerTypes(Init, DclT))
857 FVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000858
859 // C99 6.7.8p4. All file scoped initializers need to be constant.
860 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000861 }
862 // If the type changed, it means we had an incomplete type that was
863 // completed by the initializer. For example:
864 // int ary[] = { 1, 3, 5 };
865 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +0000866 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000867 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +0000868 Init->setType(DclT);
869 }
Steve Naroffbb204692007-09-12 14:07:44 +0000870
871 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000872 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000873 return;
874}
875
Reid Spencer5f016e22007-07-11 17:01:13 +0000876/// The declarators are chained together backwards, reverse the list.
877Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
878 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000879 Decl *GroupDecl = static_cast<Decl*>(group);
880 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000881 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000882
883 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
884 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000885 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000886 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000887 else { // reverse the list.
888 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000889 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000890 Group->setNextDeclarator(NewGroup);
891 NewGroup = Group;
892 Group = Next;
893 }
894 }
895 // Perform semantic analysis that depends on having fully processed both
896 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000897 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000898 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
899 if (!IDecl)
900 continue;
901 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
902 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
903 QualType T = IDecl->getType();
904
905 // C99 6.7.5.2p2: If an identifier is declared to be an object with
906 // static storage duration, it shall not have a variable length array.
907 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
908 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
909 if (VLA->getSizeExpr()) {
910 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
911 IDecl->setInvalidDecl();
912 }
913 }
914 }
915 // Block scope. C99 6.7p7: If an identifier for an object is declared with
916 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
917 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
918 if (T->isIncompleteType()) {
Chris Lattner8b1be772007-12-02 07:50:03 +0000919 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
920 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000921 IDecl->setInvalidDecl();
922 }
923 }
924 // File scope. C99 6.9.2p2: A declaration of an identifier for and
925 // object that has file scope without an initializer, and without a
926 // storage-class specifier or with the storage-class specifier "static",
927 // constitutes a tentative definition. Note: A tentative definition with
928 // external linkage is valid (C99 6.2.2p5).
Steve Naroffd3cd1e52008-01-18 00:39:39 +0000929 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
930 FVD->getStorageClass() == VarDecl::None)) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +0000931 const VariableArrayType *VAT = T->getAsVariableArrayType();
932
933 if (VAT && VAT->getSizeExpr() == 0) {
934 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
935 // array to be completed. Don't issue a diagnostic.
936 } else if (T->isIncompleteType()) {
937 // C99 6.9.2p3: If the declaration of an identifier for an object is
938 // a tentative definition and has internal linkage (C99 6.2.2p3), the
939 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +0000940 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
941 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000942 IDecl->setInvalidDecl();
943 }
944 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000945 }
946 return NewGroup;
947}
Steve Naroffe1223f72007-08-28 03:03:08 +0000948
949// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000950ParmVarDecl *
Nate Begemanbff5f5c2007-11-13 21:49:48 +0000951Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI, Scope *FnScope)
Steve Naroff66499922007-11-12 03:44:46 +0000952{
Reid Spencer5f016e22007-07-11 17:01:13 +0000953 IdentifierInfo *II = PI.Ident;
954 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
955 // Can this happen for params? We already checked that they don't conflict
956 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000957 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000958 PI.IdentLoc, FnScope)) {
959
960 }
961
962 // FIXME: Handle storage class (auto, register). No declarator?
963 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000964
965 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
966 // Doing the promotion here has a win and a loss. The win is the type for
967 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
968 // code generator). The loss is the orginal type isn't preserved. For example:
969 //
970 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
971 // int blockvardecl[5];
972 // sizeof(parmvardecl); // size == 4
973 // sizeof(blockvardecl); // size == 20
974 // }
975 //
976 // For expressions, all implicit conversions are captured using the
977 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
978 //
979 // FIXME: If a source translation tool needs to see the original type, then
980 // we need to consider storing both types (in ParmVarDecl)...
981 //
982 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattner529bd022008-01-02 22:50:48 +0000983 if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
984 // int x[restrict 4] -> int *restrict
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000985 parmDeclType = Context.getPointerType(AT->getElementType());
Chris Lattner529bd022008-01-02 22:50:48 +0000986 parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
987 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000988 parmDeclType = Context.getPointerType(parmDeclType);
989
990 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Anders Carlssonf78915f2008-02-15 07:04:12 +0000991 VarDecl::None, 0);
992 // FIXME: Handle attributes
993
Steve Naroff53a32342007-08-28 18:45:29 +0000994 if (PI.InvalidType)
995 New->setInvalidDecl();
996
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 // If this has an identifier, add it to the scope stack.
998 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000999 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 II->setFETokenInfo(New);
1001 FnScope->AddDecl(New);
1002 }
1003
1004 return New;
1005}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001006
Chris Lattnerb652cea2007-10-09 17:14:05 +00001007Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001008 assert(CurFunctionDecl == 0 && "Function parsing confused");
1009 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1010 "Not a function declarator!");
1011 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1012
1013 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1014 // for a K&R function.
1015 if (!FTI.hasPrototype) {
1016 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1017 if (FTI.ArgInfo[i].TypeInfo == 0) {
1018 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1019 FTI.ArgInfo[i].Ident->getName());
1020 // Implicitly declare the argument as type 'int' for lack of a better
1021 // type.
1022 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
1023 }
1024 }
1025
1026 // Since this is a function definition, act as though we have information
1027 // about the arguments.
1028 FTI.hasPrototype = true;
1029 } else {
1030 // FIXME: Diagnose arguments without names in C.
1031
1032 }
1033
1034 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001035
1036 // See if this is a redefinition.
1037 ScopedDecl *PrevDcl = LookupScopedDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1038 D.getIdentifierLoc(), GlobalScope);
1039 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1040 if (FD->getBody()) {
1041 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1042 D.getIdentifier()->getName());
1043 Diag(FD->getLocation(), diag::err_previous_definition);
1044 }
1045 }
Steve Narofffabbc342008-02-12 01:09:36 +00001046 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
1047 FunctionDecl *FD = dyn_cast<FunctionDecl>(decl);
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001048 assert(FD != 0 && "ActOnDeclarator() didn't return a FunctionDecl");
Reid Spencer5f016e22007-07-11 17:01:13 +00001049 CurFunctionDecl = FD;
1050
1051 // Create Decl objects for each parameter, adding them to the FunctionDecl.
1052 llvm::SmallVector<ParmVarDecl*, 16> Params;
1053
1054 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1055 // no arguments, not a function that takes a single void argument.
1056 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb751c282007-11-28 18:51:29 +00001057 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getQualifiers() &&
1058 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001059 // empty arg list, don't push any params.
1060 } else {
Steve Naroff66499922007-11-12 03:44:46 +00001061 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begemanbff5f5c2007-11-13 21:49:48 +00001062 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroff66499922007-11-12 03:44:46 +00001063 FnBodyScope));
1064 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001065 }
1066
1067 FD->setParams(&Params[0], Params.size());
1068
1069 return FD;
1070}
1071
Steve Naroffd6d054d2007-11-11 23:20:51 +00001072Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1073 Decl *dcl = static_cast<Decl *>(D);
1074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1075 FD->setBody((Stmt*)Body);
1076 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001077 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001078 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001079 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001080 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001081 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001082 // Verify and clean out per-function state.
1083
1084 // Check goto/label use.
1085 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1086 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1087 // Verify that we have no forward references left. If so, there was a goto
1088 // or address of a label taken, but no definition of it. Label fwd
1089 // definitions are indicated with a null substmt.
1090 if (I->second->getSubStmt() == 0) {
1091 LabelStmt *L = I->second;
1092 // Emit error.
1093 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1094
1095 // At this point, we have gotos that use the bogus label. Stitch it into
1096 // the function body so that they aren't leaked and that the AST is well
1097 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001098 if (Body) {
1099 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1100 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1101 } else {
1102 // The whole function wasn't parsed correctly, just delete this.
1103 delete L;
1104 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001105 }
1106 }
1107 LabelMap.clear();
1108
Steve Naroffd6d054d2007-11-11 23:20:51 +00001109 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001110}
1111
Reid Spencer5f016e22007-07-11 17:01:13 +00001112/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1113/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001114ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1115 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001116 if (getLangOptions().C99) // Extension in C99.
1117 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1118 else // Legal in C90, but warn about it.
1119 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1120
1121 // FIXME: handle stuff like:
1122 // void foo() { extern float X(); }
1123 // void bar() { X(); } <-- implicit decl for X in another scope.
1124
1125 // Set a Declarator for the implicit definition: int foo();
1126 const char *Dummy;
1127 DeclSpec DS;
1128 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1129 Error = Error; // Silence warning.
1130 assert(!Error && "Error setting up implicit decl!");
1131 Declarator D(DS, Declarator::BlockContext);
1132 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1133 D.SetIdentifier(&II, Loc);
1134
1135 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +00001136 if (Scope *FnS = S->getFnParent())
1137 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +00001138 while (S->getParent())
1139 S = S->getParent();
1140
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001141 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +00001142}
1143
1144
Chris Lattner41af0932007-11-14 06:34:38 +00001145TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001146 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001147 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001148 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001149
1150 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +00001151 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
1152 T, LastDeclarator);
1153 if (D.getInvalidType())
1154 NewTD->setInvalidDecl();
1155 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001156}
1157
Steve Naroff08d92e42007-09-15 18:49:24 +00001158/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001159/// former case, Name will be non-null. In the later case, Name will be null.
1160/// TagType indicates what kind of tag this is. TK indicates whether this is a
1161/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001162Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001163 SourceLocation KWLoc, IdentifierInfo *Name,
1164 SourceLocation NameLoc, AttributeList *Attr) {
1165 // If this is a use of an existing tag, it must have a name.
1166 assert((Name != 0 || TK == TK_Definition) &&
1167 "Nameless record must be a definition!");
1168
1169 Decl::Kind Kind;
1170 switch (TagType) {
1171 default: assert(0 && "Unknown tag type!");
1172 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1173 case DeclSpec::TST_union: Kind = Decl::Union; break;
1174//case DeclSpec::TST_class: Kind = Decl::Class; break;
1175 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1176 }
1177
1178 // If this is a named struct, check to see if there was a previous forward
1179 // declaration or definition.
1180 if (TagDecl *PrevDecl =
1181 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1182 NameLoc, S))) {
1183
1184 // If this is a use of a previous tag, or if the tag is already declared in
1185 // the same scope (so that the definition/declaration completes or
1186 // rementions the tag), reuse the decl.
1187 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1188 // Make sure that this wasn't declared as an enum and now used as a struct
1189 // or something similar.
1190 if (PrevDecl->getKind() != Kind) {
1191 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1192 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1193 }
1194
1195 // If this is a use or a forward declaration, we're good.
1196 if (TK != TK_Definition)
1197 return PrevDecl;
1198
1199 // Diagnose attempts to redefine a tag.
1200 if (PrevDecl->isDefinition()) {
1201 Diag(NameLoc, diag::err_redefinition, Name->getName());
1202 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1203 // If this is a redefinition, recover by making this struct be
1204 // anonymous, which will make any later references get the previous
1205 // definition.
1206 Name = 0;
1207 } else {
1208 // Okay, this is definition of a previously declared or referenced tag.
1209 // Move the location of the decl to be the definition site.
1210 PrevDecl->setLocation(NameLoc);
1211 return PrevDecl;
1212 }
1213 }
1214 // If we get here, this is a definition of a new struct type in a nested
1215 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1216 // type.
1217 }
1218
1219 // If there is an identifier, use the location of the identifier as the
1220 // location of the decl, otherwise use the location of the struct/union
1221 // keyword.
1222 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1223
1224 // Otherwise, if this is the first time we've seen this tag, create the decl.
1225 TagDecl *New;
1226 switch (Kind) {
1227 default: assert(0 && "Unknown tag kind!");
1228 case Decl::Enum:
1229 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1230 // enum X { A, B, C } D; D should chain to X.
1231 New = new EnumDecl(Loc, Name, 0);
1232 // If this is an undefined enum, warn.
1233 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1234 break;
1235 case Decl::Union:
1236 case Decl::Struct:
1237 case Decl::Class:
1238 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1239 // struct X { int A; } D; D should chain to X.
1240 New = new RecordDecl(Kind, Loc, Name, 0);
1241 break;
1242 }
1243
1244 // If this has an identifier, add it to the scope stack.
1245 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001246 // The scope passed in may not be a decl scope. Zip up the scope tree until
1247 // we find one that is.
1248 while ((S->getFlags() & Scope::DeclScope) == 0)
1249 S = S->getParent();
1250
1251 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001252 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001253 Name->setFETokenInfo(New);
1254 S->AddDecl(New);
1255 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001256
Reid Spencer5f016e22007-07-11 17:01:13 +00001257 return New;
1258}
1259
Steve Naroff08d92e42007-09-15 18:49:24 +00001260/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001261/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001262Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 SourceLocation DeclStart,
1264 Declarator &D, ExprTy *BitfieldWidth) {
1265 IdentifierInfo *II = D.getIdentifier();
1266 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 SourceLocation Loc = DeclStart;
1268 if (II) Loc = D.getIdentifierLoc();
1269
1270 // FIXME: Unnamed fields can be handled in various different ways, for
1271 // example, unnamed unions inject all members into the struct namespace!
1272
1273
1274 if (BitWidth) {
1275 // TODO: Validate.
1276 //printf("WARNING: BITFIELDS IGNORED!\n");
1277
1278 // 6.7.2.1p3
1279 // 6.7.2.1p4
1280
1281 } else {
1282 // Not a bitfield.
1283
1284 // validate II.
1285
1286 }
1287
1288 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001289 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1290 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001291
Reid Spencer5f016e22007-07-11 17:01:13 +00001292 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1293 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001294 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1295 Diag(Loc, diag::err_typecheck_illegal_vla,
1296 VAT->getSizeExpr()->getSourceRange());
1297 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001299 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001300 FieldDecl *NewFD;
1301
1302 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patel54e62352007-11-01 16:29:56 +00001303 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001304 else if (isa<ObjCInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1305 isa<ObjCImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
1306 isa<ObjCCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroffddd600f2007-11-14 14:15:31 +00001307 // FIXME: ivars are currently used to model properties, and
1308 // properties can appear within a protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001309 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1310 isa<ObjCProtocolDecl>(static_cast<Decl *>(TagDecl)))
1311 NewFD = new ObjCIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001312 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001313 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001314
Steve Naroff5912a352007-08-28 20:14:24 +00001315 if (D.getInvalidType() || InvalidDecl)
1316 NewFD->setInvalidDecl();
1317 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001318}
1319
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001320/// TranslateIvarVisibility - Translate visibility from a token ID to an
1321/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001322static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001323TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001324 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001325 case tok::objc_private: return ObjCIvarDecl::Private;
1326 case tok::objc_public: return ObjCIvarDecl::Public;
1327 case tok::objc_protected: return ObjCIvarDecl::Protected;
1328 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001329 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001330 }
1331}
1332
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001333void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001334 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001335 DeclTy **Fields, unsigned NumFields,
Steve Naroff60fccee2007-10-29 21:38:07 +00001336 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff08d92e42007-09-15 18:49:24 +00001337 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001338 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1339 assert(EnclosingDecl && "missing record or interface decl");
1340 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1341
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001342 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001343 // Diagnose code like:
1344 // struct S { struct S {} X; };
1345 // We discover this when we complete the outer S. Reject and ignore the
1346 // outer S.
1347 Diag(Record->getLocation(), diag::err_nested_redefinition,
1348 Record->getKindName());
1349 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001350 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 return;
1352 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 // Verify that all the fields are okay.
1354 unsigned NumNamedMembers = 0;
1355 llvm::SmallVector<FieldDecl*, 32> RecFields;
1356 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001357
Reid Spencer5f016e22007-07-11 17:01:13 +00001358 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001359
Steve Naroff74216642007-09-14 22:20:54 +00001360 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1361 assert(FD && "missing field decl");
1362
1363 // Remember all fields.
1364 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001365
1366 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001367 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001368
Steve Narofff13271f2007-09-14 23:09:53 +00001369 // If we have visibility info, make sure the AST is set accordingly.
1370 if (visibility)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001371 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001372 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001373
Reid Spencer5f016e22007-07-11 17:01:13 +00001374 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001375 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001376 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001378 FD->setInvalidDecl();
1379 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001380 continue;
1381 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001382 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1383 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001384 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001385 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001386 FD->setInvalidDecl();
1387 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001388 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001389 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 if (i != NumFields-1 || // ... that the last member ...
1391 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001392 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001394 FD->setInvalidDecl();
1395 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001396 continue;
1397 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001398 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1400 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001401 FD->setInvalidDecl();
1402 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 continue;
1404 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001405 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001406 if (Record)
1407 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001408 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1410 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001411 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1413 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001414 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001415 Record->setHasFlexibleArrayMember(true);
1416 } else {
1417 // If this is a struct/class and this is not the last element, reject
1418 // it. Note that GCC supports variable sized arrays in the middle of
1419 // structures.
1420 if (i != NumFields-1) {
1421 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1422 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001423 FD->setInvalidDecl();
1424 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 continue;
1426 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001427 // We support flexible arrays at the end of structs in other structs
1428 // as an extension.
1429 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1430 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001431 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001432 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001433 }
1434 }
1435 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001436 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001437 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001438 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1439 FD->getName());
1440 FD->setInvalidDecl();
1441 EnclosingDecl->setInvalidDecl();
1442 continue;
1443 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 // Keep track of the number of named members.
1445 if (IdentifierInfo *II = FD->getIdentifier()) {
1446 // Detect duplicate member names.
1447 if (!FieldIDs.insert(II)) {
1448 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1449 // Find the previous decl.
1450 SourceLocation PrevLoc;
1451 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1452 assert(i != e && "Didn't find previous def!");
1453 if (RecFields[i]->getIdentifier() == II) {
1454 PrevLoc = RecFields[i]->getLocation();
1455 break;
1456 }
1457 }
1458 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001459 FD->setInvalidDecl();
1460 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001461 continue;
1462 }
1463 ++NumNamedMembers;
1464 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001465 }
1466
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00001468 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001469 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00001470 Consumer.HandleTagDeclDefinition(Record);
1471 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00001472 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1473 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1474 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1475 else if (ObjCImplementationDecl *IMPDecl =
1476 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001477 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1478 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001479 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001480 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001481 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001482}
1483
Steve Naroff08d92e42007-09-15 18:49:24 +00001484Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001485 DeclTy *lastEnumConst,
1486 SourceLocation IdLoc, IdentifierInfo *Id,
1487 SourceLocation EqualLoc, ExprTy *val) {
1488 theEnumDecl = theEnumDecl; // silence unused warning.
1489 EnumConstantDecl *LastEnumConst =
1490 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1491 Expr *Val = static_cast<Expr*>(val);
1492
Chris Lattner31e05722007-08-26 06:24:45 +00001493 // The scope passed in may not be a decl scope. Zip up the scope tree until
1494 // we find one that is.
1495 while ((S->getFlags() & Scope::DeclScope) == 0)
1496 S = S->getParent();
1497
Reid Spencer5f016e22007-07-11 17:01:13 +00001498 // Verify that there isn't already something declared with this name in this
1499 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001500 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1501 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 if (S->isDeclScope(PrevDecl)) {
1503 if (isa<EnumConstantDecl>(PrevDecl))
1504 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1505 else
1506 Diag(IdLoc, diag::err_redefinition, Id->getName());
1507 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1508 // FIXME: Don't leak memory: delete Val;
1509 return 0;
1510 }
1511 }
1512
1513 llvm::APSInt EnumVal(32);
1514 QualType EltTy;
1515 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001516 // Make sure to promote the operand type to int.
1517 UsualUnaryConversions(Val);
1518
Reid Spencer5f016e22007-07-11 17:01:13 +00001519 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1520 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001521 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001522 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1523 Id->getName());
1524 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001525 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001526 } else {
1527 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001529 }
1530
1531 if (!Val) {
1532 if (LastEnumConst) {
1533 // Assign the last value + 1.
1534 EnumVal = LastEnumConst->getInitVal();
1535 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001536
1537 // Check for overflow on increment.
1538 if (EnumVal < LastEnumConst->getInitVal())
1539 Diag(IdLoc, diag::warn_enum_value_overflow);
1540
Chris Lattnerb7416f92007-08-27 17:37:24 +00001541 EltTy = LastEnumConst->getType();
1542 } else {
1543 // First value, set to zero.
1544 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001545 EnumVal.zextOrTrunc(
1546 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001547 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 }
1549
Reid Spencer5f016e22007-07-11 17:01:13 +00001550 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1551 LastEnumConst);
1552
1553 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001554 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 Id->setFETokenInfo(New);
1556 S->AddDecl(New);
1557 return New;
1558}
1559
Steve Naroff08d92e42007-09-15 18:49:24 +00001560void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 DeclTy **Elements, unsigned NumElements) {
1562 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1563 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1564
Chris Lattnere37f0be2007-08-28 05:10:31 +00001565 // TODO: If the result value doesn't fit in an int, it must be a long or long
1566 // long value. ISO C does not support this, but GCC does as an extension,
1567 // emit a warning.
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001568 unsigned IntWidth =
1569 Context.Target.getIntWidth(Context.getFullLoc(Enum->getLocation()));
Chris Lattnere37f0be2007-08-28 05:10:31 +00001570
1571
Chris Lattnerac609682007-08-28 06:15:15 +00001572 // Verify that all the values are okay, compute the size of the values, and
1573 // reverse the list.
1574 unsigned NumNegativeBits = 0;
1575 unsigned NumPositiveBits = 0;
1576
1577 // Keep track of whether all elements have type int.
1578 bool AllElementsInt = true;
1579
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 EnumConstantDecl *EltList = 0;
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.
Chris Lattner211a30e2007-08-28 05:27:00 +00001585
1586 // If the enum value doesn't fit in an int, emit an extension warning.
1587 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1588 "Should have promoted value to int");
1589 const llvm::APSInt &InitVal = ECD->getInitVal();
1590 if (InitVal.getBitWidth() > IntWidth) {
1591 llvm::APSInt V(InitVal);
1592 V.trunc(IntWidth);
1593 V.extend(InitVal.getBitWidth());
1594 if (V != InitVal)
1595 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1596 InitVal.toString());
1597 }
Chris Lattnerac609682007-08-28 06:15:15 +00001598
1599 // Keep track of the size of positive and negative values.
1600 if (InitVal.isUnsigned() || !InitVal.isNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001601 NumPositiveBits = std::max(NumPositiveBits,
1602 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001603 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001604 NumNegativeBits = std::max(NumNegativeBits,
1605 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001606
Chris Lattnerac609682007-08-28 06:15:15 +00001607 // Keep track of whether every enum element has type int (very commmon).
1608 if (AllElementsInt)
1609 AllElementsInt = ECD->getType() == Context.IntTy;
1610
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 ECD->setNextDeclarator(EltList);
1612 EltList = ECD;
1613 }
1614
Chris Lattnerac609682007-08-28 06:15:15 +00001615 // Figure out the type that should be used for this enum.
1616 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1617 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001618 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001619
1620 if (NumNegativeBits) {
1621 // If there is a negative value, figure out the smallest integer type (of
1622 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001623 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001624 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001625 BestWidth = IntWidth;
1626 } else {
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001627 BestWidth =
1628 Context.Target.getLongWidth(Context.getFullLoc(Enum->getLocation()));
1629
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001630 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001631 BestType = Context.LongTy;
1632 else {
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001633 BestWidth = Context.Target.getLongLongWidth(
1634 Context.getFullLoc(Enum->getLocation()));
1635
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001636 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001637 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1638 BestType = Context.LongLongTy;
1639 }
1640 }
1641 } else {
1642 // If there is no negative value, figure out which of uint, ulong, ulonglong
1643 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001644 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001645 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001646 BestWidth = IntWidth;
1647 } else if (NumPositiveBits <=
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001648 (BestWidth = Context.Target.getLongWidth(
1649 Context.getFullLoc(Enum->getLocation()))))
1650
Chris Lattnerac609682007-08-28 06:15:15 +00001651 BestType = Context.UnsignedLongTy;
1652 else {
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001653 BestWidth =
1654 Context.Target.getLongLongWidth(Context.getFullLoc(Enum->getLocation()));
1655
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001656 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001657 "How could an initializer get larger than ULL?");
1658 BestType = Context.UnsignedLongLongTy;
1659 }
1660 }
1661
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001662 // Loop over all of the enumerator constants, changing their types to match
1663 // the type of the enum if needed.
1664 for (unsigned i = 0; i != NumElements; ++i) {
1665 EnumConstantDecl *ECD =
1666 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1667 if (!ECD) continue; // Already issued a diagnostic.
1668
1669 // Standard C says the enumerators have int type, but we allow, as an
1670 // extension, the enumerators to be larger than int size. If each
1671 // enumerator value fits in an int, type it as an int, otherwise type it the
1672 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1673 // that X has type 'int', not 'unsigned'.
1674 if (ECD->getType() == Context.IntTy)
1675 continue; // Already int type.
1676
1677 // Determine whether the value fits into an int.
1678 llvm::APSInt InitVal = ECD->getInitVal();
1679 bool FitsInInt;
1680 if (InitVal.isUnsigned() || !InitVal.isNegative())
1681 FitsInInt = InitVal.getActiveBits() < IntWidth;
1682 else
1683 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1684
1685 // If it fits into an integer type, force it. Otherwise force it to match
1686 // the enum decl type.
1687 QualType NewTy;
1688 unsigned NewWidth;
1689 bool NewSign;
1690 if (FitsInInt) {
1691 NewTy = Context.IntTy;
1692 NewWidth = IntWidth;
1693 NewSign = true;
1694 } else if (ECD->getType() == BestType) {
1695 // Already the right type!
1696 continue;
1697 } else {
1698 NewTy = BestType;
1699 NewWidth = BestWidth;
1700 NewSign = BestType->isSignedIntegerType();
1701 }
1702
1703 // Adjust the APSInt value.
1704 InitVal.extOrTrunc(NewWidth);
1705 InitVal.setIsSigned(NewSign);
1706 ECD->setInitVal(InitVal);
1707
1708 // Adjust the Expr initializer and type.
1709 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1710 ECD->setType(NewTy);
1711 }
Chris Lattnerac609682007-08-28 06:15:15 +00001712
Chris Lattnere00b18c2007-08-28 18:24:31 +00001713 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00001714 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00001715}
1716
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001717Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1718 ExprTy *expr) {
1719 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1720
1721 return new FileScopeAsmDecl(Loc, AsmString);
1722}
1723
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001724Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
1725 SourceLocation LBrace,
1726 SourceLocation RBrace,
1727 const char *Lang,
1728 unsigned StrSize,
1729 DeclTy *D) {
1730 LinkageSpecDecl::LanguageIDs Language;
1731 Decl *dcl = static_cast<Decl *>(D);
1732 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1733 Language = LinkageSpecDecl::lang_c;
1734 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1735 Language = LinkageSpecDecl::lang_cxx;
1736 else {
1737 Diag(Loc, diag::err_bad_language);
1738 return 0;
1739 }
1740
1741 // FIXME: Add all the various semantics of linkage specifications
1742 return new LinkageSpecDecl(Loc, Language, dcl);
1743}
1744
Reid Spencer5f016e22007-07-11 17:01:13 +00001745void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001746 const char *attrName = rawAttr->getAttributeName()->getName();
1747 unsigned attrLen = rawAttr->getAttributeName()->getLength();
1748
Anders Carlssonabf5ad02007-12-19 17:43:24 +00001749 // Normalize the attribute name, __foo__ becomes foo.
1750 if (attrLen > 4 && attrName[0] == '_' && attrName[1] == '_' &&
1751 attrName[attrLen - 2] == '_' && attrName[attrLen - 1] == '_') {
1752 attrName += 2;
1753 attrLen -= 4;
1754 }
1755
1756 if (attrLen == 11 && !memcmp(attrName, "vector_size", 11)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001757 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1758 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1759 if (!newType.isNull()) // install the new vector type into the decl
1760 vDecl->setType(newType);
1761 }
1762 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1763 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1764 rawAttr);
1765 if (!newType.isNull()) // install the new vector type into the decl
1766 tDecl->setUnderlyingType(newType);
1767 }
Anders Carlssonabf5ad02007-12-19 17:43:24 +00001768 } else if (attrLen == 15 && !memcmp(attrName, "ocu_vector_type", 15)) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001769 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1770 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1771 else
Steve Naroff73322922007-07-18 18:00:27 +00001772 Diag(rawAttr->getAttributeLoc(),
1773 diag::err_typecheck_ocu_vector_not_typedef);
Christopher Lambebb97e92008-02-04 02:31:56 +00001774 } else if (attrLen == 13 && !memcmp(attrName, "address_space", 13)) {
1775 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1776 QualType newType = HandleAddressSpaceTypeAttribute(
1777 tDecl->getUnderlyingType(),
1778 rawAttr);
1779 if (!newType.isNull()) // install the new addr spaced type into the decl
1780 tDecl->setUnderlyingType(newType);
1781 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1782 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
1783 rawAttr);
1784 if (!newType.isNull()) // install the new addr spaced type into the decl
1785 vDecl->setType(newType);
1786 }
Anders Carlsson78aaae92007-12-19 07:19:40 +00001787 } else if (attrLen == 7 && !memcmp(attrName, "aligned", 7)) {
1788 HandleAlignedAttribute(New, rawAttr);
Steve Naroff73322922007-07-18 18:00:27 +00001789 }
Anders Carlsson78aaae92007-12-19 07:19:40 +00001790
Reid Spencer5f016e22007-07-11 17:01:13 +00001791 // FIXME: add other attributes...
1792}
1793
1794void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1795 AttributeList *declarator_postfix) {
1796 while (declspec_prefix) {
1797 HandleDeclAttribute(New, declspec_prefix);
1798 declspec_prefix = declspec_prefix->getNext();
1799 }
1800 while (declarator_postfix) {
1801 HandleDeclAttribute(New, declarator_postfix);
1802 declarator_postfix = declarator_postfix->getNext();
1803 }
1804}
1805
Christopher Lambebb97e92008-02-04 02:31:56 +00001806QualType Sema::HandleAddressSpaceTypeAttribute(QualType curType,
1807 AttributeList *rawAttr) {
1808 // check the attribute arugments.
1809 if (rawAttr->getNumArgs() != 1) {
1810 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1811 std::string("1"));
1812 return QualType();
1813 }
1814 Expr *addrSpaceExpr = static_cast<Expr *>(rawAttr->getArg(0));
1815 llvm::APSInt addrSpace(32);
1816 if (!addrSpaceExpr->isIntegerConstantExpr(addrSpace, Context)) {
1817 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_address_space_not_int,
1818 addrSpaceExpr->getSourceRange());
1819 return QualType();
1820 }
1821 unsigned addressSpace = static_cast<unsigned>(addrSpace.getZExtValue());
1822
1823 // Zero is the default memory space, so no qualification is needed
1824 if (addressSpace == 0)
1825 return curType;
1826
1827 // TODO: Should we convert contained types of address space
1828 // qualified types here or or where they directly participate in conversions
1829 // (i.e. elsewhere)
1830
1831 return Context.getASQualType(curType, addressSpace);
1832}
1833
Steve Naroffbea0b342007-07-29 16:33:31 +00001834void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1835 AttributeList *rawAttr) {
1836 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00001837 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00001838 if (rawAttr->getNumArgs() != 1) {
1839 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1840 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001841 return;
Steve Naroff73322922007-07-18 18:00:27 +00001842 }
1843 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1844 llvm::APSInt vecSize(32);
1845 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1846 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1847 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001848 return;
Steve Naroff73322922007-07-18 18:00:27 +00001849 }
1850 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1851 // in conjunction with complex types (pointers, arrays, functions, etc.).
1852 Type *canonType = curType.getCanonicalType().getTypePtr();
1853 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1854 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1855 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001856 return;
Steve Naroff73322922007-07-18 18:00:27 +00001857 }
1858 // unlike gcc's vector_size attribute, the size is specified as the
1859 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001860 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001861
1862 if (vectorSize == 0) {
1863 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1864 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001865 return;
Steve Naroff73322922007-07-18 18:00:27 +00001866 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001867 // Instantiate/Install the vector type, the number of elements is > 0.
1868 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1869 // Remember this typedef decl, we will need it later for diagnostics.
1870 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001871}
1872
Reid Spencer5f016e22007-07-11 17:01:13 +00001873QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001874 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001875 // check the attribute arugments.
1876 if (rawAttr->getNumArgs() != 1) {
1877 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1878 std::string("1"));
1879 return QualType();
1880 }
1881 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1882 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001883 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001884 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1885 sizeExpr->getSourceRange());
1886 return QualType();
1887 }
1888 // navigate to the base type - we need to provide for vector pointers,
1889 // vector arrays, and functions returning vectors.
1890 Type *canonType = curType.getCanonicalType().getTypePtr();
1891
Steve Naroff73322922007-07-18 18:00:27 +00001892 if (canonType->isPointerType() || canonType->isArrayType() ||
1893 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00001894 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00001895 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1896 do {
1897 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1898 canonType = PT->getPointeeType().getTypePtr();
1899 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1900 canonType = AT->getElementType().getTypePtr();
1901 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1902 canonType = FT->getResultType().getTypePtr();
1903 } while (canonType->isPointerType() || canonType->isArrayType() ||
1904 canonType->isFunctionType());
1905 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001906 }
1907 // the base type must be integer or float.
1908 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1909 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1910 curType.getCanonicalType().getAsString());
1911 return QualType();
1912 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00001913 unsigned typeSize = static_cast<unsigned>(
1914 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001915 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001916 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00001917
1918 // the vector size needs to be an integral multiple of the type size.
1919 if (vectorSize % typeSize) {
1920 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1921 sizeExpr->getSourceRange());
1922 return QualType();
1923 }
1924 if (vectorSize == 0) {
1925 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1926 sizeExpr->getSourceRange());
1927 return QualType();
1928 }
1929 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1930 // the number of elements to be a power of two (unlike GCC).
1931 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00001932 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001933}
1934
Anders Carlsson78aaae92007-12-19 07:19:40 +00001935void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
1936{
1937 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00001938 if (rawAttr->getNumArgs() > 1) {
Anders Carlsson78aaae92007-12-19 07:19:40 +00001939 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1940 std::string("1"));
1941 return;
1942 }
Eli Friedman4ca08672008-01-30 17:38:42 +00001943
Devang Patel6c751c22008-01-30 18:00:07 +00001944 // TODO: We probably need to actually do something with aligned attribute.
Eli Friedman4ca08672008-01-30 17:38:42 +00001945 if (rawAttr->getNumArgs() == 0)
1946 return;
1947
Anders Carlsson78aaae92007-12-19 07:19:40 +00001948 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
1949 llvm::APSInt alignment(32);
1950 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
1951 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1952 alignmentExpr->getSourceRange());
1953 return;
1954 }
1955}