blob: 3eb752dcf4e0aa49dcf6347c626965b2b08f729c [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"
17#include "clang/AST/Builtins.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/Type.h"
21#include "clang/Parse/DeclSpec.h"
22#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000025#include "clang/Basic/SourceManager.h"
26// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000027#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000028#include "clang/Lex/HeaderSearch.h"
Steve Naroff563477d2007-09-18 23:55:05 +000029#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000031#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
Reid Spencer5f016e22007-07-11 17:01:13 +000034Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000035 Decl *IIDecl = II.getFETokenInfo<Decl>();
36 // Find first occurance of none-tagged declaration
37 while(IIDecl && IIDecl->getIdentifierNamespace() != Decl::IDNS_Ordinary)
38 IIDecl = cast<ScopedDecl>(IIDecl)->getNext();
39 if (!IIDecl)
40 return 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000041 if (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000042 return IIDecl;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000043 if (ObjCCompatibleAliasDecl *ADecl =
44 dyn_cast<ObjCCompatibleAliasDecl>(IIDecl))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000045 return ADecl->getClassInterface();
Steve Naroff3536b442007-09-06 21:24:23 +000046 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000047}
48
Steve Naroffb216c882007-10-09 22:01:59 +000049void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000050 if (S->decl_empty()) return;
51 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
52
Reid Spencer5f016e22007-07-11 17:01:13 +000053 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
54 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000055 Decl *TmpD = static_cast<Decl*>(*I);
56 assert(TmpD && "This decl didn't get pushed??");
57 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
58 assert(D && "This decl isn't a ScopedDecl?");
59
Reid Spencer5f016e22007-07-11 17:01:13 +000060 IdentifierInfo *II = D->getIdentifier();
61 if (!II) continue;
62
63 // Unlink this decl from the identifier. Because the scope contains decls
64 // in an unordered collection, and because we have multiple identifier
65 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
66 if (II->getFETokenInfo<Decl>() == D) {
67 // Normal case, no multiple decls in different namespaces.
68 II->setFETokenInfo(D->getNext());
69 } else {
70 // Scan ahead. There are only three namespaces in C, so this loop can
71 // never execute more than 3 times.
Steve Naroffc752d042007-09-13 18:10:37 +000072 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +000073 while (SomeDecl->getNext() != D) {
74 SomeDecl = SomeDecl->getNext();
75 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
76 }
77 SomeDecl->setNext(D->getNext());
78 }
79
80 // This will have to be revisited for C++: there we want to nest stuff in
81 // namespace decls etc. Even for C, we might want a top-level translation
82 // unit decl or something.
83 if (!CurFunctionDecl)
84 continue;
85
86 // Chain this decl to the containing function, it now owns the memory for
87 // the decl.
88 D->setNext(CurFunctionDecl->getDeclChain());
89 CurFunctionDecl->setDeclChain(D);
90 }
91}
92
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +000093/// LookupInterfaceDecl - Lookup interface declaration in the scope chain.
94/// Return the first declaration found (which may or may not be a class
Fariborz Jahanian3fe44e42007-10-12 19:53:08 +000095/// declaration. Caller is responsible for handling the none-class case.
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +000096/// Bypassing the alias of a class by returning the aliased class.
97ScopedDecl *Sema::LookupInterfaceDecl(IdentifierInfo *ClassName) {
98 ScopedDecl *IDecl;
99 // Scan up the scope chain looking for a decl that matches this identifier
100 // that is in the appropriate namespace.
101 for (IDecl = ClassName->getFETokenInfo<ScopedDecl>(); IDecl;
102 IDecl = IDecl->getNext())
103 if (IDecl->getIdentifierNamespace() == Decl::IDNS_Ordinary)
104 break;
105
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000106 if (ObjCCompatibleAliasDecl *ADecl =
107 dyn_cast_or_null<ObjCCompatibleAliasDecl>(IDecl))
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000108 return ADecl->getClassInterface();
109 return IDecl;
110}
111
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000112/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +0000113/// return 0 if one not found.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000114ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000115 ScopedDecl *IdDecl = LookupInterfaceDecl(Id);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000116 return cast_or_null<ObjCInterfaceDecl>(IdDecl);
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +0000117}
118
Reid Spencer5f016e22007-07-11 17:01:13 +0000119/// LookupScopedDecl - Look up the inner-most declaration in the specified
120/// namespace.
Steve Naroffc752d042007-09-13 18:10:37 +0000121ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
122 SourceLocation IdLoc, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 if (II == 0) return 0;
124 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
125
126 // Scan up the scope chain looking for a decl that matches this identifier
127 // that is in the appropriate namespace. This search should not take long, as
128 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffc752d042007-09-13 18:10:37 +0000129 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +0000130 if (D->getIdentifierNamespace() == NS)
131 return D;
132
133 // If we didn't find a use of this identifier, and if the identifier
134 // corresponds to a compiler builtin, create the decl object for the builtin
135 // now, injecting it into translation unit scope, and return it.
136 if (NS == Decl::IDNS_Ordinary) {
137 // If this is a builtin on some other target, or if this builtin varies
138 // across targets (e.g. in type), emit a diagnostic and mark the translation
139 // unit non-portable for using it.
140 if (II->isNonPortableBuiltin()) {
141 // Only emit this diagnostic once for this builtin.
142 II->setNonPortableBuiltin(false);
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000143 Context.Target.DiagnoseNonPortability(Context.getFullLoc(IdLoc),
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 diag::port_target_builtin_use);
145 }
146 // If this is a builtin on this (or all) targets, create the decl.
147 if (unsigned BuiltinID = II->getBuiltinID())
148 return LazilyCreateBuiltin(II, BuiltinID, S);
149 }
150 return 0;
151}
152
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000153void Sema::InitBuiltinVaListType()
154{
155 if (!Context.getBuiltinVaListType().isNull())
156 return;
157
158 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
159 ScopedDecl *VaDecl = LookupScopedDecl(VaIdent, Decl::IDNS_Ordinary,
160 SourceLocation(), TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000161 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000162 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
163}
164
Reid Spencer5f016e22007-07-11 17:01:13 +0000165/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
166/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000167ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
168 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 Builtin::ID BID = (Builtin::ID)bid;
170
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000171 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson793680e2007-10-12 23:56:29 +0000172 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000173 BID == Builtin::BI__builtin_va_end)
174 InitBuiltinVaListType();
175
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000176 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Reid Spencer5f016e22007-07-11 17:01:13 +0000177 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000178 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000179
180 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000181 if (Scope *FnS = S->getFnParent())
182 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 while (S->getParent())
184 S = S->getParent();
185 S->AddDecl(New);
186
187 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000188 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000189 // Scan until we find the last (outermost) decl in the id chain.
190 while (LastDecl->getNext())
191 LastDecl = LastDecl->getNext();
192 // Insert before (outside) it.
193 LastDecl->setNext(New);
194 } else {
195 II->setFETokenInfo(New);
196 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000197 return New;
198}
199
200/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
201/// and scope as a previous declaration 'Old'. Figure out how to resolve this
202/// situation, merging decls or emitting diagnostics as appropriate.
203///
Steve Naroff8e74c932007-09-13 21:41:19 +0000204TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000205 // Verify the old decl was also a typedef.
206 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
207 if (!Old) {
208 Diag(New->getLocation(), diag::err_redefinition_different_kind,
209 New->getName());
210 Diag(OldD->getLocation(), diag::err_previous_definition);
211 return New;
212 }
213
Steve Naroff8ee529b2007-10-31 18:42:27 +0000214 // Allow multiple definitions for ObjC built-in typedefs.
215 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000216 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000217 return Old;
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000218
219 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
220 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
221 // *either* declaration is in a system header. The code below implements
222 // this adhoc compatibility rule. FIXME: The following code will not
223 // work properly when compiling ".i" files (containing preprocessed output).
224 SourceManager &SrcMgr = Context.getSourceManager();
225 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
226 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
227 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
228 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
229 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
230
231 if (OldDirType == DirectoryLookup::ExternCSystemHeaderDir ||
232 NewDirType == DirectoryLookup::ExternCSystemHeaderDir)
233 return New;
Steve Naroff8ee529b2007-10-31 18:42:27 +0000234
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
236 // TODO: This is totally simplistic. It should handle merging functions
237 // together etc, merging extern int X; int X; ...
238 Diag(New->getLocation(), diag::err_redefinition, New->getName());
239 Diag(Old->getLocation(), diag::err_previous_definition);
240 return New;
241}
242
243/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
244/// and scope as a previous declaration 'Old'. Figure out how to resolve this
245/// situation, merging decls or emitting diagnostics as appropriate.
246///
Steve Naroff8e74c932007-09-13 21:41:19 +0000247FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 // Verify the old decl was also a function.
249 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
250 if (!Old) {
251 Diag(New->getLocation(), diag::err_redefinition_different_kind,
252 New->getName());
253 Diag(OldD->getLocation(), diag::err_previous_definition);
254 return New;
255 }
256
Chris Lattner55196442007-11-20 19:04:50 +0000257 QualType OldQType = Old->getCanonicalType();
258 QualType NewQType = New->getCanonicalType();
259
260 // This is not right, but it's a start.
261 // If Old is a function prototype with no defined arguments we only compare
262 // the return type; If arguments are defined on the prototype we validate the
263 // entire function type.
264 // FIXME: We should link up decl objects here.
265 if (Old->getBody() == 0) {
266 if (OldQType.getTypePtr()->getTypeClass() == Type::FunctionNoProto &&
267 Old->getResultType() == New->getResultType())
268 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +0000269 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000270 // Function types need to be compatible, not identical. This handles
271 // duplicate function decls like "void f(int); void f(enum X);" properly.
272 if (Context.functionTypesAreCompatible(OldQType, NewQType))
273 return New;
Chris Lattnere3995fe2007-11-06 06:07:26 +0000274
Steve Naroff837618c2008-01-16 15:01:34 +0000275 // A function that has already been declared has been redeclared or defined
276 // with a different type- show appropriate diagnostic
277 diag::kind PrevDiag = Old->getBody() ? diag::err_previous_definition :
278 diag::err_previous_declaration;
279
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
281 // TODO: This is totally simplistic. It should handle merging functions
282 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000283 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
284 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000285 return New;
286}
287
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000288
289/// hasUndefinedLength - Used by equivalentArrayTypes to determine whether the
290/// the outermost VariableArrayType has no size defined.
291static bool hasUndefinedLength(const ArrayType *Array) {
292 const VariableArrayType *VAT = Array->getAsVariableArrayType();
293 return VAT && !VAT->getSizeExpr();
294}
295
296/// equivalentArrayTypes - Used to determine whether two array types are
297/// equivalent.
298/// We need to check this explicitly as an incomplete array definition is
299/// considered a VariableArrayType, so will not match a complete array
300/// definition that would be otherwise equivalent.
301static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
302 const ArrayType *NewAT = NewQType->getAsArrayType();
303 const ArrayType *OldAT = OldQType->getAsArrayType();
304
305 if (!NewAT || !OldAT)
306 return false;
307
308 // If either (or both) array types in incomplete we need to strip off the
309 // outer VariableArrayType. Once the outer VAT is removed the remaining
310 // types must be identical if the array types are to be considered
311 // equivalent.
312 // eg. int[][1] and int[1][1] become
313 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
314 // removing the outermost VAT gives
315 // CAT(1, int) and CAT(1, int)
316 // which are equal, therefore the array types are equivalent.
317 if (hasUndefinedLength(NewAT) || hasUndefinedLength(OldAT)) {
318 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
319 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000320 NewQType = NewAT->getElementType().getCanonicalType();
321 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000322 }
323
324 return NewQType == OldQType;
325}
326
Reid Spencer5f016e22007-07-11 17:01:13 +0000327/// MergeVarDecl - We just parsed a variable 'New' which has the same name
328/// and scope as a previous declaration 'Old'. Figure out how to resolve this
329/// situation, merging decls or emitting diagnostics as appropriate.
330///
331/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
332/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
333///
Steve Naroff8e74c932007-09-13 21:41:19 +0000334VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 // Verify the old decl was also a variable.
336 VarDecl *Old = dyn_cast<VarDecl>(OldD);
337 if (!Old) {
338 Diag(New->getLocation(), diag::err_redefinition_different_kind,
339 New->getName());
340 Diag(OldD->getLocation(), diag::err_previous_definition);
341 return New;
342 }
343 // Verify the types match.
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000344 if (Old->getCanonicalType() != New->getCanonicalType() &&
345 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 Diag(New->getLocation(), diag::err_redefinition, New->getName());
347 Diag(Old->getLocation(), diag::err_previous_definition);
348 return New;
349 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000350 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
351 if (New->getStorageClass() == VarDecl::Static &&
352 (Old->getStorageClass() == VarDecl::None ||
353 Old->getStorageClass() == VarDecl::Extern)) {
354 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
355 Diag(Old->getLocation(), diag::err_previous_definition);
356 return New;
357 }
358 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
359 if (New->getStorageClass() != VarDecl::Static &&
360 Old->getStorageClass() == VarDecl::Static) {
361 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
362 Diag(Old->getLocation(), diag::err_previous_definition);
363 return New;
364 }
365 // We've verified the types match, now handle "tentative" definitions.
366 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
367 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
368
369 if (OldFSDecl && NewFSDecl) {
370 // Handle C "tentative" external object definitions (C99 6.9.2).
371 bool OldIsTentative = false;
372 bool NewIsTentative = false;
373
374 if (!OldFSDecl->getInit() &&
375 (OldFSDecl->getStorageClass() == VarDecl::None ||
376 OldFSDecl->getStorageClass() == VarDecl::Static))
377 OldIsTentative = true;
378
379 // FIXME: this check doesn't work (since the initializer hasn't been
380 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
381 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
382 // thrown out the old decl.
383 if (!NewFSDecl->getInit() &&
384 (NewFSDecl->getStorageClass() == VarDecl::None ||
385 NewFSDecl->getStorageClass() == VarDecl::Static))
386 ; // change to NewIsTentative = true; once the code is moved.
387
388 if (NewIsTentative || OldIsTentative)
389 return New;
390 }
391 if (Old->getStorageClass() != VarDecl::Extern &&
392 New->getStorageClass() != VarDecl::Extern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 Diag(New->getLocation(), diag::err_redefinition, New->getName());
394 Diag(Old->getLocation(), diag::err_previous_definition);
395 }
396 return New;
397}
398
399/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
400/// no declarator (e.g. "struct foo;") is parsed.
401Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
402 // TODO: emit error on 'int;' or 'const enum foo;'.
403 // TODO: emit error on 'typedef int;'
404 // if (!DS.isMissingDeclaratorOk()) Diag(...);
405
Steve Naroff92199282007-11-17 21:37:36 +0000406 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000407}
408
Steve Naroffd0091aa2008-01-10 22:15:12 +0000409bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000410 // Get the type before calling CheckSingleAssignmentConstraints(), since
411 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000412 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000413
Chris Lattner5cf216b2008-01-04 18:04:52 +0000414 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
415 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
416 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000417}
418
Steve Naroff9e8925e2007-09-04 14:36:54 +0000419bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000420 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000421 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000422 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000423 return true; // types weren't compatible.
424
Steve Naroff9e8925e2007-09-04 14:36:54 +0000425 if (savExpr != expr) // The type was promoted, update initializer list.
426 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000427 return false;
428}
429
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000430bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
431 if (const VariableArrayType *VAT = DeclT->getAsIncompleteArrayType()) {
432 // C99 6.7.8p14. We have an array of character type with unknown size
433 // being initialized to a string literal.
434 llvm::APSInt ConstVal(32);
435 ConstVal = strLiteral->getByteLength() + 1;
436 // Return a new array type (C99 6.7.8p22).
437 DeclT = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
438 ArrayType::Normal, 0);
439 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
440 // C99 6.7.8p14. We have an array of character type with known size.
441 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
442 Diag(strLiteral->getSourceRange().getBegin(),
443 diag::warn_initializer_string_for_char_array_too_long,
444 strLiteral->getSourceRange());
445 } else {
446 assert(0 && "HandleStringLiteralInit(): Invalid array type");
447 }
448 // Set type from "char *" to "constant array of char".
449 strLiteral->setType(DeclT);
450 // For now, we always return false (meaning success).
451 return false;
452}
453
454StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000455 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000456 if (AT && AT->getElementType()->isCharType()) {
457 return dyn_cast<StringLiteral>(Init);
458 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000459 return 0;
460}
461
Steve Naroffa9960332008-01-25 00:51:06 +0000462// CheckInitializerListTypes - Checks the types of elements of an initializer
463// list. This function is recursive: it calls itself to initialize subelements
464// of aggregate types. Note that the topLevel parameter essentially refers to
465// whether this expression "owns" the initializer list passed in, or if this
466// initialization is taking elements out of a parent initializer. Each
467// call to this function adds zero or more to startIndex, reports any errors,
468// and returns true if it found any inconsistent types.
469bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
470 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000471 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000472
473 if (DeclType->isScalarType()) {
474 // The simplest case: initializing a single scalar
475 if (topLevel) {
476 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
477 IList->getSourceRange());
478 }
479 if (startIndex < IList->getNumInits()) {
480 Expr* expr = IList->getInit(startIndex);
481 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
482 // FIXME: Should an error be reported here instead?
483 unsigned newIndex = 0;
484 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
485 } else {
486 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
487 }
488 ++startIndex;
489 }
490 // FIXME: Should an error be reported for empty initializer list + scalar?
491 } else if (DeclType->isVectorType()) {
492 if (startIndex < IList->getNumInits()) {
493 const VectorType *VT = DeclType->getAsVectorType();
494 int maxElements = VT->getNumElements();
495 QualType elementType = VT->getElementType();
496
497 for (int i = 0; i < maxElements; ++i) {
498 // Don't attempt to go past the end of the init list
499 if (startIndex >= IList->getNumInits())
500 break;
501 Expr* expr = IList->getInit(startIndex);
502 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
503 unsigned newIndex = 0;
504 hadError |= CheckInitializerListTypes(SubInitList, elementType,
505 true, newIndex);
506 ++startIndex;
507 } else {
508 hadError |= CheckInitializerListTypes(IList, elementType,
509 false, startIndex);
510 }
511 }
512 }
513 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
514 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000515 if (startIndex < IList->getNumInits() && !topLevel &&
516 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
517 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000518 // We found a compatible struct; per the standard, this initializes the
519 // struct. (The C standard technically says that this only applies for
520 // initializers for declarations with automatic scope; however, this
521 // construct is unambiguous anyway because a struct cannot contain
522 // a type compatible with itself. We'll output an error when we check
523 // if the initializer is constant.)
524 // FIXME: Is a call to CheckSingleInitializer required here?
525 ++startIndex;
526 } else {
527 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
528 // If structDecl is a forward declaration, this loop won't do anything;
529 // That's okay, because an error should get printed out elsewhere. It
530 // might be worthwhile to skip over the rest of the initializer, though.
531 int numMembers = structDecl->getNumMembers() -
532 structDecl->hasFlexibleArrayMember();
533 for (int i = 0; i < numMembers; i++) {
534 // Don't attempt to go past the end of the init list
535 if (startIndex >= IList->getNumInits())
536 break;
537 FieldDecl * curField = structDecl->getMember(i);
538 if (!curField->getIdentifier()) {
539 // Don't initialize unnamed fields, e.g. "int : 20;"
540 continue;
541 }
542 QualType fieldType = curField->getType();
543 Expr* expr = IList->getInit(startIndex);
544 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
545 unsigned newStart = 0;
546 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
547 true, newStart);
548 ++startIndex;
549 } else {
550 hadError |= CheckInitializerListTypes(IList, fieldType,
551 false, startIndex);
552 }
553 if (DeclType->isUnionType())
554 break;
555 }
556 // FIXME: Implement flexible array initialization GCC extension (it's a
557 // really messy extension to implement, unfortunately...the necessary
558 // information isn't actually even here!)
559 }
560 } else if (DeclType->isArrayType()) {
561 // Check for the special-case of initializing an array with a string.
562 if (startIndex < IList->getNumInits()) {
563 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
564 DeclType)) {
565 CheckStringLiteralInit(lit, DeclType);
566 ++startIndex;
567 if (topLevel && startIndex < IList->getNumInits()) {
568 // We have leftover initializers; warn
569 Diag(IList->getInit(startIndex)->getLocStart(),
570 diag::err_excess_initializers_in_char_array_initializer,
571 IList->getInit(startIndex)->getSourceRange());
572 }
573 return false;
574 }
575 }
576 int maxElements;
577 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
578 // FIXME: use a proper constant
579 maxElements = 0x7FFFFFFF;
580 // Check for VLAs; in standard C it would be possible to check this
581 // earlier, but I don't know where clang accepts VLAs (gcc accepts
582 // them in all sorts of strange places).
583 if (const Expr *expr = VAT->getSizeExpr()) {
584 Diag(expr->getLocStart(), diag::err_variable_object_no_init,
585 expr->getSourceRange());
586 hadError = true;
587 }
588 } else {
589 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
590 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
591 }
592 QualType elementType = DeclType->getAsArrayType()->getElementType();
593 int numElements = 0;
594 for (int i = 0; i < maxElements; ++i, ++numElements) {
595 // Don't attempt to go past the end of the init list
596 if (startIndex >= IList->getNumInits())
597 break;
598 Expr* expr = IList->getInit(startIndex);
599 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
600 unsigned newIndex = 0;
601 hadError |= CheckInitializerListTypes(SubInitList, elementType,
602 true, newIndex);
603 ++startIndex;
604 } else {
605 hadError |= CheckInitializerListTypes(IList, elementType,
606 false, startIndex);
607 }
608 }
609 if (DeclType->getAsVariableArrayType()) {
610 // If this is an incomplete array type, the actual type needs to
611 // be calculated here
612 if (numElements == 0) {
613 // Sizing an array implicitly to zero is not allowed
614 // (It could in theory be allowed, but it doesn't really matter.)
615 Diag(IList->getLocStart(),
616 diag::err_at_least_one_initializer_needed_to_size_array);
617 hadError = true;
618 } else {
619 llvm::APSInt ConstVal(32);
620 ConstVal = numElements;
621 DeclType = Context.getConstantArrayType(elementType, ConstVal,
622 ArrayType::Normal, 0);
623 }
624 }
625 } else {
626 assert(0 && "Aggregate that isn't a function or array?!");
627 }
628 } else {
629 // In C, all types are either scalars or aggregates, but
630 // additional handling is needed here for C++ (and possibly others?).
631 assert(0 && "Unsupported initializer type");
632 }
633
634 // If this init list is a base list, we set the type; an initializer doesn't
635 // fundamentally have a type, but this makes the ASTs a bit easier to read
636 if (topLevel)
637 IList->setType(DeclType);
638
639 if (topLevel && startIndex < IList->getNumInits()) {
640 // We have leftover initializers; warn
641 Diag(IList->getInit(startIndex)->getLocStart(),
642 diag::warn_excess_initializers,
643 IList->getInit(startIndex)->getSourceRange());
644 }
645 return hadError;
646}
647
648bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000649 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
650 // of unknown size ("[]") or an object type that is not a variable array type.
651 if (const VariableArrayType *VAT = DeclType->getAsVariablyModifiedType())
652 return Diag(VAT->getSizeExpr()->getLocStart(),
653 diag::err_variable_object_no_init,
654 VAT->getSizeExpr()->getSourceRange());
655
Steve Naroff2fdc3742007-12-10 22:44:33 +0000656 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
657 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000658 // FIXME: Handle wide strings
659 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
660 return CheckStringLiteralInit(strLiteral, DeclType);
Steve Naroffd0091aa2008-01-10 22:15:12 +0000661 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000662 }
Steve Naroffa9960332008-01-25 00:51:06 +0000663 unsigned newIndex = 0;
664 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Narofff0090632007-09-02 02:04:30 +0000665}
666
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000667Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000668Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000669 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000670 IdentifierInfo *II = D.getIdentifier();
671
Chris Lattnere80a59c2007-07-25 00:24:17 +0000672 // All of these full declarators require an identifier. If it doesn't have
673 // one, the ParsedFreeStandingDeclSpec action should be used.
674 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000675 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000676 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000677 D.getDeclSpec().getSourceRange(), D.getSourceRange());
678 return 0;
679 }
680
Chris Lattner31e05722007-08-26 06:24:45 +0000681 // The scope passed in may not be a decl scope. Zip up the scope tree until
682 // we find one that is.
683 while ((S->getFlags() & Scope::DeclScope) == 0)
684 S = S->getParent();
685
Reid Spencer5f016e22007-07-11 17:01:13 +0000686 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000687 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
688 D.getIdentifierLoc(), S);
Steve Naroffc752d042007-09-13 18:10:37 +0000689 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000690 bool InvalidDecl = false;
691
Chris Lattner41af0932007-11-14 06:34:38 +0000692 QualType R = GetTypeForDeclarator(D, S);
693 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
694
Reid Spencer5f016e22007-07-11 17:01:13 +0000695 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000696 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 if (!NewTD) return 0;
698
699 // Handle attributes prior to checking for duplicates in MergeVarDecl
700 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
701 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000702 // Merge the decl with the existing one if appropriate. If the decl is
703 // in an outer scope, it isn't the same thing.
704 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000705 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
706 if (NewTD == 0) return 0;
707 }
708 New = NewTD;
709 if (S->getParent() == 0) {
710 // C99 6.7.7p2: If a typedef name specifies a variably modified type
711 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000712 if (const VariableArrayType *VAT =
713 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
714 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
715 VAT->getSizeExpr()->getSourceRange());
716 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 }
718 }
Chris Lattner41af0932007-11-14 06:34:38 +0000719 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000720 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000721 switch (D.getDeclSpec().getStorageClassSpec()) {
722 default: assert(0 && "Unknown storage class!");
723 case DeclSpec::SCS_auto:
724 case DeclSpec::SCS_register:
725 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
726 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000727 InvalidDecl = true;
728 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000729 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
730 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
731 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000732 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000733 }
734
735 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000736 D.getDeclSpec().isInlineSpecified(),
Nate Begeman1b4e2512007-11-13 22:14:47 +0000737 LastDeclarator,
738 D.getDeclSpec().getAttributes());
739
740 // Transfer ownership of DeclSpec attributes to FunctionDecl
741 D.getDeclSpec().clearAttributes();
Reid Spencer5f016e22007-07-11 17:01:13 +0000742
Steve Naroffffce4d52008-01-09 23:34:55 +0000743 // Merge the decl with the existing one if appropriate. Since C functions
744 // are in a flat namespace, make sure we consider decls in outer scopes.
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 if (PrevDecl) {
746 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
747 if (NewFD == 0) return 0;
748 }
749 New = NewFD;
750 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000751 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000752 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
753 D.getIdentifier()->getName());
754 InvalidDecl = true;
755 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000756
757 VarDecl *NewVD;
758 VarDecl::StorageClass SC;
759 switch (D.getDeclSpec().getStorageClassSpec()) {
760 default: assert(0 && "Unknown storage class!");
Steve Naroffd6326c62008-01-25 22:14:40 +0000761 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
762 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
763 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
764 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
765 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
766 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000767 }
768 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000769 // C99 6.9p2: The storage-class specifiers auto and register shall not
770 // appear in the declaration specifiers in an external declaration.
771 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
772 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
773 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000774 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000775 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000776 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000777 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000778 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000779 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000780 // Handle attributes prior to checking for duplicates in MergeVarDecl
781 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
782 D.getAttributes());
783
Steve Naroffffce4d52008-01-09 23:34:55 +0000784 // Merge the decl with the existing one if appropriate. If the decl is
785 // in an outer scope, it isn't the same thing.
786 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 NewVD = MergeVarDecl(NewVD, PrevDecl);
788 if (NewVD == 0) return 0;
789 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000790 New = NewVD;
791 }
792
793 // If this has an identifier, add it to the scope stack.
794 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000795 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000796 II->setFETokenInfo(New);
797 S->AddDecl(New);
798 }
Steve Naroff5912a352007-08-28 20:14:24 +0000799 // If any semantic error occurred, mark the decl as invalid.
800 if (D.getInvalidType() || InvalidDecl)
801 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000802
803 return New;
804}
805
Steve Naroffd0091aa2008-01-10 22:15:12 +0000806bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
807 SourceLocation loc;
808 // FIXME: Remove the isReference check and handle assignment to a reference.
809 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
810 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
811 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
812 return true;
813 }
814 return false;
815}
816
Steve Naroffbb204692007-09-12 14:07:44 +0000817void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000818 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000819 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000820 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000821
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000822 // If there is no declaration, there was an error parsing it. Just ignore
823 // the initializer.
824 if (RealDecl == 0) {
825 delete Init;
826 return;
827 }
Steve Naroffbb204692007-09-12 14:07:44 +0000828
Steve Naroff410e3e22007-09-12 20:13:48 +0000829 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
830 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000831 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
832 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000833 RealDecl->setInvalidDecl();
834 return;
835 }
Steve Naroffbb204692007-09-12 14:07:44 +0000836 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +0000837 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000838 QualType DclT = VDecl->getType(), SavT = DclT;
839 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000840 VarDecl::StorageClass SC = BVD->getStorageClass();
841 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000842 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000843 BVD->setInvalidDecl();
844 } else if (!BVD->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000845 if (CheckInitializerTypes(Init, DclT))
846 BVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000847 if (SC == VarDecl::Static) // C99 6.7.8p4.
848 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000849 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000850 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000851 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000852 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000853 if (!FVD->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +0000854 if (CheckInitializerTypes(Init, DclT))
855 FVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000856
857 // C99 6.7.8p4. All file scoped initializers need to be constant.
858 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000859 }
860 // If the type changed, it means we had an incomplete type that was
861 // completed by the initializer. For example:
862 // int ary[] = { 1, 3, 5 };
863 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +0000864 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000865 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +0000866 Init->setType(DclT);
867 }
Steve Naroffbb204692007-09-12 14:07:44 +0000868
869 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000870 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000871 return;
872}
873
Reid Spencer5f016e22007-07-11 17:01:13 +0000874/// The declarators are chained together backwards, reverse the list.
875Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
876 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000877 Decl *GroupDecl = static_cast<Decl*>(group);
878 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000879 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000880
881 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
882 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000883 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000884 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000885 else { // reverse the list.
886 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000887 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000888 Group->setNextDeclarator(NewGroup);
889 NewGroup = Group;
890 Group = Next;
891 }
892 }
893 // Perform semantic analysis that depends on having fully processed both
894 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000895 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000896 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
897 if (!IDecl)
898 continue;
899 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
900 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
901 QualType T = IDecl->getType();
902
903 // C99 6.7.5.2p2: If an identifier is declared to be an object with
904 // static storage duration, it shall not have a variable length array.
905 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
906 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
907 if (VLA->getSizeExpr()) {
908 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
909 IDecl->setInvalidDecl();
910 }
911 }
912 }
913 // Block scope. C99 6.7p7: If an identifier for an object is declared with
914 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
915 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
916 if (T->isIncompleteType()) {
Chris Lattner8b1be772007-12-02 07:50:03 +0000917 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
918 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000919 IDecl->setInvalidDecl();
920 }
921 }
922 // File scope. C99 6.9.2p2: A declaration of an identifier for and
923 // object that has file scope without an initializer, and without a
924 // storage-class specifier or with the storage-class specifier "static",
925 // constitutes a tentative definition. Note: A tentative definition with
926 // external linkage is valid (C99 6.2.2p5).
Steve Naroffd3cd1e52008-01-18 00:39:39 +0000927 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
928 FVD->getStorageClass() == VarDecl::None)) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +0000929 const VariableArrayType *VAT = T->getAsVariableArrayType();
930
931 if (VAT && VAT->getSizeExpr() == 0) {
932 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
933 // array to be completed. Don't issue a diagnostic.
934 } else if (T->isIncompleteType()) {
935 // C99 6.9.2p3: If the declaration of an identifier for an object is
936 // a tentative definition and has internal linkage (C99 6.2.2p3), the
937 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +0000938 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
939 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000940 IDecl->setInvalidDecl();
941 }
942 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000943 }
944 return NewGroup;
945}
Steve Naroffe1223f72007-08-28 03:03:08 +0000946
947// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000948ParmVarDecl *
Nate Begemanbff5f5c2007-11-13 21:49:48 +0000949Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI, Scope *FnScope)
Steve Naroff66499922007-11-12 03:44:46 +0000950{
Reid Spencer5f016e22007-07-11 17:01:13 +0000951 IdentifierInfo *II = PI.Ident;
952 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
953 // Can this happen for params? We already checked that they don't conflict
954 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000955 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000956 PI.IdentLoc, FnScope)) {
957
958 }
959
960 // FIXME: Handle storage class (auto, register). No declarator?
961 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000962
963 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
964 // Doing the promotion here has a win and a loss. The win is the type for
965 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
966 // code generator). The loss is the orginal type isn't preserved. For example:
967 //
968 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
969 // int blockvardecl[5];
970 // sizeof(parmvardecl); // size == 4
971 // sizeof(blockvardecl); // size == 20
972 // }
973 //
974 // For expressions, all implicit conversions are captured using the
975 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
976 //
977 // FIXME: If a source translation tool needs to see the original type, then
978 // we need to consider storing both types (in ParmVarDecl)...
979 //
980 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattner529bd022008-01-02 22:50:48 +0000981 if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
982 // int x[restrict 4] -> int *restrict
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000983 parmDeclType = Context.getPointerType(AT->getElementType());
Chris Lattner529bd022008-01-02 22:50:48 +0000984 parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
985 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000986 parmDeclType = Context.getPointerType(parmDeclType);
987
988 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Nate Begeman1b4e2512007-11-13 22:14:47 +0000989 VarDecl::None, 0, PI.AttrList);
Steve Naroff53a32342007-08-28 18:45:29 +0000990 if (PI.InvalidType)
991 New->setInvalidDecl();
992
Reid Spencer5f016e22007-07-11 17:01:13 +0000993 // If this has an identifier, add it to the scope stack.
994 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000995 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000996 II->setFETokenInfo(New);
997 FnScope->AddDecl(New);
998 }
999
1000 return New;
1001}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001002
Chris Lattnerb652cea2007-10-09 17:14:05 +00001003Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001004 assert(CurFunctionDecl == 0 && "Function parsing confused");
1005 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1006 "Not a function declarator!");
1007 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1008
1009 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1010 // for a K&R function.
1011 if (!FTI.hasPrototype) {
1012 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1013 if (FTI.ArgInfo[i].TypeInfo == 0) {
1014 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1015 FTI.ArgInfo[i].Ident->getName());
1016 // Implicitly declare the argument as type 'int' for lack of a better
1017 // type.
1018 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
1019 }
1020 }
1021
1022 // Since this is a function definition, act as though we have information
1023 // about the arguments.
1024 FTI.hasPrototype = true;
1025 } else {
1026 // FIXME: Diagnose arguments without names in C.
1027
1028 }
1029
1030 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001031
1032 // See if this is a redefinition.
1033 ScopedDecl *PrevDcl = LookupScopedDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1034 D.getIdentifierLoc(), GlobalScope);
1035 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1036 if (FD->getBody()) {
1037 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1038 D.getIdentifier()->getName());
1039 Diag(FD->getLocation(), diag::err_previous_definition);
1040 }
1041 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001042 FunctionDecl *FD =
Steve Naroff08d92e42007-09-15 18:49:24 +00001043 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001044 assert(FD != 0 && "ActOnDeclarator() didn't return a FunctionDecl");
Reid Spencer5f016e22007-07-11 17:01:13 +00001045 CurFunctionDecl = FD;
1046
1047 // Create Decl objects for each parameter, adding them to the FunctionDecl.
1048 llvm::SmallVector<ParmVarDecl*, 16> Params;
1049
1050 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1051 // no arguments, not a function that takes a single void argument.
1052 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb751c282007-11-28 18:51:29 +00001053 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getQualifiers() &&
1054 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 // empty arg list, don't push any params.
1056 } else {
Steve Naroff66499922007-11-12 03:44:46 +00001057 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begemanbff5f5c2007-11-13 21:49:48 +00001058 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroff66499922007-11-12 03:44:46 +00001059 FnBodyScope));
1060 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001061 }
1062
1063 FD->setParams(&Params[0], Params.size());
1064
1065 return FD;
1066}
1067
Steve Naroffd6d054d2007-11-11 23:20:51 +00001068Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1069 Decl *dcl = static_cast<Decl *>(D);
1070 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1071 FD->setBody((Stmt*)Body);
1072 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001073 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001074 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001075 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001076 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001077 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001078 // Verify and clean out per-function state.
1079
1080 // Check goto/label use.
1081 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1082 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1083 // Verify that we have no forward references left. If so, there was a goto
1084 // or address of a label taken, but no definition of it. Label fwd
1085 // definitions are indicated with a null substmt.
1086 if (I->second->getSubStmt() == 0) {
1087 LabelStmt *L = I->second;
1088 // Emit error.
1089 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1090
1091 // At this point, we have gotos that use the bogus label. Stitch it into
1092 // the function body so that they aren't leaked and that the AST is well
1093 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001094 if (Body) {
1095 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1096 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1097 } else {
1098 // The whole function wasn't parsed correctly, just delete this.
1099 delete L;
1100 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001101 }
1102 }
1103 LabelMap.clear();
1104
Steve Naroffd6d054d2007-11-11 23:20:51 +00001105 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001106}
1107
Reid Spencer5f016e22007-07-11 17:01:13 +00001108/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1109/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001110ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1111 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001112 if (getLangOptions().C99) // Extension in C99.
1113 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1114 else // Legal in C90, but warn about it.
1115 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1116
1117 // FIXME: handle stuff like:
1118 // void foo() { extern float X(); }
1119 // void bar() { X(); } <-- implicit decl for X in another scope.
1120
1121 // Set a Declarator for the implicit definition: int foo();
1122 const char *Dummy;
1123 DeclSpec DS;
1124 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1125 Error = Error; // Silence warning.
1126 assert(!Error && "Error setting up implicit decl!");
1127 Declarator D(DS, Declarator::BlockContext);
1128 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1129 D.SetIdentifier(&II, Loc);
1130
1131 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +00001132 if (Scope *FnS = S->getFnParent())
1133 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 while (S->getParent())
1135 S = S->getParent();
1136
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001137 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +00001138}
1139
1140
Chris Lattner41af0932007-11-14 06:34:38 +00001141TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001142 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001144 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001145
1146 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +00001147 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
1148 T, LastDeclarator);
1149 if (D.getInvalidType())
1150 NewTD->setInvalidDecl();
1151 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001152}
1153
Steve Naroff08d92e42007-09-15 18:49:24 +00001154/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001155/// former case, Name will be non-null. In the later case, Name will be null.
1156/// TagType indicates what kind of tag this is. TK indicates whether this is a
1157/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001158Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001159 SourceLocation KWLoc, IdentifierInfo *Name,
1160 SourceLocation NameLoc, AttributeList *Attr) {
1161 // If this is a use of an existing tag, it must have a name.
1162 assert((Name != 0 || TK == TK_Definition) &&
1163 "Nameless record must be a definition!");
1164
1165 Decl::Kind Kind;
1166 switch (TagType) {
1167 default: assert(0 && "Unknown tag type!");
1168 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1169 case DeclSpec::TST_union: Kind = Decl::Union; break;
1170//case DeclSpec::TST_class: Kind = Decl::Class; break;
1171 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1172 }
1173
1174 // If this is a named struct, check to see if there was a previous forward
1175 // declaration or definition.
1176 if (TagDecl *PrevDecl =
1177 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1178 NameLoc, S))) {
1179
1180 // If this is a use of a previous tag, or if the tag is already declared in
1181 // the same scope (so that the definition/declaration completes or
1182 // rementions the tag), reuse the decl.
1183 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1184 // Make sure that this wasn't declared as an enum and now used as a struct
1185 // or something similar.
1186 if (PrevDecl->getKind() != Kind) {
1187 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1188 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1189 }
1190
1191 // If this is a use or a forward declaration, we're good.
1192 if (TK != TK_Definition)
1193 return PrevDecl;
1194
1195 // Diagnose attempts to redefine a tag.
1196 if (PrevDecl->isDefinition()) {
1197 Diag(NameLoc, diag::err_redefinition, Name->getName());
1198 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1199 // If this is a redefinition, recover by making this struct be
1200 // anonymous, which will make any later references get the previous
1201 // definition.
1202 Name = 0;
1203 } else {
1204 // Okay, this is definition of a previously declared or referenced tag.
1205 // Move the location of the decl to be the definition site.
1206 PrevDecl->setLocation(NameLoc);
1207 return PrevDecl;
1208 }
1209 }
1210 // If we get here, this is a definition of a new struct type in a nested
1211 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1212 // type.
1213 }
1214
1215 // If there is an identifier, use the location of the identifier as the
1216 // location of the decl, otherwise use the location of the struct/union
1217 // keyword.
1218 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1219
1220 // Otherwise, if this is the first time we've seen this tag, create the decl.
1221 TagDecl *New;
1222 switch (Kind) {
1223 default: assert(0 && "Unknown tag kind!");
1224 case Decl::Enum:
1225 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1226 // enum X { A, B, C } D; D should chain to X.
1227 New = new EnumDecl(Loc, Name, 0);
1228 // If this is an undefined enum, warn.
1229 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1230 break;
1231 case Decl::Union:
1232 case Decl::Struct:
1233 case Decl::Class:
1234 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1235 // struct X { int A; } D; D should chain to X.
1236 New = new RecordDecl(Kind, Loc, Name, 0);
1237 break;
1238 }
1239
1240 // If this has an identifier, add it to the scope stack.
1241 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001242 // The scope passed in may not be a decl scope. Zip up the scope tree until
1243 // we find one that is.
1244 while ((S->getFlags() & Scope::DeclScope) == 0)
1245 S = S->getParent();
1246
1247 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001248 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 Name->setFETokenInfo(New);
1250 S->AddDecl(New);
1251 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001252
Reid Spencer5f016e22007-07-11 17:01:13 +00001253 return New;
1254}
1255
Steve Naroff08d92e42007-09-15 18:49:24 +00001256/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001257/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001258Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001259 SourceLocation DeclStart,
1260 Declarator &D, ExprTy *BitfieldWidth) {
1261 IdentifierInfo *II = D.getIdentifier();
1262 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 SourceLocation Loc = DeclStart;
1264 if (II) Loc = D.getIdentifierLoc();
1265
1266 // FIXME: Unnamed fields can be handled in various different ways, for
1267 // example, unnamed unions inject all members into the struct namespace!
1268
1269
1270 if (BitWidth) {
1271 // TODO: Validate.
1272 //printf("WARNING: BITFIELDS IGNORED!\n");
1273
1274 // 6.7.2.1p3
1275 // 6.7.2.1p4
1276
1277 } else {
1278 // Not a bitfield.
1279
1280 // validate II.
1281
1282 }
1283
1284 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001285 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1286 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001287
Reid Spencer5f016e22007-07-11 17:01:13 +00001288 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1289 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001290 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1291 Diag(Loc, diag::err_typecheck_illegal_vla,
1292 VAT->getSizeExpr()->getSourceRange());
1293 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001296 FieldDecl *NewFD;
1297
1298 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patel54e62352007-11-01 16:29:56 +00001299 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001300 else if (isa<ObjCInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1301 isa<ObjCImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
1302 isa<ObjCCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroffddd600f2007-11-14 14:15:31 +00001303 // FIXME: ivars are currently used to model properties, and
1304 // properties can appear within a protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001305 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1306 isa<ObjCProtocolDecl>(static_cast<Decl *>(TagDecl)))
1307 NewFD = new ObjCIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001308 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001309 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001310
Steve Naroff5912a352007-08-28 20:14:24 +00001311 if (D.getInvalidType() || InvalidDecl)
1312 NewFD->setInvalidDecl();
1313 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001314}
1315
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001316/// TranslateIvarVisibility - Translate visibility from a token ID to an
1317/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001318static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001319TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001320 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001321 case tok::objc_private: return ObjCIvarDecl::Private;
1322 case tok::objc_public: return ObjCIvarDecl::Public;
1323 case tok::objc_protected: return ObjCIvarDecl::Protected;
1324 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001325 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001326 }
1327}
1328
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001329void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001330 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001331 DeclTy **Fields, unsigned NumFields,
Steve Naroff60fccee2007-10-29 21:38:07 +00001332 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff08d92e42007-09-15 18:49:24 +00001333 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001334 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1335 assert(EnclosingDecl && "missing record or interface decl");
1336 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1337
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001338 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 // Diagnose code like:
1340 // struct S { struct S {} X; };
1341 // We discover this when we complete the outer S. Reject and ignore the
1342 // outer S.
1343 Diag(Record->getLocation(), diag::err_nested_redefinition,
1344 Record->getKindName());
1345 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001346 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001347 return;
1348 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 // Verify that all the fields are okay.
1350 unsigned NumNamedMembers = 0;
1351 llvm::SmallVector<FieldDecl*, 32> RecFields;
1352 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001353
Reid Spencer5f016e22007-07-11 17:01:13 +00001354 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001355
Steve Naroff74216642007-09-14 22:20:54 +00001356 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1357 assert(FD && "missing field decl");
1358
1359 // Remember all fields.
1360 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001361
1362 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001363 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001364
Steve Narofff13271f2007-09-14 23:09:53 +00001365 // If we have visibility info, make sure the AST is set accordingly.
1366 if (visibility)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001367 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001368 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001369
Reid Spencer5f016e22007-07-11 17:01:13 +00001370 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001371 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001372 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001374 FD->setInvalidDecl();
1375 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 continue;
1377 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1379 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001380 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001381 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001382 FD->setInvalidDecl();
1383 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001384 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001385 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001386 if (i != NumFields-1 || // ... that the last member ...
1387 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001388 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001390 FD->setInvalidDecl();
1391 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 continue;
1393 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001394 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001395 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1396 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001397 FD->setInvalidDecl();
1398 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 continue;
1400 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001401 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001402 if (Record)
1403 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001405 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1406 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001407 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001408 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1409 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001410 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 Record->setHasFlexibleArrayMember(true);
1412 } else {
1413 // If this is a struct/class and this is not the last element, reject
1414 // it. Note that GCC supports variable sized arrays in the middle of
1415 // structures.
1416 if (i != NumFields-1) {
1417 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1418 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001419 FD->setInvalidDecl();
1420 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 continue;
1422 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001423 // We support flexible arrays at the end of structs in other structs
1424 // as an extension.
1425 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1426 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001427 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001428 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 }
1430 }
1431 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001432 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001433 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001434 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1435 FD->getName());
1436 FD->setInvalidDecl();
1437 EnclosingDecl->setInvalidDecl();
1438 continue;
1439 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001440 // Keep track of the number of named members.
1441 if (IdentifierInfo *II = FD->getIdentifier()) {
1442 // Detect duplicate member names.
1443 if (!FieldIDs.insert(II)) {
1444 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1445 // Find the previous decl.
1446 SourceLocation PrevLoc;
1447 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1448 assert(i != e && "Didn't find previous def!");
1449 if (RecFields[i]->getIdentifier() == II) {
1450 PrevLoc = RecFields[i]->getLocation();
1451 break;
1452 }
1453 }
1454 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001455 FD->setInvalidDecl();
1456 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001457 continue;
1458 }
1459 ++NumNamedMembers;
1460 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001461 }
1462
Reid Spencer5f016e22007-07-11 17:01:13 +00001463 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00001464 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001465 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00001466 Consumer.HandleTagDeclDefinition(Record);
1467 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00001468 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1469 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1470 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1471 else if (ObjCImplementationDecl *IMPDecl =
1472 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001473 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1474 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001475 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001476 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001477 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001478}
1479
Steve Naroff08d92e42007-09-15 18:49:24 +00001480Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001481 DeclTy *lastEnumConst,
1482 SourceLocation IdLoc, IdentifierInfo *Id,
1483 SourceLocation EqualLoc, ExprTy *val) {
1484 theEnumDecl = theEnumDecl; // silence unused warning.
1485 EnumConstantDecl *LastEnumConst =
1486 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1487 Expr *Val = static_cast<Expr*>(val);
1488
Chris Lattner31e05722007-08-26 06:24:45 +00001489 // The scope passed in may not be a decl scope. Zip up the scope tree until
1490 // we find one that is.
1491 while ((S->getFlags() & Scope::DeclScope) == 0)
1492 S = S->getParent();
1493
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 // Verify that there isn't already something declared with this name in this
1495 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001496 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1497 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001498 if (S->isDeclScope(PrevDecl)) {
1499 if (isa<EnumConstantDecl>(PrevDecl))
1500 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1501 else
1502 Diag(IdLoc, diag::err_redefinition, Id->getName());
1503 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1504 // FIXME: Don't leak memory: delete Val;
1505 return 0;
1506 }
1507 }
1508
1509 llvm::APSInt EnumVal(32);
1510 QualType EltTy;
1511 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001512 // Make sure to promote the operand type to int.
1513 UsualUnaryConversions(Val);
1514
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1516 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001517 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1519 Id->getName());
1520 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001521 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001522 } else {
1523 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001525 }
1526
1527 if (!Val) {
1528 if (LastEnumConst) {
1529 // Assign the last value + 1.
1530 EnumVal = LastEnumConst->getInitVal();
1531 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001532
1533 // Check for overflow on increment.
1534 if (EnumVal < LastEnumConst->getInitVal())
1535 Diag(IdLoc, diag::warn_enum_value_overflow);
1536
Chris Lattnerb7416f92007-08-27 17:37:24 +00001537 EltTy = LastEnumConst->getType();
1538 } else {
1539 // First value, set to zero.
1540 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001541 EnumVal.zextOrTrunc(
1542 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001543 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001544 }
1545
Reid Spencer5f016e22007-07-11 17:01:13 +00001546 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1547 LastEnumConst);
1548
1549 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001550 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 Id->setFETokenInfo(New);
1552 S->AddDecl(New);
1553 return New;
1554}
1555
Steve Naroff08d92e42007-09-15 18:49:24 +00001556void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 DeclTy **Elements, unsigned NumElements) {
1558 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1559 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1560
Chris Lattnere37f0be2007-08-28 05:10:31 +00001561 // TODO: If the result value doesn't fit in an int, it must be a long or long
1562 // long value. ISO C does not support this, but GCC does as an extension,
1563 // emit a warning.
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001564 unsigned IntWidth =
1565 Context.Target.getIntWidth(Context.getFullLoc(Enum->getLocation()));
Chris Lattnere37f0be2007-08-28 05:10:31 +00001566
1567
Chris Lattnerac609682007-08-28 06:15:15 +00001568 // Verify that all the values are okay, compute the size of the values, and
1569 // reverse the list.
1570 unsigned NumNegativeBits = 0;
1571 unsigned NumPositiveBits = 0;
1572
1573 // Keep track of whether all elements have type int.
1574 bool AllElementsInt = true;
1575
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 EnumConstantDecl *EltList = 0;
1577 for (unsigned i = 0; i != NumElements; ++i) {
1578 EnumConstantDecl *ECD =
1579 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1580 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001581
1582 // If the enum value doesn't fit in an int, emit an extension warning.
1583 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1584 "Should have promoted value to int");
1585 const llvm::APSInt &InitVal = ECD->getInitVal();
1586 if (InitVal.getBitWidth() > IntWidth) {
1587 llvm::APSInt V(InitVal);
1588 V.trunc(IntWidth);
1589 V.extend(InitVal.getBitWidth());
1590 if (V != InitVal)
1591 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1592 InitVal.toString());
1593 }
Chris Lattnerac609682007-08-28 06:15:15 +00001594
1595 // Keep track of the size of positive and negative values.
1596 if (InitVal.isUnsigned() || !InitVal.isNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001597 NumPositiveBits = std::max(NumPositiveBits,
1598 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001599 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001600 NumNegativeBits = std::max(NumNegativeBits,
1601 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001602
Chris Lattnerac609682007-08-28 06:15:15 +00001603 // Keep track of whether every enum element has type int (very commmon).
1604 if (AllElementsInt)
1605 AllElementsInt = ECD->getType() == Context.IntTy;
1606
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 ECD->setNextDeclarator(EltList);
1608 EltList = ECD;
1609 }
1610
Chris Lattnerac609682007-08-28 06:15:15 +00001611 // Figure out the type that should be used for this enum.
1612 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1613 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001614 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001615
1616 if (NumNegativeBits) {
1617 // If there is a negative value, figure out the smallest integer type (of
1618 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001619 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001620 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001621 BestWidth = IntWidth;
1622 } else {
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001623 BestWidth =
1624 Context.Target.getLongWidth(Context.getFullLoc(Enum->getLocation()));
1625
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001626 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001627 BestType = Context.LongTy;
1628 else {
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001629 BestWidth = Context.Target.getLongLongWidth(
1630 Context.getFullLoc(Enum->getLocation()));
1631
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001632 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001633 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1634 BestType = Context.LongLongTy;
1635 }
1636 }
1637 } else {
1638 // If there is no negative value, figure out which of uint, ulong, ulonglong
1639 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001640 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001641 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001642 BestWidth = IntWidth;
1643 } else if (NumPositiveBits <=
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001644 (BestWidth = Context.Target.getLongWidth(
1645 Context.getFullLoc(Enum->getLocation()))))
1646
Chris Lattnerac609682007-08-28 06:15:15 +00001647 BestType = Context.UnsignedLongTy;
1648 else {
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001649 BestWidth =
1650 Context.Target.getLongLongWidth(Context.getFullLoc(Enum->getLocation()));
1651
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001652 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001653 "How could an initializer get larger than ULL?");
1654 BestType = Context.UnsignedLongLongTy;
1655 }
1656 }
1657
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001658 // Loop over all of the enumerator constants, changing their types to match
1659 // the type of the enum if needed.
1660 for (unsigned i = 0; i != NumElements; ++i) {
1661 EnumConstantDecl *ECD =
1662 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1663 if (!ECD) continue; // Already issued a diagnostic.
1664
1665 // Standard C says the enumerators have int type, but we allow, as an
1666 // extension, the enumerators to be larger than int size. If each
1667 // enumerator value fits in an int, type it as an int, otherwise type it the
1668 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1669 // that X has type 'int', not 'unsigned'.
1670 if (ECD->getType() == Context.IntTy)
1671 continue; // Already int type.
1672
1673 // Determine whether the value fits into an int.
1674 llvm::APSInt InitVal = ECD->getInitVal();
1675 bool FitsInInt;
1676 if (InitVal.isUnsigned() || !InitVal.isNegative())
1677 FitsInInt = InitVal.getActiveBits() < IntWidth;
1678 else
1679 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1680
1681 // If it fits into an integer type, force it. Otherwise force it to match
1682 // the enum decl type.
1683 QualType NewTy;
1684 unsigned NewWidth;
1685 bool NewSign;
1686 if (FitsInInt) {
1687 NewTy = Context.IntTy;
1688 NewWidth = IntWidth;
1689 NewSign = true;
1690 } else if (ECD->getType() == BestType) {
1691 // Already the right type!
1692 continue;
1693 } else {
1694 NewTy = BestType;
1695 NewWidth = BestWidth;
1696 NewSign = BestType->isSignedIntegerType();
1697 }
1698
1699 // Adjust the APSInt value.
1700 InitVal.extOrTrunc(NewWidth);
1701 InitVal.setIsSigned(NewSign);
1702 ECD->setInitVal(InitVal);
1703
1704 // Adjust the Expr initializer and type.
1705 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1706 ECD->setType(NewTy);
1707 }
Chris Lattnerac609682007-08-28 06:15:15 +00001708
Chris Lattnere00b18c2007-08-28 18:24:31 +00001709 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00001710 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00001711}
1712
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001713Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
1714 SourceLocation LBrace,
1715 SourceLocation RBrace,
1716 const char *Lang,
1717 unsigned StrSize,
1718 DeclTy *D) {
1719 LinkageSpecDecl::LanguageIDs Language;
1720 Decl *dcl = static_cast<Decl *>(D);
1721 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1722 Language = LinkageSpecDecl::lang_c;
1723 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1724 Language = LinkageSpecDecl::lang_cxx;
1725 else {
1726 Diag(Loc, diag::err_bad_language);
1727 return 0;
1728 }
1729
1730 // FIXME: Add all the various semantics of linkage specifications
1731 return new LinkageSpecDecl(Loc, Language, dcl);
1732}
1733
Reid Spencer5f016e22007-07-11 17:01:13 +00001734void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001735 const char *attrName = rawAttr->getAttributeName()->getName();
1736 unsigned attrLen = rawAttr->getAttributeName()->getLength();
1737
Anders Carlssonabf5ad02007-12-19 17:43:24 +00001738 // Normalize the attribute name, __foo__ becomes foo.
1739 if (attrLen > 4 && attrName[0] == '_' && attrName[1] == '_' &&
1740 attrName[attrLen - 2] == '_' && attrName[attrLen - 1] == '_') {
1741 attrName += 2;
1742 attrLen -= 4;
1743 }
1744
1745 if (attrLen == 11 && !memcmp(attrName, "vector_size", 11)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001746 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1747 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1748 if (!newType.isNull()) // install the new vector type into the decl
1749 vDecl->setType(newType);
1750 }
1751 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1752 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1753 rawAttr);
1754 if (!newType.isNull()) // install the new vector type into the decl
1755 tDecl->setUnderlyingType(newType);
1756 }
Anders Carlssonabf5ad02007-12-19 17:43:24 +00001757 } else if (attrLen == 15 && !memcmp(attrName, "ocu_vector_type", 15)) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001758 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1759 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1760 else
Steve Naroff73322922007-07-18 18:00:27 +00001761 Diag(rawAttr->getAttributeLoc(),
1762 diag::err_typecheck_ocu_vector_not_typedef);
Christopher Lambebb97e92008-02-04 02:31:56 +00001763 } else if (attrLen == 13 && !memcmp(attrName, "address_space", 13)) {
1764 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1765 QualType newType = HandleAddressSpaceTypeAttribute(
1766 tDecl->getUnderlyingType(),
1767 rawAttr);
1768 if (!newType.isNull()) // install the new addr spaced type into the decl
1769 tDecl->setUnderlyingType(newType);
1770 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1771 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
1772 rawAttr);
1773 if (!newType.isNull()) // install the new addr spaced type into the decl
1774 vDecl->setType(newType);
1775 }
Anders Carlsson78aaae92007-12-19 07:19:40 +00001776 } else if (attrLen == 7 && !memcmp(attrName, "aligned", 7)) {
1777 HandleAlignedAttribute(New, rawAttr);
Steve Naroff73322922007-07-18 18:00:27 +00001778 }
Anders Carlsson78aaae92007-12-19 07:19:40 +00001779
Reid Spencer5f016e22007-07-11 17:01:13 +00001780 // FIXME: add other attributes...
1781}
1782
1783void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1784 AttributeList *declarator_postfix) {
1785 while (declspec_prefix) {
1786 HandleDeclAttribute(New, declspec_prefix);
1787 declspec_prefix = declspec_prefix->getNext();
1788 }
1789 while (declarator_postfix) {
1790 HandleDeclAttribute(New, declarator_postfix);
1791 declarator_postfix = declarator_postfix->getNext();
1792 }
1793}
1794
Christopher Lambebb97e92008-02-04 02:31:56 +00001795QualType Sema::HandleAddressSpaceTypeAttribute(QualType curType,
1796 AttributeList *rawAttr) {
1797 // check the attribute arugments.
1798 if (rawAttr->getNumArgs() != 1) {
1799 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1800 std::string("1"));
1801 return QualType();
1802 }
1803 Expr *addrSpaceExpr = static_cast<Expr *>(rawAttr->getArg(0));
1804 llvm::APSInt addrSpace(32);
1805 if (!addrSpaceExpr->isIntegerConstantExpr(addrSpace, Context)) {
1806 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_address_space_not_int,
1807 addrSpaceExpr->getSourceRange());
1808 return QualType();
1809 }
1810 unsigned addressSpace = static_cast<unsigned>(addrSpace.getZExtValue());
1811
1812 // Zero is the default memory space, so no qualification is needed
1813 if (addressSpace == 0)
1814 return curType;
1815
1816 // TODO: Should we convert contained types of address space
1817 // qualified types here or or where they directly participate in conversions
1818 // (i.e. elsewhere)
1819
1820 return Context.getASQualType(curType, addressSpace);
1821}
1822
Steve Naroffbea0b342007-07-29 16:33:31 +00001823void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1824 AttributeList *rawAttr) {
1825 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00001826 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00001827 if (rawAttr->getNumArgs() != 1) {
1828 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1829 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001830 return;
Steve Naroff73322922007-07-18 18:00:27 +00001831 }
1832 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1833 llvm::APSInt vecSize(32);
1834 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1835 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1836 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001837 return;
Steve Naroff73322922007-07-18 18:00:27 +00001838 }
1839 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1840 // in conjunction with complex types (pointers, arrays, functions, etc.).
1841 Type *canonType = curType.getCanonicalType().getTypePtr();
1842 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1843 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1844 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001845 return;
Steve Naroff73322922007-07-18 18:00:27 +00001846 }
1847 // unlike gcc's vector_size attribute, the size is specified as the
1848 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001849 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001850
1851 if (vectorSize == 0) {
1852 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1853 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001854 return;
Steve Naroff73322922007-07-18 18:00:27 +00001855 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001856 // Instantiate/Install the vector type, the number of elements is > 0.
1857 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1858 // Remember this typedef decl, we will need it later for diagnostics.
1859 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001860}
1861
Reid Spencer5f016e22007-07-11 17:01:13 +00001862QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001863 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001864 // check the attribute arugments.
1865 if (rawAttr->getNumArgs() != 1) {
1866 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1867 std::string("1"));
1868 return QualType();
1869 }
1870 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1871 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001872 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001873 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1874 sizeExpr->getSourceRange());
1875 return QualType();
1876 }
1877 // navigate to the base type - we need to provide for vector pointers,
1878 // vector arrays, and functions returning vectors.
1879 Type *canonType = curType.getCanonicalType().getTypePtr();
1880
Steve Naroff73322922007-07-18 18:00:27 +00001881 if (canonType->isPointerType() || canonType->isArrayType() ||
1882 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00001883 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00001884 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1885 do {
1886 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1887 canonType = PT->getPointeeType().getTypePtr();
1888 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1889 canonType = AT->getElementType().getTypePtr();
1890 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1891 canonType = FT->getResultType().getTypePtr();
1892 } while (canonType->isPointerType() || canonType->isArrayType() ||
1893 canonType->isFunctionType());
1894 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001895 }
1896 // the base type must be integer or float.
1897 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1898 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1899 curType.getCanonicalType().getAsString());
1900 return QualType();
1901 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00001902 unsigned typeSize = static_cast<unsigned>(
1903 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001904 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001905 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00001906
1907 // the vector size needs to be an integral multiple of the type size.
1908 if (vectorSize % typeSize) {
1909 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1910 sizeExpr->getSourceRange());
1911 return QualType();
1912 }
1913 if (vectorSize == 0) {
1914 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1915 sizeExpr->getSourceRange());
1916 return QualType();
1917 }
1918 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1919 // the number of elements to be a power of two (unlike GCC).
1920 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00001921 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001922}
1923
Anders Carlsson78aaae92007-12-19 07:19:40 +00001924void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
1925{
1926 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00001927 if (rawAttr->getNumArgs() > 1) {
Anders Carlsson78aaae92007-12-19 07:19:40 +00001928 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1929 std::string("1"));
1930 return;
1931 }
Eli Friedman4ca08672008-01-30 17:38:42 +00001932
Devang Patel6c751c22008-01-30 18:00:07 +00001933 // TODO: We probably need to actually do something with aligned attribute.
Eli Friedman4ca08672008-01-30 17:38:42 +00001934 if (rawAttr->getNumArgs() == 0)
1935 return;
1936
Anders Carlsson78aaae92007-12-19 07:19:40 +00001937 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
1938 llvm::APSInt alignment(32);
1939 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
1940 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1941 alignmentExpr->getSourceRange());
1942 return;
1943 }
1944}