blob: 68177e03c8b8aedc920f4a9ab150575c7439e949 [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner697e5d62006-11-09 06:32:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnere168f762006-11-10 05:29:30 +000014#include "Sema.h"
Chris Lattner5c5fbcc2006-12-03 08:41:30 +000015#include "clang/AST/ASTContext.h"
Chris Lattner9561a0b2007-01-28 08:20:04 +000016#include "clang/AST/Builtins.h"
Chris Lattnere168f762006-11-10 05:29:30 +000017#include "clang/AST/Decl.h"
Chris Lattner1300fb92007-01-23 23:42:53 +000018#include "clang/AST/Expr.h"
Chris Lattnerf84a79c2006-11-11 22:59:23 +000019#include "clang/AST/Type.h"
Chris Lattner591a6752006-11-19 23:16:18 +000020#include "clang/Parse/DeclSpec.h"
Chris Lattnere168f762006-11-10 05:29:30 +000021#include "clang/Parse/Scope.h"
Chris Lattnerac18be92006-11-20 06:49:47 +000022#include "clang/Basic/LangOptions.h"
Chris Lattner9561a0b2007-01-28 08:20:04 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroffd54978b2007-09-18 23:55:05 +000024#include "llvm/ADT/SmallString.h"
Chris Lattner38047f92007-01-27 06:24:01 +000025#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian458f7112007-10-05 18:00:57 +000026#include "llvm/ADT/DenseSet.h"
Chris Lattner697e5d62006-11-09 06:32:27 +000027using namespace clang;
28
Chris Lattner2ebe4bb2006-11-20 01:29:42 +000029Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Fariborz Jahaniand52cd412007-10-12 16:34:10 +000030 Decl *IIDecl = II.getFETokenInfo<Decl>();
31 // Find first occurance of none-tagged declaration
32 while(IIDecl && IIDecl->getIdentifierNamespace() != Decl::IDNS_Ordinary)
33 IIDecl = cast<ScopedDecl>(IIDecl)->getNext();
34 if (!IIDecl)
35 return 0;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000036 if (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl))
Fariborz Jahaniand52cd412007-10-12 16:34:10 +000037 return IIDecl;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000038 if (ObjCCompatibleAliasDecl *ADecl =
39 dyn_cast<ObjCCompatibleAliasDecl>(IIDecl))
Fariborz Jahaniand52cd412007-10-12 16:34:10 +000040 return ADecl->getClassInterface();
Steve Naroff09bf8152007-09-06 21:24:23 +000041 return 0;
Chris Lattnere168f762006-11-10 05:29:30 +000042}
43
Steve Naroffc62adb62007-10-09 22:01:59 +000044void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +000045 if (S->decl_empty()) return;
46 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
47
Chris Lattner302b4be2006-11-19 02:31:38 +000048 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
49 I != E; ++I) {
Steve Naroff9324db12007-09-13 18:10:37 +000050 Decl *TmpD = static_cast<Decl*>(*I);
51 assert(TmpD && "This decl didn't get pushed??");
52 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
53 assert(D && "This decl isn't a ScopedDecl?");
54
Chris Lattnerff65b6b2007-01-23 01:33:16 +000055 IdentifierInfo *II = D->getIdentifier();
56 if (!II) continue;
Chris Lattner302b4be2006-11-19 02:31:38 +000057
Chris Lattnerff65b6b2007-01-23 01:33:16 +000058 // Unlink this decl from the identifier. Because the scope contains decls
59 // in an unordered collection, and because we have multiple identifier
60 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
61 if (II->getFETokenInfo<Decl>() == D) {
62 // Normal case, no multiple decls in different namespaces.
63 II->setFETokenInfo(D->getNext());
64 } else {
65 // Scan ahead. There are only three namespaces in C, so this loop can
66 // never execute more than 3 times.
Steve Naroff9324db12007-09-13 18:10:37 +000067 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Chris Lattnerff65b6b2007-01-23 01:33:16 +000068 while (SomeDecl->getNext() != D) {
69 SomeDecl = SomeDecl->getNext();
70 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
71 }
72 SomeDecl->setNext(D->getNext());
73 }
Chris Lattner302b4be2006-11-19 02:31:38 +000074
Chris Lattner740b2f32006-11-21 01:32:20 +000075 // This will have to be revisited for C++: there we want to nest stuff in
76 // namespace decls etc. Even for C, we might want a top-level translation
77 // unit decl or something.
78 if (!CurFunctionDecl)
79 continue;
80
81 // Chain this decl to the containing function, it now owns the memory for
82 // the decl.
83 D->setNext(CurFunctionDecl->getDeclChain());
84 CurFunctionDecl->setDeclChain(D);
Chris Lattner302b4be2006-11-19 02:31:38 +000085 }
86}
87
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +000088/// LookupInterfaceDecl - Lookup interface declaration in the scope chain.
89/// Return the first declaration found (which may or may not be a class
Fariborz Jahanian02fbb682007-10-12 19:53:08 +000090/// declaration. Caller is responsible for handling the none-class case.
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +000091/// Bypassing the alias of a class by returning the aliased class.
92ScopedDecl *Sema::LookupInterfaceDecl(IdentifierInfo *ClassName) {
93 ScopedDecl *IDecl;
94 // Scan up the scope chain looking for a decl that matches this identifier
95 // that is in the appropriate namespace.
96 for (IDecl = ClassName->getFETokenInfo<ScopedDecl>(); IDecl;
97 IDecl = IDecl->getNext())
98 if (IDecl->getIdentifierNamespace() == Decl::IDNS_Ordinary)
99 break;
100
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000101 if (ObjCCompatibleAliasDecl *ADecl =
102 dyn_cast_or_null<ObjCCompatibleAliasDecl>(IDecl))
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +0000103 return ADecl->getClassInterface();
104 return IDecl;
105}
106
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000107/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian343f7092007-09-29 00:54:24 +0000108/// return 0 if one not found.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000109ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +0000110 ScopedDecl *IdDecl = LookupInterfaceDecl(Id);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000111 return cast_or_null<ObjCInterfaceDecl>(IdDecl);
Fariborz Jahanian343f7092007-09-29 00:54:24 +0000112}
113
Chris Lattner18b19622007-01-22 07:39:13 +0000114/// LookupScopedDecl - Look up the inner-most declaration in the specified
115/// namespace.
Steve Naroff9324db12007-09-13 18:10:37 +0000116ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
117 SourceLocation IdLoc, Scope *S) {
Chris Lattner18b19622007-01-22 07:39:13 +0000118 if (II == 0) return 0;
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000119 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
Chris Lattner18b19622007-01-22 07:39:13 +0000120
121 // Scan up the scope chain looking for a decl that matches this identifier
122 // that is in the appropriate namespace. This search should not take long, as
123 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroff9324db12007-09-13 18:10:37 +0000124 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner18b19622007-01-22 07:39:13 +0000125 if (D->getIdentifierNamespace() == NS)
126 return D;
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000127
Chris Lattner9561a0b2007-01-28 08:20:04 +0000128 // If we didn't find a use of this identifier, and if the identifier
129 // corresponds to a compiler builtin, create the decl object for the builtin
130 // now, injecting it into translation unit scope, and return it.
131 if (NS == Decl::IDNS_Ordinary) {
132 // If this is a builtin on some other target, or if this builtin varies
133 // across targets (e.g. in type), emit a diagnostic and mark the translation
134 // unit non-portable for using it.
135 if (II->isNonPortableBuiltin()) {
136 // Only emit this diagnostic once for this builtin.
137 II->setNonPortableBuiltin(false);
Ted Kremenek1daa3cf2007-12-12 22:39:36 +0000138 Context.Target.DiagnoseNonPortability(Context.getFullLoc(IdLoc),
Chris Lattner9561a0b2007-01-28 08:20:04 +0000139 diag::port_target_builtin_use);
140 }
Chris Lattner9561a0b2007-01-28 08:20:04 +0000141 // If this is a builtin on this (or all) targets, create the decl.
142 if (unsigned BuiltinID = II->getBuiltinID())
143 return LazilyCreateBuiltin(II, BuiltinID, S);
144 }
Chris Lattner18b19622007-01-22 07:39:13 +0000145 return 0;
146}
147
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000148void Sema::InitBuiltinVaListType()
149{
150 if (!Context.getBuiltinVaListType().isNull())
151 return;
152
153 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
154 ScopedDecl *VaDecl = LookupScopedDecl(VaIdent, Decl::IDNS_Ordinary,
155 SourceLocation(), TUScope);
Steve Naroffeee59eb2007-10-18 22:17:45 +0000156 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000157 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
158}
159
Chris Lattner9561a0b2007-01-28 08:20:04 +0000160/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
161/// lazily create a decl for it.
Chris Lattner9c7a0362007-10-10 23:42:28 +0000162ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
163 Scope *S) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000164 Builtin::ID BID = (Builtin::ID)bid;
165
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000166 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson24ebce62007-10-12 23:56:29 +0000167 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000168 BID == Builtin::BI__builtin_va_end)
169 InitBuiltinVaListType();
170
Anders Carlsson87c149b2007-10-11 01:00:40 +0000171 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner776fac82007-06-09 00:53:06 +0000172 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattnerb677a932007-08-26 04:02:13 +0000173 FunctionDecl::Extern, false, 0);
Chris Lattner9561a0b2007-01-28 08:20:04 +0000174
175 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000176 if (Scope *FnS = S->getFnParent())
177 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner9561a0b2007-01-28 08:20:04 +0000178 while (S->getParent())
179 S = S->getParent();
180 S->AddDecl(New);
181
182 // Add this decl to the end of the identifier info.
Steve Naroff9324db12007-09-13 18:10:37 +0000183 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000184 // Scan until we find the last (outermost) decl in the id chain.
185 while (LastDecl->getNext())
186 LastDecl = LastDecl->getNext();
187 // Insert before (outside) it.
188 LastDecl->setNext(New);
189 } else {
190 II->setFETokenInfo(New);
191 }
Chris Lattner9561a0b2007-01-28 08:20:04 +0000192 return New;
193}
194
Chris Lattner01564d92007-01-27 19:27:06 +0000195/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
196/// and scope as a previous declaration 'Old'. Figure out how to resolve this
197/// situation, merging decls or emitting diagnostics as appropriate.
198///
Steve Naroff9def2b12007-09-13 21:41:19 +0000199TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000200 // Verify the old decl was also a typedef.
201 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
202 if (!Old) {
203 Diag(New->getLocation(), diag::err_redefinition_different_kind,
204 New->getName());
205 Diag(OldD->getLocation(), diag::err_previous_definition);
206 return New;
207 }
208
Steve Naroff6d40db02007-10-31 18:42:27 +0000209 // Allow multiple definitions for ObjC built-in typedefs.
210 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000211 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff6d40db02007-10-31 18:42:27 +0000212 return Old;
213
Chris Lattner01564d92007-01-27 19:27:06 +0000214 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
215 // TODO: This is totally simplistic. It should handle merging functions
216 // together etc, merging extern int X; int X; ...
217 Diag(New->getLocation(), diag::err_redefinition, New->getName());
218 Diag(Old->getLocation(), diag::err_previous_definition);
219 return New;
220}
221
222/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
223/// and scope as a previous declaration 'Old'. Figure out how to resolve this
224/// situation, merging decls or emitting diagnostics as appropriate.
225///
Steve Naroff9def2b12007-09-13 21:41:19 +0000226FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000227 // Verify the old decl was also a function.
228 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
229 if (!Old) {
230 Diag(New->getLocation(), diag::err_redefinition_different_kind,
231 New->getName());
232 Diag(OldD->getLocation(), diag::err_previous_definition);
233 return New;
234 }
235
Chris Lattner5c3f1542007-11-20 19:04:50 +0000236 QualType OldQType = Old->getCanonicalType();
237 QualType NewQType = New->getCanonicalType();
238
239 // This is not right, but it's a start.
240 // If Old is a function prototype with no defined arguments we only compare
241 // the return type; If arguments are defined on the prototype we validate the
242 // entire function type.
243 // FIXME: We should link up decl objects here.
244 if (Old->getBody() == 0) {
245 if (OldQType.getTypePtr()->getTypeClass() == Type::FunctionNoProto &&
246 Old->getResultType() == New->getResultType())
247 return New;
Chris Lattnerefe4aea2007-01-27 19:35:39 +0000248 }
Steve Naroff012484d2008-01-14 20:51:29 +0000249 // Function types need to be compatible, not identical. This handles
250 // duplicate function decls like "void f(int); void f(enum X);" properly.
251 if (Context.functionTypesAreCompatible(OldQType, NewQType))
252 return New;
Chris Lattner45d561a2007-11-06 06:07:26 +0000253
Steve Naroff17832a42008-01-16 15:01:34 +0000254 // A function that has already been declared has been redeclared or defined
255 // with a different type- show appropriate diagnostic
256 diag::kind PrevDiag = Old->getBody() ? diag::err_previous_definition :
257 diag::err_previous_declaration;
258
Chris Lattner01564d92007-01-27 19:27:06 +0000259 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
260 // TODO: This is totally simplistic. It should handle merging functions
261 // together etc, merging extern int X; int X; ...
Steve Naroff17832a42008-01-16 15:01:34 +0000262 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
263 Diag(Old->getLocation(), PrevDiag);
Chris Lattner01564d92007-01-27 19:27:06 +0000264 return New;
265}
266
Chris Lattner32097252007-11-06 04:28:31 +0000267
268/// hasUndefinedLength - Used by equivalentArrayTypes to determine whether the
269/// the outermost VariableArrayType has no size defined.
270static bool hasUndefinedLength(const ArrayType *Array) {
271 const VariableArrayType *VAT = Array->getAsVariableArrayType();
272 return VAT && !VAT->getSizeExpr();
273}
274
275/// equivalentArrayTypes - Used to determine whether two array types are
276/// equivalent.
277/// We need to check this explicitly as an incomplete array definition is
278/// considered a VariableArrayType, so will not match a complete array
279/// definition that would be otherwise equivalent.
280static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
281 const ArrayType *NewAT = NewQType->getAsArrayType();
282 const ArrayType *OldAT = OldQType->getAsArrayType();
283
284 if (!NewAT || !OldAT)
285 return false;
286
287 // If either (or both) array types in incomplete we need to strip off the
288 // outer VariableArrayType. Once the outer VAT is removed the remaining
289 // types must be identical if the array types are to be considered
290 // equivalent.
291 // eg. int[][1] and int[1][1] become
292 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
293 // removing the outermost VAT gives
294 // CAT(1, int) and CAT(1, int)
295 // which are equal, therefore the array types are equivalent.
296 if (hasUndefinedLength(NewAT) || hasUndefinedLength(OldAT)) {
297 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
298 return false;
Eli Friedman361de612008-01-29 07:51:12 +0000299 NewQType = NewAT->getElementType().getCanonicalType();
300 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattner32097252007-11-06 04:28:31 +0000301 }
302
303 return NewQType == OldQType;
304}
305
Chris Lattner01564d92007-01-27 19:27:06 +0000306/// MergeVarDecl - We just parsed a variable 'New' which has the same name
307/// and scope as a previous declaration 'Old'. Figure out how to resolve this
308/// situation, merging decls or emitting diagnostics as appropriate.
309///
Steve Narofffc49d672007-04-01 21:27:45 +0000310/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
311/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
312///
Steve Naroff9def2b12007-09-13 21:41:19 +0000313VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000314 // Verify the old decl was also a variable.
315 VarDecl *Old = dyn_cast<VarDecl>(OldD);
316 if (!Old) {
317 Diag(New->getLocation(), diag::err_redefinition_different_kind,
318 New->getName());
319 Diag(OldD->getLocation(), diag::err_previous_definition);
320 return New;
321 }
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000322 // Verify the types match.
Chris Lattner32097252007-11-06 04:28:31 +0000323 if (Old->getCanonicalType() != New->getCanonicalType() &&
324 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000325 Diag(New->getLocation(), diag::err_redefinition, New->getName());
326 Diag(Old->getLocation(), diag::err_previous_definition);
327 return New;
328 }
Steve Naroff1e787362008-01-30 00:44:01 +0000329 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
330 if (New->getStorageClass() == VarDecl::Static &&
331 (Old->getStorageClass() == VarDecl::None ||
332 Old->getStorageClass() == VarDecl::Extern)) {
333 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
334 Diag(Old->getLocation(), diag::err_previous_definition);
335 return New;
336 }
337 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
338 if (New->getStorageClass() != VarDecl::Static &&
339 Old->getStorageClass() == VarDecl::Static) {
340 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
341 Diag(Old->getLocation(), diag::err_previous_definition);
342 return New;
343 }
344 // We've verified the types match, now handle "tentative" definitions.
345 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
346 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
347
348 if (OldFSDecl && NewFSDecl) {
349 // Handle C "tentative" external object definitions (C99 6.9.2).
350 bool OldIsTentative = false;
351 bool NewIsTentative = false;
352
353 if (!OldFSDecl->getInit() &&
354 (OldFSDecl->getStorageClass() == VarDecl::None ||
355 OldFSDecl->getStorageClass() == VarDecl::Static))
356 OldIsTentative = true;
357
358 // FIXME: this check doesn't work (since the initializer hasn't been
359 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
360 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
361 // thrown out the old decl.
362 if (!NewFSDecl->getInit() &&
363 (NewFSDecl->getStorageClass() == VarDecl::None ||
364 NewFSDecl->getStorageClass() == VarDecl::Static))
365 ; // change to NewIsTentative = true; once the code is moved.
366
367 if (NewIsTentative || OldIsTentative)
368 return New;
369 }
370 if (Old->getStorageClass() != VarDecl::Extern &&
371 New->getStorageClass() != VarDecl::Extern) {
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000372 Diag(New->getLocation(), diag::err_redefinition, New->getName());
373 Diag(Old->getLocation(), diag::err_previous_definition);
374 }
Chris Lattner01564d92007-01-27 19:27:06 +0000375 return New;
376}
377
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000378/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
379/// no declarator (e.g. "struct foo;") is parsed.
380Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
381 // TODO: emit error on 'int;' or 'const enum foo;'.
382 // TODO: emit error on 'typedef int;'
383 // if (!DS.isMissingDeclaratorOk()) Diag(...);
384
Steve Naroff14f5f792007-11-17 21:37:36 +0000385 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000386}
387
Steve Naroff98f72032008-01-10 22:15:12 +0000388bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroff2fea1392007-09-02 02:04:30 +0000389 // Get the type before calling CheckSingleAssignmentConstraints(), since
390 // it can promote the expression.
Chris Lattner9bad62c2008-01-04 18:04:52 +0000391 QualType InitType = Init->getType();
Steve Naroff2fea1392007-09-02 02:04:30 +0000392
Chris Lattner9bad62c2008-01-04 18:04:52 +0000393 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
394 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
395 InitType, Init, "initializing");
Steve Naroff2fea1392007-09-02 02:04:30 +0000396}
397
Steve Naroff77b97002007-09-04 14:36:54 +0000398bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroff98f72032008-01-10 22:15:12 +0000399 QualType ElementType) {
Chris Lattnerf6412552007-12-11 23:15:04 +0000400 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff98f72032008-01-10 22:15:12 +0000401 if (CheckSingleInitializer(expr, ElementType))
Chris Lattnerf6412552007-12-11 23:15:04 +0000402 return true; // types weren't compatible.
403
Steve Naroff77b97002007-09-04 14:36:54 +0000404 if (savExpr != expr) // The type was promoted, update initializer list.
405 IList->setInit(slot, expr);
Steve Naroffac074b42007-09-04 02:20:04 +0000406 return false;
407}
408
Steve Naroffaf2a0222008-01-22 00:55:40 +0000409bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
410 if (const VariableArrayType *VAT = DeclT->getAsIncompleteArrayType()) {
411 // C99 6.7.8p14. We have an array of character type with unknown size
412 // being initialized to a string literal.
413 llvm::APSInt ConstVal(32);
414 ConstVal = strLiteral->getByteLength() + 1;
415 // Return a new array type (C99 6.7.8p22).
416 DeclT = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
417 ArrayType::Normal, 0);
418 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
419 // C99 6.7.8p14. We have an array of character type with known size.
420 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
421 Diag(strLiteral->getSourceRange().getBegin(),
422 diag::warn_initializer_string_for_char_array_too_long,
423 strLiteral->getSourceRange());
424 } else {
425 assert(0 && "HandleStringLiteralInit(): Invalid array type");
426 }
427 // Set type from "char *" to "constant array of char".
428 strLiteral->setType(DeclT);
429 // For now, we always return false (meaning success).
430 return false;
431}
432
433StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffaf2a0222008-01-22 00:55:40 +0000434 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000435 if (AT && AT->getElementType()->isCharType()) {
436 return dyn_cast<StringLiteral>(Init);
437 }
Steve Naroffaf2a0222008-01-22 00:55:40 +0000438 return 0;
439}
440
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000441// CheckInitializerListTypes - Checks the types of elements of an initializer
442// list. This function is recursive: it calls itself to initialize subelements
443// of aggregate types. Note that the topLevel parameter essentially refers to
444// whether this expression "owns" the initializer list passed in, or if this
445// initialization is taking elements out of a parent initializer. Each
446// call to this function adds zero or more to startIndex, reports any errors,
447// and returns true if it found any inconsistent types.
448bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
449 bool topLevel, unsigned& startIndex) {
Steve Naroff91f78082007-12-10 22:44:33 +0000450 bool hadError = false;
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000451
452 if (DeclType->isScalarType()) {
453 // The simplest case: initializing a single scalar
454 if (topLevel) {
455 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
456 IList->getSourceRange());
457 }
458 if (startIndex < IList->getNumInits()) {
459 Expr* expr = IList->getInit(startIndex);
460 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
461 // FIXME: Should an error be reported here instead?
462 unsigned newIndex = 0;
463 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
464 } else {
465 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
466 }
467 ++startIndex;
468 }
469 // FIXME: Should an error be reported for empty initializer list + scalar?
470 } else if (DeclType->isVectorType()) {
471 if (startIndex < IList->getNumInits()) {
472 const VectorType *VT = DeclType->getAsVectorType();
473 int maxElements = VT->getNumElements();
474 QualType elementType = VT->getElementType();
475
476 for (int i = 0; i < maxElements; ++i) {
477 // Don't attempt to go past the end of the init list
478 if (startIndex >= IList->getNumInits())
479 break;
480 Expr* expr = IList->getInit(startIndex);
481 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
482 unsigned newIndex = 0;
483 hadError |= CheckInitializerListTypes(SubInitList, elementType,
484 true, newIndex);
485 ++startIndex;
486 } else {
487 hadError |= CheckInitializerListTypes(IList, elementType,
488 false, startIndex);
489 }
490 }
491 }
492 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
493 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroffaeb6b302008-01-28 02:00:41 +0000494 if (startIndex < IList->getNumInits() && !topLevel &&
495 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
496 DeclType)) {
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000497 // We found a compatible struct; per the standard, this initializes the
498 // struct. (The C standard technically says that this only applies for
499 // initializers for declarations with automatic scope; however, this
500 // construct is unambiguous anyway because a struct cannot contain
501 // a type compatible with itself. We'll output an error when we check
502 // if the initializer is constant.)
503 // FIXME: Is a call to CheckSingleInitializer required here?
504 ++startIndex;
505 } else {
506 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
507 // If structDecl is a forward declaration, this loop won't do anything;
508 // That's okay, because an error should get printed out elsewhere. It
509 // might be worthwhile to skip over the rest of the initializer, though.
510 int numMembers = structDecl->getNumMembers() -
511 structDecl->hasFlexibleArrayMember();
512 for (int i = 0; i < numMembers; i++) {
513 // Don't attempt to go past the end of the init list
514 if (startIndex >= IList->getNumInits())
515 break;
516 FieldDecl * curField = structDecl->getMember(i);
517 if (!curField->getIdentifier()) {
518 // Don't initialize unnamed fields, e.g. "int : 20;"
519 continue;
520 }
521 QualType fieldType = curField->getType();
522 Expr* expr = IList->getInit(startIndex);
523 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
524 unsigned newStart = 0;
525 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
526 true, newStart);
527 ++startIndex;
528 } else {
529 hadError |= CheckInitializerListTypes(IList, fieldType,
530 false, startIndex);
531 }
532 if (DeclType->isUnionType())
533 break;
534 }
535 // FIXME: Implement flexible array initialization GCC extension (it's a
536 // really messy extension to implement, unfortunately...the necessary
537 // information isn't actually even here!)
538 }
539 } else if (DeclType->isArrayType()) {
540 // Check for the special-case of initializing an array with a string.
541 if (startIndex < IList->getNumInits()) {
542 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
543 DeclType)) {
544 CheckStringLiteralInit(lit, DeclType);
545 ++startIndex;
546 if (topLevel && startIndex < IList->getNumInits()) {
547 // We have leftover initializers; warn
548 Diag(IList->getInit(startIndex)->getLocStart(),
549 diag::err_excess_initializers_in_char_array_initializer,
550 IList->getInit(startIndex)->getSourceRange());
551 }
552 return false;
553 }
554 }
555 int maxElements;
556 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
557 // FIXME: use a proper constant
558 maxElements = 0x7FFFFFFF;
559 // Check for VLAs; in standard C it would be possible to check this
560 // earlier, but I don't know where clang accepts VLAs (gcc accepts
561 // them in all sorts of strange places).
562 if (const Expr *expr = VAT->getSizeExpr()) {
563 Diag(expr->getLocStart(), diag::err_variable_object_no_init,
564 expr->getSourceRange());
565 hadError = true;
566 }
567 } else {
568 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
569 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
570 }
571 QualType elementType = DeclType->getAsArrayType()->getElementType();
572 int numElements = 0;
573 for (int i = 0; i < maxElements; ++i, ++numElements) {
574 // Don't attempt to go past the end of the init list
575 if (startIndex >= IList->getNumInits())
576 break;
577 Expr* expr = IList->getInit(startIndex);
578 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
579 unsigned newIndex = 0;
580 hadError |= CheckInitializerListTypes(SubInitList, elementType,
581 true, newIndex);
582 ++startIndex;
583 } else {
584 hadError |= CheckInitializerListTypes(IList, elementType,
585 false, startIndex);
586 }
587 }
588 if (DeclType->getAsVariableArrayType()) {
589 // If this is an incomplete array type, the actual type needs to
590 // be calculated here
591 if (numElements == 0) {
592 // Sizing an array implicitly to zero is not allowed
593 // (It could in theory be allowed, but it doesn't really matter.)
594 Diag(IList->getLocStart(),
595 diag::err_at_least_one_initializer_needed_to_size_array);
596 hadError = true;
597 } else {
598 llvm::APSInt ConstVal(32);
599 ConstVal = numElements;
600 DeclType = Context.getConstantArrayType(elementType, ConstVal,
601 ArrayType::Normal, 0);
602 }
603 }
604 } else {
605 assert(0 && "Aggregate that isn't a function or array?!");
606 }
607 } else {
608 // In C, all types are either scalars or aggregates, but
609 // additional handling is needed here for C++ (and possibly others?).
610 assert(0 && "Unsupported initializer type");
611 }
612
613 // If this init list is a base list, we set the type; an initializer doesn't
614 // fundamentally have a type, but this makes the ASTs a bit easier to read
615 if (topLevel)
616 IList->setType(DeclType);
617
618 if (topLevel && startIndex < IList->getNumInits()) {
619 // We have leftover initializers; warn
620 Diag(IList->getInit(startIndex)->getLocStart(),
621 diag::warn_excess_initializers,
622 IList->getInit(startIndex)->getSourceRange());
623 }
624 return hadError;
625}
626
627bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Narofff9eb5982008-01-21 23:53:58 +0000628 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
629 // of unknown size ("[]") or an object type that is not a variable array type.
630 if (const VariableArrayType *VAT = DeclType->getAsVariablyModifiedType())
631 return Diag(VAT->getSizeExpr()->getLocStart(),
632 diag::err_variable_object_no_init,
633 VAT->getSizeExpr()->getSourceRange());
634
Steve Naroff91f78082007-12-10 22:44:33 +0000635 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
636 if (!InitList) {
Steve Naroffaf2a0222008-01-22 00:55:40 +0000637 // FIXME: Handle wide strings
638 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
639 return CheckStringLiteralInit(strLiteral, DeclType);
Steve Naroff98f72032008-01-10 22:15:12 +0000640 return CheckSingleInitializer(Init, DeclType);
Steve Naroff91f78082007-12-10 22:44:33 +0000641 }
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000642 unsigned newIndex = 0;
643 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroff2fea1392007-09-02 02:04:30 +0000644}
645
Fariborz Jahanian56ff1462007-11-08 23:49:49 +0000646Sema::DeclTy *
Steve Naroff30d242c2007-09-15 18:49:24 +0000647Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroffa23cc792007-09-13 23:52:58 +0000648 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattnere168f762006-11-10 05:29:30 +0000649 IdentifierInfo *II = D.getIdentifier();
Chris Lattner302b4be2006-11-19 02:31:38 +0000650
Chris Lattner02c04392007-07-25 00:24:17 +0000651 // All of these full declarators require an identifier. If it doesn't have
652 // one, the ParsedFreeStandingDeclSpec action should be used.
653 if (II == 0) {
Chris Lattnera7c19fe2007-10-16 22:36:42 +0000654 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerc4f6d0c2007-08-28 06:17:15 +0000655 diag::err_declarator_need_ident,
Chris Lattner02c04392007-07-25 00:24:17 +0000656 D.getDeclSpec().getSourceRange(), D.getSourceRange());
657 return 0;
658 }
659
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000660 // The scope passed in may not be a decl scope. Zip up the scope tree until
661 // we find one that is.
662 while ((S->getFlags() & Scope::DeclScope) == 0)
663 S = S->getParent();
664
Chris Lattner01564d92007-01-27 19:27:06 +0000665 // See if this is a redefinition of a variable in the same scope.
Steve Naroff9324db12007-09-13 18:10:37 +0000666 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
667 D.getIdentifierLoc(), S);
Steve Naroff9324db12007-09-13 18:10:37 +0000668 ScopedDecl *New;
Steve Narofff93b6722007-08-28 20:14:24 +0000669 bool InvalidDecl = false;
670
Chris Lattner07b201d2007-11-14 06:34:38 +0000671 QualType R = GetTypeForDeclarator(D, S);
672 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
673
Chris Lattner01a7c532007-01-25 23:09:03 +0000674 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner07b201d2007-11-14 06:34:38 +0000675 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner01564d92007-01-27 19:27:06 +0000676 if (!NewTD) return 0;
Steve Naroffa8fd9732007-06-11 00:35:03 +0000677
678 // Handle attributes prior to checking for duplicates in MergeVarDecl
679 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
680 D.getAttributes());
Steve Naroffe6b0ec82008-01-09 23:34:55 +0000681 // Merge the decl with the existing one if appropriate. If the decl is
682 // in an outer scope, it isn't the same thing.
683 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner01564d92007-01-27 19:27:06 +0000684 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
685 if (NewTD == 0) return 0;
686 }
687 New = NewTD;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000688 if (S->getParent() == 0) {
689 // C99 6.7.7p2: If a typedef name specifies a variably modified type
690 // then it shall have block scope.
Steve Naroff096dd942007-08-31 17:20:07 +0000691 if (const VariableArrayType *VAT =
692 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
693 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
694 VAT->getSizeExpr()->getSourceRange());
695 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000696 }
697 }
Chris Lattner07b201d2007-11-14 06:34:38 +0000698 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattnercc61bf52007-09-27 15:15:46 +0000699 FunctionDecl::StorageClass SC = FunctionDecl::None;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000700 switch (D.getDeclSpec().getStorageClassSpec()) {
701 default: assert(0 && "Unknown storage class!");
702 case DeclSpec::SCS_auto:
703 case DeclSpec::SCS_register:
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000704 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
705 R.getAsString());
Steve Narofff93b6722007-08-28 20:14:24 +0000706 InvalidDecl = true;
707 break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000708 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
709 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
710 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff1f7f6922008-01-28 21:57:15 +0000711 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000712 }
713
Chris Lattner776fac82007-06-09 00:53:06 +0000714 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattnerb677a932007-08-26 04:02:13 +0000715 D.getDeclSpec().isInlineSpecified(),
Nate Begemana0f78972007-11-13 22:14:47 +0000716 LastDeclarator,
717 D.getDeclSpec().getAttributes());
718
719 // Transfer ownership of DeclSpec attributes to FunctionDecl
720 D.getDeclSpec().clearAttributes();
Chris Lattner01564d92007-01-27 19:27:06 +0000721
Steve Naroffe6b0ec82008-01-09 23:34:55 +0000722 // Merge the decl with the existing one if appropriate. Since C functions
723 // are in a flat namespace, make sure we consider decls in outer scopes.
Chris Lattner01564d92007-01-27 19:27:06 +0000724 if (PrevDecl) {
725 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
726 if (NewFD == 0) return 0;
727 }
728 New = NewFD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000729 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000730 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +0000731 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
732 D.getIdentifier()->getName());
733 InvalidDecl = true;
734 }
Chris Lattner01564d92007-01-27 19:27:06 +0000735
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000736 VarDecl *NewVD;
737 VarDecl::StorageClass SC;
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000738 switch (D.getDeclSpec().getStorageClassSpec()) {
739 default: assert(0 && "Unknown storage class!");
Steve Narofffda82092008-01-25 22:14:40 +0000740 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
741 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
742 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
743 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
744 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
745 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000746 }
Steve Narofffc49d672007-04-01 21:27:45 +0000747 if (S->getParent() == 0) {
Bill Wendlingd6de6572007-06-02 09:40:07 +0000748 // C99 6.9p2: The storage-class specifiers auto and register shall not
749 // appear in the declaration specifiers in an external declaration.
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000750 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000751 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
752 R.getAsString());
Steve Naroffcf871f52007-08-28 18:45:29 +0000753 InvalidDecl = true;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000754 }
Chris Lattner776fac82007-06-09 00:53:06 +0000755 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff2fea1392007-09-02 02:04:30 +0000756 } else {
Chris Lattner776fac82007-06-09 00:53:06 +0000757 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcf871f52007-08-28 18:45:29 +0000758 }
Steve Naroffa8fd9732007-06-11 00:35:03 +0000759 // Handle attributes prior to checking for duplicates in MergeVarDecl
760 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
761 D.getAttributes());
762
Steve Naroffe6b0ec82008-01-09 23:34:55 +0000763 // Merge the decl with the existing one if appropriate. If the decl is
764 // in an outer scope, it isn't the same thing.
765 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner01564d92007-01-27 19:27:06 +0000766 NewVD = MergeVarDecl(NewVD, PrevDecl);
767 if (NewVD == 0) return 0;
768 }
769 New = NewVD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000770 }
Chris Lattner302b4be2006-11-19 02:31:38 +0000771
Chris Lattnere168f762006-11-10 05:29:30 +0000772 // If this has an identifier, add it to the scope stack.
773 if (II) {
Steve Naroff9324db12007-09-13 18:10:37 +0000774 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattnere168f762006-11-10 05:29:30 +0000775 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000776 S->AddDecl(New);
Chris Lattnere168f762006-11-10 05:29:30 +0000777 }
Steve Narofff93b6722007-08-28 20:14:24 +0000778 // If any semantic error occurred, mark the decl as invalid.
779 if (D.getInvalidType() || InvalidDecl)
780 New->setInvalidDecl();
Chris Lattnere168f762006-11-10 05:29:30 +0000781
782 return New;
783}
784
Steve Naroff98f72032008-01-10 22:15:12 +0000785bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
786 SourceLocation loc;
787 // FIXME: Remove the isReference check and handle assignment to a reference.
788 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
789 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
790 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
791 return true;
792 }
793 return false;
794}
795
Steve Naroff61091402007-09-12 14:07:44 +0000796void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff437b4d82007-09-12 20:13:48 +0000797 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff61091402007-09-12 14:07:44 +0000798 Expr *Init = static_cast<Expr *>(init);
Chris Lattner8beb9de2007-10-19 20:10:30 +0000799 assert(Init && "missing initializer");
Steve Naroff61091402007-09-12 14:07:44 +0000800
Chris Lattner8beb9de2007-10-19 20:10:30 +0000801 // If there is no declaration, there was an error parsing it. Just ignore
802 // the initializer.
803 if (RealDecl == 0) {
804 delete Init;
805 return;
806 }
Steve Naroff61091402007-09-12 14:07:44 +0000807
Steve Naroff437b4d82007-09-12 20:13:48 +0000808 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
809 if (!VDecl) {
Steve Naroff9def2b12007-09-13 21:41:19 +0000810 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
811 diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +0000812 RealDecl->setInvalidDecl();
813 return;
814 }
Steve Naroff61091402007-09-12 14:07:44 +0000815 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +0000816 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +0000817 QualType DclT = VDecl->getType(), SavT = DclT;
818 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff61091402007-09-12 14:07:44 +0000819 VarDecl::StorageClass SC = BVD->getStorageClass();
820 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +0000821 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff61091402007-09-12 14:07:44 +0000822 BVD->setInvalidDecl();
823 } else if (!BVD->isInvalidDecl()) {
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000824 if (CheckInitializerTypes(Init, DclT))
825 BVD->setInvalidDecl();
Steve Naroff98f72032008-01-10 22:15:12 +0000826 if (SC == VarDecl::Static) // C99 6.7.8p4.
827 CheckForConstantInitializer(Init, DclT);
Steve Naroff61091402007-09-12 14:07:44 +0000828 }
Steve Naroff437b4d82007-09-12 20:13:48 +0000829 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff61091402007-09-12 14:07:44 +0000830 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff437b4d82007-09-12 20:13:48 +0000831 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff61091402007-09-12 14:07:44 +0000832 if (!FVD->isInvalidDecl())
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000833 if (CheckInitializerTypes(Init, DclT))
834 FVD->setInvalidDecl();
Steve Naroff98f72032008-01-10 22:15:12 +0000835
836 // C99 6.7.8p4. All file scoped initializers need to be constant.
837 CheckForConstantInitializer(Init, DclT);
Steve Naroff61091402007-09-12 14:07:44 +0000838 }
839 // If the type changed, it means we had an incomplete type that was
840 // completed by the initializer. For example:
841 // int ary[] = { 1, 3, 5 };
842 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb2ed9afd2007-11-29 19:09:19 +0000843 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff437b4d82007-09-12 20:13:48 +0000844 VDecl->setType(DclT);
Christopher Lamb2ed9afd2007-11-29 19:09:19 +0000845 Init->setType(DclT);
846 }
Steve Naroff61091402007-09-12 14:07:44 +0000847
848 // Attach the initializer to the decl.
Steve Naroff437b4d82007-09-12 20:13:48 +0000849 VDecl->setInit(Init);
Steve Naroff61091402007-09-12 14:07:44 +0000850 return;
851}
852
Chris Lattner776fac82007-06-09 00:53:06 +0000853/// The declarators are chained together backwards, reverse the list.
854Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
855 // Often we have single declarators, handle them quickly.
Steve Naroffa23cc792007-09-13 23:52:58 +0000856 Decl *GroupDecl = static_cast<Decl*>(group);
857 if (GroupDecl == 0)
Steve Naroff61091402007-09-12 14:07:44 +0000858 return 0;
Steve Naroffa23cc792007-09-13 23:52:58 +0000859
860 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
861 ScopedDecl *NewGroup = 0;
Steve Naroff61091402007-09-12 14:07:44 +0000862 if (Group->getNextDeclarator() == 0)
Chris Lattner776fac82007-06-09 00:53:06 +0000863 NewGroup = Group;
Steve Naroff61091402007-09-12 14:07:44 +0000864 else { // reverse the list.
865 while (Group) {
Steve Naroffa23cc792007-09-13 23:52:58 +0000866 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff61091402007-09-12 14:07:44 +0000867 Group->setNextDeclarator(NewGroup);
868 NewGroup = Group;
869 Group = Next;
870 }
871 }
872 // Perform semantic analysis that depends on having fully processed both
873 // the declarator and initializer.
Steve Naroffa23cc792007-09-13 23:52:58 +0000874 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff61091402007-09-12 14:07:44 +0000875 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
876 if (!IDecl)
877 continue;
878 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
879 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
880 QualType T = IDecl->getType();
881
882 // C99 6.7.5.2p2: If an identifier is declared to be an object with
883 // static storage duration, it shall not have a variable length array.
884 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
885 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
886 if (VLA->getSizeExpr()) {
887 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
888 IDecl->setInvalidDecl();
889 }
890 }
891 }
892 // Block scope. C99 6.7p7: If an identifier for an object is declared with
893 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
894 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
895 if (T->isIncompleteType()) {
Chris Lattner310369f2007-12-02 07:50:03 +0000896 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
897 T.getAsString());
Steve Naroff61091402007-09-12 14:07:44 +0000898 IDecl->setInvalidDecl();
899 }
900 }
901 // File scope. C99 6.9.2p2: A declaration of an identifier for and
902 // object that has file scope without an initializer, and without a
903 // storage-class specifier or with the storage-class specifier "static",
904 // constitutes a tentative definition. Note: A tentative definition with
905 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb716fba2008-01-18 00:39:39 +0000906 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
907 FVD->getStorageClass() == VarDecl::None)) {
Steve Naroffacb6fa62008-01-18 20:40:52 +0000908 const VariableArrayType *VAT = T->getAsVariableArrayType();
909
910 if (VAT && VAT->getSizeExpr() == 0) {
911 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
912 // array to be completed. Don't issue a diagnostic.
913 } else if (T->isIncompleteType()) {
914 // C99 6.9.2p3: If the declaration of an identifier for an object is
915 // a tentative definition and has internal linkage (C99 6.2.2p3), the
916 // declared type shall not be an incomplete type.
Chris Lattner310369f2007-12-02 07:50:03 +0000917 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
918 T.getAsString());
Steve Naroff61091402007-09-12 14:07:44 +0000919 IDecl->setInvalidDecl();
920 }
921 }
Chris Lattner776fac82007-06-09 00:53:06 +0000922 }
923 return NewGroup;
924}
Steve Naroff7e6f7c22007-08-28 03:03:08 +0000925
926// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner53621a52007-06-13 20:44:40 +0000927ParmVarDecl *
Nate Begeman313f8ca2007-11-13 21:49:48 +0000928Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI, Scope *FnScope)
Steve Naroffd0bf5162007-11-12 03:44:46 +0000929{
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000930 IdentifierInfo *II = PI.Ident;
Chris Lattnerc284e9b2007-01-23 05:14:32 +0000931 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
932 // Can this happen for params? We already checked that they don't conflict
933 // among each other. Here they can only shadow globals, which is ok.
Chris Lattnerd2b88ab2007-07-13 03:05:23 +0000934 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Chris Lattner9561a0b2007-01-28 08:20:04 +0000935 PI.IdentLoc, FnScope)) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000936
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000937 }
938
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000939 // FIXME: Handle storage class (auto, register). No declarator?
Chris Lattner776fac82007-06-09 00:53:06 +0000940 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff773df5c2007-08-07 22:44:21 +0000941
942 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
943 // Doing the promotion here has a win and a loss. The win is the type for
944 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
945 // code generator). The loss is the orginal type isn't preserved. For example:
946 //
947 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
948 // int blockvardecl[5];
949 // sizeof(parmvardecl); // size == 4
950 // sizeof(blockvardecl); // size == 20
951 // }
952 //
953 // For expressions, all implicit conversions are captured using the
954 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
955 //
956 // FIXME: If a source translation tool needs to see the original type, then
957 // we need to consider storing both types (in ParmVarDecl)...
958 //
959 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattner4f203512008-01-02 22:50:48 +0000960 if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
961 // int x[restrict 4] -> int *restrict
Steve Naroff773df5c2007-08-07 22:44:21 +0000962 parmDeclType = Context.getPointerType(AT->getElementType());
Chris Lattner4f203512008-01-02 22:50:48 +0000963 parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
964 } else if (parmDeclType->isFunctionType())
Steve Naroff773df5c2007-08-07 22:44:21 +0000965 parmDeclType = Context.getPointerType(parmDeclType);
966
967 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Nate Begemana0f78972007-11-13 22:14:47 +0000968 VarDecl::None, 0, PI.AttrList);
Steve Naroffcf871f52007-08-28 18:45:29 +0000969 if (PI.InvalidType)
970 New->setInvalidDecl();
971
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000972 // If this has an identifier, add it to the scope stack.
973 if (II) {
Steve Naroff9324db12007-09-13 18:10:37 +0000974 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000975 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000976 FnScope->AddDecl(New);
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000977 }
Chris Lattner229ce602006-11-21 01:21:07 +0000978
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000979 return New;
980}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +0000981
Chris Lattnera55a2cc2007-10-09 17:14:05 +0000982Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner229ce602006-11-21 01:21:07 +0000983 assert(CurFunctionDecl == 0 && "Function parsing confused");
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000984 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
985 "Not a function declarator!");
986 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
987
988 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
989 // for a K&R function.
990 if (!FTI.hasPrototype) {
991 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
992 if (FTI.ArgInfo[i].TypeInfo == 0) {
Chris Lattner843c5922007-06-10 23:40:34 +0000993 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000994 FTI.ArgInfo[i].Ident->getName());
995 // Implicitly declare the argument as type 'int' for lack of a better
996 // type.
997 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
998 }
999 }
1000
1001 // Since this is a function definition, act as though we have information
1002 // about the arguments.
1003 FTI.hasPrototype = true;
Chris Lattner2114d5e2006-12-04 07:40:24 +00001004 } else {
1005 // FIXME: Diagnose arguments without names in C.
1006
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001007 }
1008
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001009 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00001010
1011 // See if this is a redefinition.
1012 ScopedDecl *PrevDcl = LookupScopedDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1013 D.getIdentifierLoc(), GlobalScope);
1014 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1015 if (FD->getBody()) {
1016 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1017 D.getIdentifier()->getName());
1018 Diag(FD->getLocation(), diag::err_previous_definition);
1019 }
1020 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001021 FunctionDecl *FD =
Steve Naroff30d242c2007-09-15 18:49:24 +00001022 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Steve Naroff012484d2008-01-14 20:51:29 +00001023 assert(FD != 0 && "ActOnDeclarator() didn't return a FunctionDecl");
Chris Lattner229ce602006-11-21 01:21:07 +00001024 CurFunctionDecl = FD;
Chris Lattner2114d5e2006-12-04 07:40:24 +00001025
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001026 // Create Decl objects for each parameter, adding them to the FunctionDecl.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001027 llvm::SmallVector<ParmVarDecl*, 16> Params;
Chris Lattnerf61c8a82007-01-21 19:04:43 +00001028
1029 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1030 // no arguments, not a function that takes a single void argument.
1031 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerdb2a6ef2007-11-28 18:51:29 +00001032 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getQualifiers() &&
1033 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Chris Lattner99d31772007-01-21 22:37:37 +00001034 // empty arg list, don't push any params.
Chris Lattnerf61c8a82007-01-21 19:04:43 +00001035 } else {
Steve Naroffd0bf5162007-11-12 03:44:46 +00001036 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begeman313f8ca2007-11-13 21:49:48 +00001037 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroffd0bf5162007-11-12 03:44:46 +00001038 FnBodyScope));
1039 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00001040 }
Chris Lattner2114d5e2006-12-04 07:40:24 +00001041
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001042 FD->setParams(&Params[0], Params.size());
Chris Lattner2114d5e2006-12-04 07:40:24 +00001043
Chris Lattnere168f762006-11-10 05:29:30 +00001044 return FD;
1045}
1046
Steve Naroffb313fc32007-11-11 23:20:51 +00001047Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1048 Decl *dcl = static_cast<Decl *>(D);
1049 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1050 FD->setBody((Stmt*)Body);
1051 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroffd78c81b2007-12-13 18:18:56 +00001052 CurFunctionDecl = 0;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001053 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffb313fc32007-11-11 23:20:51 +00001054 MD->setBody((Stmt*)Body);
Steve Naroffe3d1ab22007-11-12 13:56:41 +00001055 CurMethodDecl = 0;
Steve Naroffd78c81b2007-12-13 18:18:56 +00001056 }
Chris Lattnere2473062007-05-28 06:28:18 +00001057 // Verify and clean out per-function state.
1058
1059 // Check goto/label use.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001060 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1061 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
Chris Lattnere2473062007-05-28 06:28:18 +00001062 // Verify that we have no forward references left. If so, there was a goto
1063 // or address of a label taken, but no definition of it. Label fwd
1064 // definitions are indicated with a null substmt.
1065 if (I->second->getSubStmt() == 0) {
1066 LabelStmt *L = I->second;
1067 // Emit error.
Chris Lattnereefa10e2007-05-28 06:56:27 +00001068 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
Chris Lattnere2473062007-05-28 06:28:18 +00001069
1070 // At this point, we have gotos that use the bogus label. Stitch it into
1071 // the function body so that they aren't leaked and that the AST is well
1072 // formed.
Chris Lattner3efff542008-01-25 00:01:10 +00001073 if (Body) {
1074 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1075 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1076 } else {
1077 // The whole function wasn't parsed correctly, just delete this.
1078 delete L;
1079 }
Chris Lattnere2473062007-05-28 06:28:18 +00001080 }
1081 }
1082 LabelMap.clear();
1083
Steve Naroffb313fc32007-11-11 23:20:51 +00001084 return D;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00001085}
1086
Chris Lattnerac18be92006-11-20 06:49:47 +00001087/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1088/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff2f742082007-09-16 16:16:00 +00001089ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1090 IdentifierInfo &II, Scope *S) {
Chris Lattnerac18be92006-11-20 06:49:47 +00001091 if (getLangOptions().C99) // Extension in C99.
1092 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1093 else // Legal in C90, but warn about it.
1094 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1095
1096 // FIXME: handle stuff like:
1097 // void foo() { extern float X(); }
1098 // void bar() { X(); } <-- implicit decl for X in another scope.
1099
1100 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00001101 const char *Dummy;
Chris Lattnerac18be92006-11-20 06:49:47 +00001102 DeclSpec DS;
Chris Lattnerb20e8942006-11-28 05:30:29 +00001103 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001104 Error = Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00001105 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00001106 Declarator D(DS, Declarator::BlockContext);
Chris Lattnercbc426d2006-12-02 06:43:02 +00001107 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
Chris Lattnerac18be92006-11-20 06:49:47 +00001108 D.SetIdentifier(&II, Loc);
1109
Chris Lattner62d2e662007-01-28 00:21:37 +00001110 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001111 if (Scope *FnS = S->getFnParent())
1112 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner62d2e662007-01-28 00:21:37 +00001113 while (S->getParent())
1114 S = S->getParent();
Chris Lattnerac18be92006-11-20 06:49:47 +00001115
Steve Naroff2f742082007-09-16 16:16:00 +00001116 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattnerac18be92006-11-20 06:49:47 +00001117}
1118
Chris Lattner302b4be2006-11-19 02:31:38 +00001119
Chris Lattner07b201d2007-11-14 06:34:38 +00001120TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroffa23cc792007-09-13 23:52:58 +00001121 ScopedDecl *LastDeclarator) {
Chris Lattner776fac82007-06-09 00:53:06 +00001122 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00001123 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001124
Chris Lattner18b19622007-01-22 07:39:13 +00001125 // Scope manipulation handled by caller.
Steve Narofff93b6722007-08-28 20:14:24 +00001126 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
1127 T, LastDeclarator);
1128 if (D.getInvalidType())
1129 NewTD->setInvalidDecl();
1130 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00001131}
1132
Steve Naroff30d242c2007-09-15 18:49:24 +00001133/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00001134/// former case, Name will be non-null. In the later case, Name will be null.
1135/// TagType indicates what kind of tag this is. TK indicates whether this is a
1136/// reference/declaration/definition of a tag.
Steve Naroff30d242c2007-09-15 18:49:24 +00001137Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001138 SourceLocation KWLoc, IdentifierInfo *Name,
Steve Naroffb3096442007-06-09 03:47:53 +00001139 SourceLocation NameLoc, AttributeList *Attr) {
Chris Lattner8799cf22007-01-23 01:57:16 +00001140 // If this is a use of an existing tag, it must have a name.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001141 assert((Name != 0 || TK == TK_Definition) &&
1142 "Nameless record must be a definition!");
Chris Lattner8799cf22007-01-23 01:57:16 +00001143
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001144 Decl::Kind Kind;
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001145 switch (TagType) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001146 default: assert(0 && "Unknown tag type!");
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001147 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1148 case DeclSpec::TST_union: Kind = Decl::Union; break;
1149//case DeclSpec::TST_class: Kind = Decl::Class; break;
1150 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001151 }
Chris Lattner7e783a12007-01-23 02:05:42 +00001152
Chris Lattner18b19622007-01-22 07:39:13 +00001153 // If this is a named struct, check to see if there was a previous forward
1154 // declaration or definition.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001155 if (TagDecl *PrevDecl =
Chris Lattner9561a0b2007-01-28 08:20:04 +00001156 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1157 NameLoc, S))) {
Chris Lattner8799cf22007-01-23 01:57:16 +00001158
1159 // If this is a use of a previous tag, or if the tag is already declared in
1160 // the same scope (so that the definition/declaration completes or
1161 // rementions the tag), reuse the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001162 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
Chris Lattner7e783a12007-01-23 02:05:42 +00001163 // Make sure that this wasn't declared as an enum and now used as a struct
1164 // or something similar.
1165 if (PrevDecl->getKind() != Kind) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001166 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
Chris Lattner7e783a12007-01-23 02:05:42 +00001167 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1168 }
Chris Lattner7b9ace62007-01-23 20:11:08 +00001169
1170 // If this is a use or a forward declaration, we're good.
1171 if (TK != TK_Definition)
1172 return PrevDecl;
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001173
Chris Lattner7b9ace62007-01-23 20:11:08 +00001174 // Diagnose attempts to redefine a tag.
1175 if (PrevDecl->isDefinition()) {
1176 Diag(NameLoc, diag::err_redefinition, Name->getName());
1177 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1178 // If this is a redefinition, recover by making this struct be
1179 // anonymous, which will make any later references get the previous
1180 // definition.
1181 Name = 0;
1182 } else {
1183 // Okay, this is definition of a previously declared or referenced tag.
1184 // Move the location of the decl to be the definition site.
1185 PrevDecl->setLocation(NameLoc);
Chris Lattner7b9ace62007-01-23 20:11:08 +00001186 return PrevDecl;
1187 }
Chris Lattner8799cf22007-01-23 01:57:16 +00001188 }
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001189 // If we get here, this is a definition of a new struct type in a nested
1190 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1191 // type.
Chris Lattner18b19622007-01-22 07:39:13 +00001192 }
1193
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001194 // If there is an identifier, use the location of the identifier as the
1195 // location of the decl, otherwise use the location of the struct/union
1196 // keyword.
1197 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1198
Chris Lattner18b19622007-01-22 07:39:13 +00001199 // Otherwise, if this is the first time we've seen this tag, create the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001200 TagDecl *New;
Chris Lattner720a0542007-01-25 00:44:24 +00001201 switch (Kind) {
1202 default: assert(0 && "Unknown tag kind!");
Chris Lattner5f521502007-01-25 06:27:24 +00001203 case Decl::Enum:
Chris Lattner776fac82007-06-09 00:53:06 +00001204 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1205 // enum X { A, B, C } D; D should chain to X.
1206 New = new EnumDecl(Loc, Name, 0);
Chris Lattner5f521502007-01-25 06:27:24 +00001207 // If this is an undefined enum, warn.
Chris Lattnerc1915e22007-01-25 07:29:02 +00001208 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Chris Lattner5f521502007-01-25 06:27:24 +00001209 break;
Chris Lattner720a0542007-01-25 00:44:24 +00001210 case Decl::Union:
1211 case Decl::Struct:
1212 case Decl::Class:
Chris Lattner776fac82007-06-09 00:53:06 +00001213 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1214 // struct X { int A; } D; D should chain to X.
1215 New = new RecordDecl(Kind, Loc, Name, 0);
Chris Lattner720a0542007-01-25 00:44:24 +00001216 break;
1217 }
Chris Lattner18b19622007-01-22 07:39:13 +00001218
1219 // If this has an identifier, add it to the scope stack.
1220 if (Name) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001221 // The scope passed in may not be a decl scope. Zip up the scope tree until
1222 // we find one that is.
1223 while ((S->getFlags() & Scope::DeclScope) == 0)
1224 S = S->getParent();
1225
1226 // Add it to the decl chain.
Steve Naroff9324db12007-09-13 18:10:37 +00001227 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner18b19622007-01-22 07:39:13 +00001228 Name->setFETokenInfo(New);
1229 S->AddDecl(New);
1230 }
Steve Naroff197616c2007-11-28 22:54:11 +00001231
Chris Lattner18b19622007-01-22 07:39:13 +00001232 return New;
1233}
Chris Lattner1300fb92007-01-23 23:42:53 +00001234
Steve Naroff30d242c2007-09-15 18:49:24 +00001235/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00001236/// to create a FieldDecl object for it.
Steve Naroff30d242c2007-09-15 18:49:24 +00001237Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Chris Lattner1300fb92007-01-23 23:42:53 +00001238 SourceLocation DeclStart,
1239 Declarator &D, ExprTy *BitfieldWidth) {
1240 IdentifierInfo *II = D.getIdentifier();
1241 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner1300fb92007-01-23 23:42:53 +00001242 SourceLocation Loc = DeclStart;
1243 if (II) Loc = D.getIdentifierLoc();
1244
Chris Lattner62d2e662007-01-28 00:21:37 +00001245 // FIXME: Unnamed fields can be handled in various different ways, for
1246 // example, unnamed unions inject all members into the struct namespace!
1247
1248
Chris Lattner1300fb92007-01-23 23:42:53 +00001249 if (BitWidth) {
1250 // TODO: Validate.
Steve Narofff84d11f2007-05-23 21:48:04 +00001251 //printf("WARNING: BITFIELDS IGNORED!\n");
Chris Lattner1300fb92007-01-23 23:42:53 +00001252
1253 // 6.7.2.1p3
1254 // 6.7.2.1p4
1255
1256 } else {
1257 // Not a bitfield.
1258
1259 // validate II.
1260
1261 }
1262
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001263 QualType T = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +00001264 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1265 bool InvalidDecl = false;
Steve Naroff096dd942007-08-31 17:20:07 +00001266
Steve Naroff8eeeb132007-05-08 21:09:37 +00001267 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1268 // than a variably modified type.
Steve Naroff096dd942007-08-31 17:20:07 +00001269 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1270 Diag(Loc, diag::err_typecheck_illegal_vla,
1271 VAT->getSizeExpr()->getSourceRange());
1272 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +00001273 }
Chris Lattner776fac82007-06-09 00:53:06 +00001274 // FIXME: Chain fielddecls together.
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001275 FieldDecl *NewFD;
1276
1277 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patel32714062007-11-01 16:29:56 +00001278 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001279 else if (isa<ObjCInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1280 isa<ObjCImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
1281 isa<ObjCCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroff9e0887cf2007-11-14 14:15:31 +00001282 // FIXME: ivars are currently used to model properties, and
1283 // properties can appear within a protocol.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001284 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1285 isa<ObjCProtocolDecl>(static_cast<Decl *>(TagDecl)))
1286 NewFD = new ObjCIvarDecl(Loc, II, T);
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001287 else
Steve Naroff30d242c2007-09-15 18:49:24 +00001288 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001289
Steve Narofff93b6722007-08-28 20:14:24 +00001290 if (D.getInvalidType() || InvalidDecl)
1291 NewFD->setInvalidDecl();
1292 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00001293}
1294
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001295/// TranslateIvarVisibility - Translate visibility from a token ID to an
1296/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001297static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001298TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00001299 switch (ivarVisibility) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001300 case tok::objc_private: return ObjCIvarDecl::Private;
1301 case tok::objc_public: return ObjCIvarDecl::Public;
1302 case tok::objc_protected: return ObjCIvarDecl::Protected;
1303 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001304 default: assert(false && "Unknown visitibility kind");
Steve Naroff2e688fd2007-09-14 23:09:53 +00001305 }
1306}
1307
Fariborz Jahanian343f7092007-09-29 00:54:24 +00001308void Sema::ActOnFields(Scope* S,
Fariborz Jahanian67341402007-10-04 00:45:27 +00001309 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff30d242c2007-09-15 18:49:24 +00001310 DeclTy **Fields, unsigned NumFields,
Steve Naroff33a1e802007-10-29 21:38:07 +00001311 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff30d242c2007-09-15 18:49:24 +00001312 tok::ObjCKeywordKind *visibility) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00001313 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1314 assert(EnclosingDecl && "missing record or interface decl");
1315 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1316
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001317 if (Record && Record->isDefinition()) {
Chris Lattner1300fb92007-01-23 23:42:53 +00001318 // Diagnose code like:
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001319 // struct S { struct S {} X; };
Chris Lattner1300fb92007-01-23 23:42:53 +00001320 // We discover this when we complete the outer S. Reject and ignore the
1321 // outer S.
1322 Diag(Record->getLocation(), diag::err_nested_redefinition,
1323 Record->getKindName());
1324 Diag(RecLoc, diag::err_previous_definition);
Steve Naroffdb47ee22007-09-14 22:20:54 +00001325 Record->setInvalidDecl();
Chris Lattner1300fb92007-01-23 23:42:53 +00001326 return;
1327 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001328 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00001329 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +00001330 llvm::SmallVector<FieldDecl*, 32> RecFields;
1331 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroffdb47ee22007-09-14 22:20:54 +00001332
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001333 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001334
Steve Naroffdb47ee22007-09-14 22:20:54 +00001335 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1336 assert(FD && "missing field decl");
1337
1338 // Remember all fields.
1339 RecFields.push_back(FD);
Chris Lattner720a0542007-01-25 00:44:24 +00001340
1341 // Get the type for the field.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001342 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner720a0542007-01-25 00:44:24 +00001343
Steve Naroff2e688fd2007-09-14 23:09:53 +00001344 // If we have visibility info, make sure the AST is set accordingly.
1345 if (visibility)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001346 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001347 TranslateIvarVisibility(visibility[i]));
Steve Naroff2e688fd2007-09-14 23:09:53 +00001348
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001349 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001350 if (FDTy->isFunctionType()) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00001351 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001352 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001353 FD->setInvalidDecl();
1354 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001355 continue;
1356 }
Chris Lattner82625602007-01-24 02:26:21 +00001357 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
Chris Lattner720a0542007-01-25 00:44:24 +00001358 if (FDTy->isIncompleteType()) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001359 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian67341402007-10-04 00:45:27 +00001360 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001361 FD->setInvalidDecl();
1362 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian67341402007-10-04 00:45:27 +00001363 continue;
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001364 }
Chris Lattner82625602007-01-24 02:26:21 +00001365 if (i != NumFields-1 || // ... that the last member ...
1366 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner0fd893e2007-07-31 21:33:24 +00001367 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner82625602007-01-24 02:26:21 +00001368 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001369 FD->setInvalidDecl();
1370 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00001371 continue;
1372 }
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001373 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner82625602007-01-24 02:26:21 +00001374 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1375 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001376 FD->setInvalidDecl();
1377 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00001378 continue;
1379 }
Chris Lattner720a0542007-01-25 00:44:24 +00001380 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001381 if (Record)
1382 Record->setHasFlexibleArrayMember(true);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001383 }
Chris Lattner720a0542007-01-25 00:44:24 +00001384 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1385 /// field of another structure or the element of an array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001386 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner720a0542007-01-25 00:44:24 +00001387 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1388 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001389 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner41943152007-01-25 04:52:46 +00001390 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00001391 } else {
1392 // If this is a struct/class and this is not the last element, reject
1393 // it. Note that GCC supports variable sized arrays in the middle of
1394 // structures.
1395 if (i != NumFields-1) {
1396 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1397 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001398 FD->setInvalidDecl();
1399 EnclosingDecl->setInvalidDecl();
Chris Lattner720a0542007-01-25 00:44:24 +00001400 continue;
1401 }
Chris Lattner720a0542007-01-25 00:44:24 +00001402 // We support flexible arrays at the end of structs in other structs
1403 // as an extension.
1404 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1405 FD->getName());
Fariborz Jahanian67341402007-10-04 00:45:27 +00001406 if (Record)
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001407 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00001408 }
1409 }
1410 }
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00001411 /// A field cannot be an Objective-c object
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001412 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00001413 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1414 FD->getName());
1415 FD->setInvalidDecl();
1416 EnclosingDecl->setInvalidDecl();
1417 continue;
1418 }
Chris Lattner82625602007-01-24 02:26:21 +00001419 // Keep track of the number of named members.
Chris Lattnere5a66562007-01-25 22:48:42 +00001420 if (IdentifierInfo *II = FD->getIdentifier()) {
1421 // Detect duplicate member names.
Chris Lattnerbaf33662007-01-27 02:14:08 +00001422 if (!FieldIDs.insert(II)) {
Chris Lattnere5a66562007-01-25 22:48:42 +00001423 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1424 // Find the previous decl.
1425 SourceLocation PrevLoc;
1426 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1427 assert(i != e && "Didn't find previous def!");
1428 if (RecFields[i]->getIdentifier() == II) {
1429 PrevLoc = RecFields[i]->getLocation();
1430 break;
1431 }
1432 }
1433 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroffdb47ee22007-09-14 22:20:54 +00001434 FD->setInvalidDecl();
1435 EnclosingDecl->setInvalidDecl();
Chris Lattnere5a66562007-01-25 22:48:42 +00001436 continue;
1437 }
Chris Lattner82625602007-01-24 02:26:21 +00001438 ++NumNamedMembers;
Chris Lattnere5a66562007-01-25 22:48:42 +00001439 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001440 }
Chris Lattner82625602007-01-24 02:26:21 +00001441
Chris Lattner82625602007-01-24 02:26:21 +00001442 // Okay, we successfully defined 'Record'.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001443 if (Record)
1444 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00001445 else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001446 ObjCIvarDecl **ClsFields =
1447 reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1448 if (isa<ObjCInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1449 cast<ObjCInterfaceDecl>(static_cast<Decl*>(RecDecl))->
Steve Naroff33a1e802007-10-29 21:38:07 +00001450 addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001451 else if (isa<ObjCImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1452 ObjCImplementationDecl* IMPDecl =
1453 cast<ObjCImplementationDecl>(static_cast<Decl*>(RecDecl));
1454 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1455 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian95b60762007-10-31 18:48:14 +00001456 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00001457 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00001458 }
Chris Lattner1300fb92007-01-23 23:42:53 +00001459}
1460
Steve Naroff30d242c2007-09-15 18:49:24 +00001461Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4ef40012007-06-11 01:28:17 +00001462 DeclTy *lastEnumConst,
Chris Lattnerc1915e22007-01-25 07:29:02 +00001463 SourceLocation IdLoc, IdentifierInfo *Id,
Chris Lattner4ef40012007-06-11 01:28:17 +00001464 SourceLocation EqualLoc, ExprTy *val) {
1465 theEnumDecl = theEnumDecl; // silence unused warning.
1466 EnumConstantDecl *LastEnumConst =
1467 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1468 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00001469
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001470 // The scope passed in may not be a decl scope. Zip up the scope tree until
1471 // we find one that is.
1472 while ((S->getFlags() & Scope::DeclScope) == 0)
1473 S = S->getParent();
1474
Chris Lattner8116d1b2007-01-25 22:38:29 +00001475 // Verify that there isn't already something declared with this name in this
1476 // scope.
Steve Naroff9def2b12007-09-13 21:41:19 +00001477 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1478 IdLoc, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00001479 if (S->isDeclScope(PrevDecl)) {
1480 if (isa<EnumConstantDecl>(PrevDecl))
1481 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1482 else
1483 Diag(IdLoc, diag::err_redefinition, Id->getName());
1484 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner4ef40012007-06-11 01:28:17 +00001485 // FIXME: Don't leak memory: delete Val;
Chris Lattner8116d1b2007-01-25 22:38:29 +00001486 return 0;
1487 }
1488 }
Chris Lattner4ef40012007-06-11 01:28:17 +00001489
Chris Lattner23b7eb62007-06-15 23:05:46 +00001490 llvm::APSInt EnumVal(32);
Chris Lattner4ef40012007-06-11 01:28:17 +00001491 QualType EltTy;
1492 if (Val) {
Chris Lattner0515e4b2007-08-27 21:16:18 +00001493 // Make sure to promote the operand type to int.
1494 UsualUnaryConversions(Val);
1495
Chris Lattner4ef40012007-06-11 01:28:17 +00001496 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1497 SourceLocation ExpLoc;
Chris Lattner0e9d6222007-07-15 23:26:56 +00001498 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Chris Lattner4ef40012007-06-11 01:28:17 +00001499 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1500 Id->getName());
1501 // FIXME: Don't leak memory: delete Val;
Chris Lattnerf283a372007-08-27 17:37:24 +00001502 Val = 0; // Just forget about it.
Chris Lattnerc92bc4c2007-08-29 16:03:41 +00001503 } else {
1504 EltTy = Val->getType();
Chris Lattner4ef40012007-06-11 01:28:17 +00001505 }
Chris Lattnerf283a372007-08-27 17:37:24 +00001506 }
1507
1508 if (!Val) {
1509 if (LastEnumConst) {
1510 // Assign the last value + 1.
1511 EnumVal = LastEnumConst->getInitVal();
1512 ++EnumVal;
Chris Lattner0515e4b2007-08-27 21:16:18 +00001513
1514 // Check for overflow on increment.
1515 if (EnumVal < LastEnumConst->getInitVal())
1516 Diag(IdLoc, diag::warn_enum_value_overflow);
1517
Chris Lattnerf283a372007-08-27 17:37:24 +00001518 EltTy = LastEnumConst->getType();
1519 } else {
1520 // First value, set to zero.
1521 EltTy = Context.IntTy;
Chris Lattner9cf21c52007-09-04 02:45:27 +00001522 EnumVal.zextOrTrunc(
1523 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerf283a372007-08-27 17:37:24 +00001524 }
Steve Naroff63969212007-05-07 21:22:42 +00001525 }
Chris Lattner4ef40012007-06-11 01:28:17 +00001526
Chris Lattner4ef40012007-06-11 01:28:17 +00001527 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1528 LastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +00001529
1530 // Register this decl in the current scope stack.
Steve Naroff9324db12007-09-13 18:10:37 +00001531 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner8116d1b2007-01-25 22:38:29 +00001532 Id->setFETokenInfo(New);
1533 S->AddDecl(New);
1534 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001535}
1536
Steve Naroff30d242c2007-09-15 18:49:24 +00001537void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattnerc1915e22007-01-25 07:29:02 +00001538 DeclTy **Elements, unsigned NumElements) {
1539 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1540 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1541
Chris Lattner67933c02007-08-28 05:10:31 +00001542 // TODO: If the result value doesn't fit in an int, it must be a long or long
1543 // long value. ISO C does not support this, but GCC does as an extension,
1544 // emit a warning.
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001545 unsigned IntWidth =
1546 Context.Target.getIntWidth(Context.getFullLoc(Enum->getLocation()));
Chris Lattner67933c02007-08-28 05:10:31 +00001547
1548
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001549 // Verify that all the values are okay, compute the size of the values, and
1550 // reverse the list.
1551 unsigned NumNegativeBits = 0;
1552 unsigned NumPositiveBits = 0;
1553
1554 // Keep track of whether all elements have type int.
1555 bool AllElementsInt = true;
1556
Chris Lattner4ef40012007-06-11 01:28:17 +00001557 EnumConstantDecl *EltList = 0;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001558 for (unsigned i = 0; i != NumElements; ++i) {
1559 EnumConstantDecl *ECD =
1560 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1561 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnerbf478cb2007-08-28 05:27:00 +00001562
1563 // If the enum value doesn't fit in an int, emit an extension warning.
1564 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1565 "Should have promoted value to int");
1566 const llvm::APSInt &InitVal = ECD->getInitVal();
1567 if (InitVal.getBitWidth() > IntWidth) {
1568 llvm::APSInt V(InitVal);
1569 V.trunc(IntWidth);
1570 V.extend(InitVal.getBitWidth());
1571 if (V != InitVal)
1572 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1573 InitVal.toString());
1574 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001575
1576 // Keep track of the size of positive and negative values.
1577 if (InitVal.isUnsigned() || !InitVal.isNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +00001578 NumPositiveBits = std::max(NumPositiveBits,
1579 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001580 else
Chris Lattner49f980c2008-01-14 21:47:29 +00001581 NumNegativeBits = std::max(NumNegativeBits,
1582 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00001583
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001584 // Keep track of whether every enum element has type int (very commmon).
1585 if (AllElementsInt)
1586 AllElementsInt = ECD->getType() == Context.IntTy;
1587
Chris Lattner4ef40012007-06-11 01:28:17 +00001588 ECD->setNextDeclarator(EltList);
1589 EltList = ECD;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001590 }
1591
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001592 // Figure out the type that should be used for this enum.
1593 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1594 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001595 unsigned BestWidth;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001596
1597 if (NumNegativeBits) {
1598 // If there is a negative value, figure out the smallest integer type (of
1599 // int/long/longlong) that fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001600 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001601 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001602 BestWidth = IntWidth;
1603 } else {
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001604 BestWidth =
1605 Context.Target.getLongWidth(Context.getFullLoc(Enum->getLocation()));
1606
Chris Lattner3a370bf2007-08-29 17:31:48 +00001607 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001608 BestType = Context.LongTy;
1609 else {
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001610 BestWidth = Context.Target.getLongLongWidth(
1611 Context.getFullLoc(Enum->getLocation()));
1612
Chris Lattner3a370bf2007-08-29 17:31:48 +00001613 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001614 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1615 BestType = Context.LongLongTy;
1616 }
1617 }
1618 } else {
1619 // If there is no negative value, figure out which of uint, ulong, ulonglong
1620 // fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001621 if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001622 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001623 BestWidth = IntWidth;
1624 } else if (NumPositiveBits <=
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001625 (BestWidth = Context.Target.getLongWidth(
1626 Context.getFullLoc(Enum->getLocation()))))
1627
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001628 BestType = Context.UnsignedLongTy;
1629 else {
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001630 BestWidth =
1631 Context.Target.getLongLongWidth(Context.getFullLoc(Enum->getLocation()));
1632
Chris Lattner3a370bf2007-08-29 17:31:48 +00001633 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001634 "How could an initializer get larger than ULL?");
1635 BestType = Context.UnsignedLongLongTy;
1636 }
1637 }
1638
Chris Lattner3a370bf2007-08-29 17:31:48 +00001639 // Loop over all of the enumerator constants, changing their types to match
1640 // the type of the enum if needed.
1641 for (unsigned i = 0; i != NumElements; ++i) {
1642 EnumConstantDecl *ECD =
1643 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1644 if (!ECD) continue; // Already issued a diagnostic.
1645
1646 // Standard C says the enumerators have int type, but we allow, as an
1647 // extension, the enumerators to be larger than int size. If each
1648 // enumerator value fits in an int, type it as an int, otherwise type it the
1649 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1650 // that X has type 'int', not 'unsigned'.
1651 if (ECD->getType() == Context.IntTy)
1652 continue; // Already int type.
1653
1654 // Determine whether the value fits into an int.
1655 llvm::APSInt InitVal = ECD->getInitVal();
1656 bool FitsInInt;
1657 if (InitVal.isUnsigned() || !InitVal.isNegative())
1658 FitsInInt = InitVal.getActiveBits() < IntWidth;
1659 else
1660 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1661
1662 // If it fits into an integer type, force it. Otherwise force it to match
1663 // the enum decl type.
1664 QualType NewTy;
1665 unsigned NewWidth;
1666 bool NewSign;
1667 if (FitsInInt) {
1668 NewTy = Context.IntTy;
1669 NewWidth = IntWidth;
1670 NewSign = true;
1671 } else if (ECD->getType() == BestType) {
1672 // Already the right type!
1673 continue;
1674 } else {
1675 NewTy = BestType;
1676 NewWidth = BestWidth;
1677 NewSign = BestType->isSignedIntegerType();
1678 }
1679
1680 // Adjust the APSInt value.
1681 InitVal.extOrTrunc(NewWidth);
1682 InitVal.setIsSigned(NewSign);
1683 ECD->setInitVal(InitVal);
1684
1685 // Adjust the Expr initializer and type.
1686 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1687 ECD->setType(NewTy);
1688 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001689
Chris Lattner1c1f9322007-08-28 18:24:31 +00001690 Enum->defineElements(EltList, BestType);
Chris Lattnerc1915e22007-01-25 07:29:02 +00001691}
Chris Lattner1300fb92007-01-23 23:42:53 +00001692
Chris Lattner38376f12008-01-12 07:05:38 +00001693Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
1694 SourceLocation LBrace,
1695 SourceLocation RBrace,
1696 const char *Lang,
1697 unsigned StrSize,
1698 DeclTy *D) {
1699 LinkageSpecDecl::LanguageIDs Language;
1700 Decl *dcl = static_cast<Decl *>(D);
1701 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1702 Language = LinkageSpecDecl::lang_c;
1703 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1704 Language = LinkageSpecDecl::lang_cxx;
1705 else {
1706 Diag(Loc, diag::err_bad_language);
1707 return 0;
1708 }
1709
1710 // FIXME: Add all the various semantics of linkage specifications
1711 return new LinkageSpecDecl(Loc, Language, dcl);
1712}
1713
Steve Naroffa8fd9732007-06-11 00:35:03 +00001714void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
Anders Carlsson081f1b42007-12-19 06:16:30 +00001715 const char *attrName = rawAttr->getAttributeName()->getName();
1716 unsigned attrLen = rawAttr->getAttributeName()->getLength();
1717
Anders Carlsson2c26cc22007-12-19 17:43:24 +00001718 // Normalize the attribute name, __foo__ becomes foo.
1719 if (attrLen > 4 && attrName[0] == '_' && attrName[1] == '_' &&
1720 attrName[attrLen - 2] == '_' && attrName[attrLen - 1] == '_') {
1721 attrName += 2;
1722 attrLen -= 4;
1723 }
1724
1725 if (attrLen == 11 && !memcmp(attrName, "vector_size", 11)) {
Steve Naroffa8fd9732007-06-11 00:35:03 +00001726 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001727 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001728 if (!newType.isNull()) // install the new vector type into the decl
1729 vDecl->setType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001730 }
1731 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001732 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1733 rawAttr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001734 if (!newType.isNull()) // install the new vector type into the decl
1735 tDecl->setUnderlyingType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001736 }
Anders Carlsson2c26cc22007-12-19 17:43:24 +00001737 } else if (attrLen == 15 && !memcmp(attrName, "ocu_vector_type", 15)) {
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001738 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1739 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1740 else
Steve Naroff91fcddb2007-07-18 18:00:27 +00001741 Diag(rawAttr->getAttributeLoc(),
1742 diag::err_typecheck_ocu_vector_not_typedef);
Anders Carlsson721f6012007-12-19 07:19:40 +00001743 } else if (attrLen == 7 && !memcmp(attrName, "aligned", 7)) {
1744 HandleAlignedAttribute(New, rawAttr);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001745 }
Anders Carlsson721f6012007-12-19 07:19:40 +00001746
Steve Naroffa8fd9732007-06-11 00:35:03 +00001747 // FIXME: add other attributes...
1748}
1749
1750void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1751 AttributeList *declarator_postfix) {
1752 while (declspec_prefix) {
1753 HandleDeclAttribute(New, declspec_prefix);
1754 declspec_prefix = declspec_prefix->getNext();
1755 }
1756 while (declarator_postfix) {
1757 HandleDeclAttribute(New, declarator_postfix);
1758 declarator_postfix = declarator_postfix->getNext();
1759 }
1760}
1761
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001762void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1763 AttributeList *rawAttr) {
1764 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson721f6012007-12-19 07:19:40 +00001765 // check the attribute arguments.
Steve Naroff91fcddb2007-07-18 18:00:27 +00001766 if (rawAttr->getNumArgs() != 1) {
1767 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1768 std::string("1"));
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001769 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001770 }
1771 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1772 llvm::APSInt vecSize(32);
1773 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1774 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1775 sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001776 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001777 }
1778 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1779 // in conjunction with complex types (pointers, arrays, functions, etc.).
1780 Type *canonType = curType.getCanonicalType().getTypePtr();
1781 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1782 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1783 curType.getCanonicalType().getAsString());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001784 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001785 }
1786 // unlike gcc's vector_size attribute, the size is specified as the
1787 // number of elements, not the number of bytes.
Chris Lattner9cf21c52007-09-04 02:45:27 +00001788 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001789
1790 if (vectorSize == 0) {
1791 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1792 sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001793 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001794 }
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001795 // Instantiate/Install the vector type, the number of elements is > 0.
1796 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1797 // Remember this typedef decl, we will need it later for diagnostics.
1798 OCUVectorDecls.push_back(tDecl);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001799}
1800
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001801QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattner983a8bb2007-07-13 22:13:22 +00001802 AttributeList *rawAttr) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001803 // check the attribute arugments.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001804 if (rawAttr->getNumArgs() != 1) {
1805 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1806 std::string("1"));
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001807 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001808 }
1809 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
Chris Lattner23b7eb62007-06-15 23:05:46 +00001810 llvm::APSInt vecSize(32);
Chris Lattner0e9d6222007-07-15 23:26:56 +00001811 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Steve Naroffa8fd9732007-06-11 00:35:03 +00001812 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1813 sizeExpr->getSourceRange());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001814 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001815 }
1816 // navigate to the base type - we need to provide for vector pointers,
1817 // vector arrays, and functions returning vectors.
1818 Type *canonType = curType.getCanonicalType().getTypePtr();
1819
Steve Naroff91fcddb2007-07-18 18:00:27 +00001820 if (canonType->isPointerType() || canonType->isArrayType() ||
1821 canonType->isFunctionType()) {
Chris Lattner0f8a39c2007-12-19 05:38:06 +00001822 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff91fcddb2007-07-18 18:00:27 +00001823 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1824 do {
1825 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1826 canonType = PT->getPointeeType().getTypePtr();
1827 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1828 canonType = AT->getElementType().getTypePtr();
1829 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1830 canonType = FT->getResultType().getTypePtr();
1831 } while (canonType->isPointerType() || canonType->isArrayType() ||
1832 canonType->isFunctionType());
1833 */
Steve Naroffa8fd9732007-06-11 00:35:03 +00001834 }
1835 // the base type must be integer or float.
1836 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1837 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1838 curType.getCanonicalType().getAsString());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001839 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001840 }
Chris Lattner9cf21c52007-09-04 02:45:27 +00001841 unsigned typeSize = static_cast<unsigned>(
1842 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001843 // vecSize is specified in bytes - convert to bits.
Chris Lattner9cf21c52007-09-04 02:45:27 +00001844 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001845
1846 // the vector size needs to be an integral multiple of the type size.
1847 if (vectorSize % typeSize) {
1848 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1849 sizeExpr->getSourceRange());
1850 return QualType();
1851 }
1852 if (vectorSize == 0) {
1853 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1854 sizeExpr->getSourceRange());
1855 return QualType();
1856 }
1857 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1858 // the number of elements to be a power of two (unlike GCC).
1859 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff91fcddb2007-07-18 18:00:27 +00001860 return Context.getVectorType(curType, vectorSize/typeSize);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001861}
1862
Anders Carlsson721f6012007-12-19 07:19:40 +00001863void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
1864{
1865 // check the attribute arguments.
Anders Carlsson2c26cc22007-12-19 17:43:24 +00001866 // FIXME: Handle the case where are no arguments.
Anders Carlsson721f6012007-12-19 07:19:40 +00001867 if (rawAttr->getNumArgs() != 1) {
1868 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1869 std::string("1"));
1870 return;
1871 }
1872
1873 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
1874 llvm::APSInt alignment(32);
1875 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
1876 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1877 alignmentExpr->getSourceRange());
1878 return;
1879 }
1880}