blob: 7443d365a97726413931d86cdf83d218a9b7a47f [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;
36 if (isa<TypedefDecl>(IIDecl) || isa<ObjcInterfaceDecl>(IIDecl))
37 return IIDecl;
38 if (ObjcCompatibleAliasDecl *ADecl =
39 dyn_cast<ObjcCompatibleAliasDecl>(IIDecl))
40 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
101 if (ObjcCompatibleAliasDecl *ADecl =
102 dyn_cast_or_null<ObjcCompatibleAliasDecl>(IDecl))
103 return ADecl->getClassInterface();
104 return IDecl;
105}
106
Fariborz Jahanianfa0667b2007-09-29 17:04:06 +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.
Steve Naroffc6814ea2007-10-02 20:01:56 +0000109ObjcInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +0000110 ScopedDecl *IdDecl = LookupInterfaceDecl(Id);
111 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!
Chris Lattnerda463fe2007-12-12 07:09:47 +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;
248 if (OldQType == NewQType)
249 return New;
Chris Lattnerefe4aea2007-01-27 19:35:39 +0000250 }
Chris Lattner45d561a2007-11-06 06:07:26 +0000251
Chris Lattner5c3f1542007-11-20 19:04:50 +0000252 if (New->getBody() == 0 && OldQType == NewQType) {
Chris Lattner45d561a2007-11-06 06:07:26 +0000253 return 0;
254 }
Chris Lattnerc511efb2007-01-27 19:32:14 +0000255
Chris Lattner01564d92007-01-27 19:27:06 +0000256 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
257 // TODO: This is totally simplistic. It should handle merging functions
258 // together etc, merging extern int X; int X; ...
259 Diag(New->getLocation(), diag::err_redefinition, New->getName());
260 Diag(Old->getLocation(), diag::err_previous_definition);
261 return New;
262}
263
Chris Lattner32097252007-11-06 04:28:31 +0000264
265/// hasUndefinedLength - Used by equivalentArrayTypes to determine whether the
266/// the outermost VariableArrayType has no size defined.
267static bool hasUndefinedLength(const ArrayType *Array) {
268 const VariableArrayType *VAT = Array->getAsVariableArrayType();
269 return VAT && !VAT->getSizeExpr();
270}
271
272/// equivalentArrayTypes - Used to determine whether two array types are
273/// equivalent.
274/// We need to check this explicitly as an incomplete array definition is
275/// considered a VariableArrayType, so will not match a complete array
276/// definition that would be otherwise equivalent.
277static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
278 const ArrayType *NewAT = NewQType->getAsArrayType();
279 const ArrayType *OldAT = OldQType->getAsArrayType();
280
281 if (!NewAT || !OldAT)
282 return false;
283
284 // If either (or both) array types in incomplete we need to strip off the
285 // outer VariableArrayType. Once the outer VAT is removed the remaining
286 // types must be identical if the array types are to be considered
287 // equivalent.
288 // eg. int[][1] and int[1][1] become
289 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
290 // removing the outermost VAT gives
291 // CAT(1, int) and CAT(1, int)
292 // which are equal, therefore the array types are equivalent.
293 if (hasUndefinedLength(NewAT) || hasUndefinedLength(OldAT)) {
294 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
295 return false;
296 NewQType = NewAT->getElementType();
297 OldQType = OldAT->getElementType();
298 }
299
300 return NewQType == OldQType;
301}
302
Chris Lattner01564d92007-01-27 19:27:06 +0000303/// MergeVarDecl - We just parsed a variable 'New' which has the same name
304/// and scope as a previous declaration 'Old'. Figure out how to resolve this
305/// situation, merging decls or emitting diagnostics as appropriate.
306///
Steve Narofffc49d672007-04-01 21:27:45 +0000307/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
308/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
309///
Steve Naroff9def2b12007-09-13 21:41:19 +0000310VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000311 // Verify the old decl was also a variable.
312 VarDecl *Old = dyn_cast<VarDecl>(OldD);
313 if (!Old) {
314 Diag(New->getLocation(), diag::err_redefinition_different_kind,
315 New->getName());
316 Diag(OldD->getLocation(), diag::err_previous_definition);
317 return New;
318 }
Steve Naroff5c131802007-08-30 01:06:46 +0000319 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
320 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
321 bool OldIsTentative = false;
322
323 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
324 // Handle C "tentative" external object definitions. FIXME: finish!
325 if (!OldFSDecl->getInit() &&
326 (OldFSDecl->getStorageClass() == VarDecl::None ||
327 OldFSDecl->getStorageClass() == VarDecl::Static))
328 OldIsTentative = true;
329 }
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000330 // Verify the types match.
Chris Lattner32097252007-11-06 04:28:31 +0000331 if (Old->getCanonicalType() != New->getCanonicalType() &&
332 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000333 Diag(New->getLocation(), diag::err_redefinition, New->getName());
334 Diag(Old->getLocation(), diag::err_previous_definition);
335 return New;
336 }
337 // We've verified the types match, now check if Old is "extern".
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000338 if (Old->getStorageClass() != VarDecl::Extern) {
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000339 Diag(New->getLocation(), diag::err_redefinition, New->getName());
340 Diag(Old->getLocation(), diag::err_previous_definition);
341 }
Chris Lattner01564d92007-01-27 19:27:06 +0000342 return New;
343}
344
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000345/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
346/// no declarator (e.g. "struct foo;") is parsed.
347Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
348 // TODO: emit error on 'int;' or 'const enum foo;'.
349 // TODO: emit error on 'typedef int;'
350 // if (!DS.isMissingDeclaratorOk()) Diag(...);
351
Steve Naroff14f5f792007-11-17 21:37:36 +0000352 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000353}
354
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000355bool Sema::CheckSingleInitializer(Expr *&Init, bool isStatic,
356 QualType DeclType) {
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000357 // FIXME: Remove the isReferenceType check and handle assignment
358 // to a reference.
Chris Lattnerf6412552007-12-11 23:15:04 +0000359 SourceLocation loc;
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000360 if (isStatic && !DeclType->isReferenceType() &&
361 !Init->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
Chris Lattnerf6412552007-12-11 23:15:04 +0000362 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000363 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
364 return true;
365 }
366
Steve Naroff2fea1392007-09-02 02:04:30 +0000367 AssignmentCheckResult result;
Steve Naroff2fea1392007-09-02 02:04:30 +0000368 // Get the type before calling CheckSingleAssignmentConstraints(), since
369 // it can promote the expression.
370 QualType rhsType = Init->getType();
371
372 result = CheckSingleAssignmentConstraints(DeclType, Init);
373
374 // decode the result (notice that extensions still return a type).
375 switch (result) {
376 case Compatible:
377 break;
378 case Incompatible:
Steve Narofff33527a2007-09-02 15:34:30 +0000379 // FIXME: tighten up this check which should allow:
380 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
381 if (rhsType == Context.getPointerType(Context.CharTy))
382 break;
Chris Lattnerf6412552007-12-11 23:15:04 +0000383 Diag(Init->getLocStart(), diag::err_typecheck_assign_incompatible,
Steve Naroff2fea1392007-09-02 02:04:30 +0000384 DeclType.getAsString(), rhsType.getAsString(),
385 Init->getSourceRange());
386 return true;
387 case PointerFromInt:
Chris Lattnerf6412552007-12-11 23:15:04 +0000388 Diag(Init->getLocStart(), diag::ext_typecheck_assign_pointer_int,
Steve Naroff0ee0b0a2007-11-27 17:58:44 +0000389 DeclType.getAsString(), rhsType.getAsString(),
390 Init->getSourceRange());
Steve Naroff2fea1392007-09-02 02:04:30 +0000391 break;
392 case IntFromPointer:
Chris Lattnerf6412552007-12-11 23:15:04 +0000393 Diag(Init->getLocStart(), diag::ext_typecheck_assign_pointer_int,
Steve Naroff2fea1392007-09-02 02:04:30 +0000394 DeclType.getAsString(), rhsType.getAsString(),
395 Init->getSourceRange());
396 break;
397 case IncompatiblePointer:
Chris Lattnerf6412552007-12-11 23:15:04 +0000398 Diag(Init->getLocStart(), diag::ext_typecheck_assign_incompatible_pointer,
Steve Naroff2fea1392007-09-02 02:04:30 +0000399 DeclType.getAsString(), rhsType.getAsString(),
400 Init->getSourceRange());
401 break;
402 case CompatiblePointerDiscardsQualifiers:
Chris Lattnerf6412552007-12-11 23:15:04 +0000403 Diag(Init->getLocStart(), diag::ext_typecheck_assign_discards_qualifiers,
Steve Naroff2fea1392007-09-02 02:04:30 +0000404 DeclType.getAsString(), rhsType.getAsString(),
405 Init->getSourceRange());
406 break;
407 }
408 return false;
409}
410
Steve Naroff77b97002007-09-04 14:36:54 +0000411bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
412 bool isStatic, QualType ElementType) {
Steve Naroffac074b42007-09-04 02:20:04 +0000413 SourceLocation loc;
Steve Naroffac074b42007-09-04 02:20:04 +0000414 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
Chris Lattnerf6412552007-12-11 23:15:04 +0000415 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
Steve Naroffac074b42007-09-04 02:20:04 +0000416 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
417 return true;
Steve Naroffac074b42007-09-04 02:20:04 +0000418 }
Chris Lattnerf6412552007-12-11 23:15:04 +0000419
420 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
421 if (CheckSingleInitializer(expr, isStatic, ElementType))
422 return true; // types weren't compatible.
423
Steve Naroff77b97002007-09-04 14:36:54 +0000424 if (savExpr != expr) // The type was promoted, update initializer list.
425 IList->setInit(slot, expr);
Steve Naroffac074b42007-09-04 02:20:04 +0000426 return false;
427}
428
429void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
430 QualType ElementType, bool isStatic,
431 int &nInitializers, bool &hadError) {
Steve Naroff91f78082007-12-10 22:44:33 +0000432 unsigned numInits = IList->getNumInits();
433
434 if (numInits) {
435 if (CheckForCharArrayInitializer(IList, ElementType, nInitializers,
436 false, hadError))
437 return;
438
439 for (unsigned i = 0; i < numInits; i++) {
440 Expr *expr = IList->getInit(i);
Steve Narofff33527a2007-09-02 15:34:30 +0000441
Steve Naroff91f78082007-12-10 22:44:33 +0000442 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
443 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
444 int maxElements = CAT->getMaximumElements();
445 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
446 maxElements, hadError);
447 }
448 } else {
449 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
450 }
451 nInitializers++;
452 }
453 } else {
454 Diag(IList->getLocStart(),
455 diag::err_at_least_one_initializer_needed_to_size_array);
456 hadError = true;
457 }
458}
459
460bool Sema::CheckForCharArrayInitializer(InitListExpr *IList,
461 QualType ElementType,
462 int &nInitializers, bool isConstant,
463 bool &hadError)
464{
465 if (ElementType->isPointerType())
466 return false;
467
468 if (StringLiteral *literal = dyn_cast<StringLiteral>(IList->getInit(0))) {
469 // FIXME: Handle wide strings
470 if (ElementType->isCharType()) {
471 if (isConstant) {
472 if (literal->getByteLength() > (unsigned)nInitializers) {
473 Diag(literal->getSourceRange().getBegin(),
474 diag::warn_initializer_string_for_char_array_too_long,
475 literal->getSourceRange());
476 }
477 } else {
478 nInitializers = literal->getByteLength() + 1;
Steve Narofff33527a2007-09-02 15:34:30 +0000479 }
Steve Naroffac074b42007-09-04 02:20:04 +0000480 } else {
Steve Naroff91f78082007-12-10 22:44:33 +0000481 // FIXME: It might be better if we could point to the declaration
482 // here, instead of the string literal.
483 Diag(literal->getSourceRange().getBegin(),
484 diag::array_of_wrong_type_initialized_from_string,
485 ElementType.getAsString());
486 hadError = true;
Steve Narofff33527a2007-09-02 15:34:30 +0000487 }
Steve Naroff91f78082007-12-10 22:44:33 +0000488
489 // Check for excess initializers
490 for (unsigned i = 1; i < IList->getNumInits(); i++) {
491 Expr *expr = IList->getInit(i);
492 Diag(expr->getLocStart(),
493 diag::err_excess_initializers_in_char_array_initializer,
494 expr->getSourceRange());
495 }
496
497 return true;
Steve Naroffac074b42007-09-04 02:20:04 +0000498 }
Steve Naroff91f78082007-12-10 22:44:33 +0000499
500 return false;
Steve Naroffac074b42007-09-04 02:20:04 +0000501}
502
503// FIXME: Doesn't deal with arrays of structures yet.
504void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
505 QualType ElementType, bool isStatic,
506 int &totalInits, bool &hadError) {
507 int maxElementsAtThisLevel = 0;
508 int nInitsAtLevel = 0;
509
Steve Naroff2c20c382007-12-07 21:12:53 +0000510 if (ElementType->isRecordType()) // FIXME: until we support structures...
511 return;
512
Steve Naroffac074b42007-09-04 02:20:04 +0000513 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
514 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff67ae4432007-09-04 21:13:33 +0000515 maxElementsAtThisLevel = CAT->getMaximumElements();
516 // Set DeclType, used below to recurse (for multi-dimensional arrays).
517 DeclType = CAT->getElementType();
Steve Naroffac074b42007-09-04 02:20:04 +0000518 } else if (DeclType->isScalarType()) {
Anders Carlsson5dd106b2007-12-03 01:01:28 +0000519 if (const VectorType *VT = DeclType->getAsVectorType())
520 maxElementsAtThisLevel = VT->getNumElements();
521 else {
522 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
523 IList->getSourceRange());
524 maxElementsAtThisLevel = 1;
525 }
Steve Naroffac074b42007-09-04 02:20:04 +0000526 }
527 // The empty init list "{ }" is treated specially below.
528 unsigned numInits = IList->getNumInits();
529 if (numInits) {
Steve Naroff91f78082007-12-10 22:44:33 +0000530 if (CheckForCharArrayInitializer(IList, ElementType,
531 maxElementsAtThisLevel,
532 true, hadError))
533 return;
534
Steve Naroffac074b42007-09-04 02:20:04 +0000535 for (unsigned i = 0; i < numInits; i++) {
536 Expr *expr = IList->getInit(i);
537
538 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
539 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
540 totalInits, hadError);
541 } else {
Steve Naroff77b97002007-09-04 14:36:54 +0000542 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroffac074b42007-09-04 02:20:04 +0000543 nInitsAtLevel++; // increment the number of initializers at this level.
544 totalInits--; // decrement the total number of initializers.
545
546 // Check if we have space for another initializer.
Anders Carlssoncbdb6f52007-12-05 04:57:06 +0000547 if (((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0)))
Steve Naroffac074b42007-09-04 02:20:04 +0000548 Diag(expr->getLocStart(), diag::warn_excess_initializers,
549 expr->getSourceRange());
550 }
551 }
552 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
553 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
554 } else {
555 // we have an initializer list with no elements.
556 totalInits -= maxElementsAtThisLevel;
557 if (totalInits < 0)
558 Diag(IList->getLocStart(), diag::warn_excess_initializers,
559 IList->getSourceRange());
Steve Narofff33527a2007-09-02 15:34:30 +0000560 }
Steve Narofff33527a2007-09-02 15:34:30 +0000561}
562
Steve Naroff77b97002007-09-04 14:36:54 +0000563bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Naroff91f78082007-12-10 22:44:33 +0000564 bool hadError = false;
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000565
Steve Naroff91f78082007-12-10 22:44:33 +0000566 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
567 if (!InitList) {
568 if (StringLiteral *strLiteral = dyn_cast<StringLiteral>(Init)) {
569 const VariableArrayType *VAT = DeclType->getAsVariableArrayType();
570 // FIXME: Handle wide strings
571 if (VAT && VAT->getElementType()->isCharType()) {
572 // C99 6.7.8p14. We have an array of character type with unknown size
573 // being initialized to a string literal.
574 llvm::APSInt ConstVal(32);
575 ConstVal = strLiteral->getByteLength() + 1;
576 // Return a new array type (C99 6.7.8p22).
577 DeclType = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
578 ArrayType::Normal, 0);
Steve Narofff727faf2007-12-11 00:00:01 +0000579 // set type from "char *" to "constant array of char".
580 strLiteral->setType(DeclType);
Steve Naroff91f78082007-12-10 22:44:33 +0000581 return hadError;
582 }
583 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
584 if (CAT && CAT->getElementType()->isCharType()) {
585 // C99 6.7.8p14. We have an array of character type with known size.
586 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements()) {
587 Diag(strLiteral->getSourceRange().getBegin(),
588 diag::warn_initializer_string_for_char_array_too_long,
589 strLiteral->getSourceRange());
590 }
Steve Narofff727faf2007-12-11 00:00:01 +0000591 // set type from "char *" to "constant array of char".
592 strLiteral->setType(DeclType);
Steve Naroff91f78082007-12-10 22:44:33 +0000593 return hadError;
594 }
595 }
596 return CheckSingleInitializer(Init, isStatic, DeclType);
597 }
Steve Naroff2fea1392007-09-02 02:04:30 +0000598 // We have an InitListExpr, make sure we set the type.
599 Init->setType(DeclType);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000600
Steve Naroffb03f5942007-09-02 20:30:18 +0000601 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
602 // of unknown size ("[]") or an object type that is not a variable array type.
603 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
Chris Lattner78e34a02007-12-18 07:02:56 +0000604 if (const Expr *expr = VAT->getSizeExpr())
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000605 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
606 expr->getSourceRange());
607
Steve Naroff67ae4432007-09-04 21:13:33 +0000608 // We have a VariableArrayType with unknown size. Note that only the first
609 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroffac074b42007-09-04 02:20:04 +0000610 int numInits = 0;
Steve Naroff67ae4432007-09-04 21:13:33 +0000611 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
612 isStatic, numInits, hadError);
Steve Naroff91f78082007-12-10 22:44:33 +0000613 llvm::APSInt ConstVal(32);
614
615 if (!hadError)
Steve Naroffac074b42007-09-04 02:20:04 +0000616 ConstVal = numInits;
Steve Naroff91f78082007-12-10 22:44:33 +0000617
618 // Return a new array type from the number of initializers (C99 6.7.8p22).
619
620 // Note that if there was an error, we will still set the decl type,
621 // to an array type with 0 elements.
622 // This is to avoid "incomplete type foo[]" errors when we've already
623 // reported the real cause of the error.
624 DeclType = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
625 ArrayType::Normal, 0);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000626 return hadError;
627 }
628 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff67ae4432007-09-04 21:13:33 +0000629 int maxElements = CAT->getMaximumElements();
630 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
631 isStatic, maxElements, hadError);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000632 return hadError;
633 }
Anders Carlsson5dd106b2007-12-03 01:01:28 +0000634 if (const VectorType *VT = DeclType->getAsVectorType()) {
635 int maxElements = VT->getNumElements();
636 CheckConstantInitList(DeclType, InitList, VT->getElementType(),
637 isStatic, maxElements, hadError);
638 return hadError;
639 }
Steve Naroffac074b42007-09-04 02:20:04 +0000640 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
641 int maxElements = 1;
642 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
643 hadError);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000644 return hadError;
Steve Naroffb03f5942007-09-02 20:30:18 +0000645 }
Steve Naroff2644aaf2007-12-05 04:00:10 +0000646 // FIXME: Handle struct/union types, including those appearing in a
647 // CompoundLiteralExpr...
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000648 return hadError;
Steve Naroff2fea1392007-09-02 02:04:30 +0000649}
650
Fariborz Jahanian56ff1462007-11-08 23:49:49 +0000651Sema::DeclTy *
Steve Naroff30d242c2007-09-15 18:49:24 +0000652Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroffa23cc792007-09-13 23:52:58 +0000653 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattnere168f762006-11-10 05:29:30 +0000654 IdentifierInfo *II = D.getIdentifier();
Chris Lattner302b4be2006-11-19 02:31:38 +0000655
Chris Lattner02c04392007-07-25 00:24:17 +0000656 // All of these full declarators require an identifier. If it doesn't have
657 // one, the ParsedFreeStandingDeclSpec action should be used.
658 if (II == 0) {
Chris Lattnera7c19fe2007-10-16 22:36:42 +0000659 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerc4f6d0c2007-08-28 06:17:15 +0000660 diag::err_declarator_need_ident,
Chris Lattner02c04392007-07-25 00:24:17 +0000661 D.getDeclSpec().getSourceRange(), D.getSourceRange());
662 return 0;
663 }
664
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000665 // The scope passed in may not be a decl scope. Zip up the scope tree until
666 // we find one that is.
667 while ((S->getFlags() & Scope::DeclScope) == 0)
668 S = S->getParent();
669
Chris Lattner01564d92007-01-27 19:27:06 +0000670 // See if this is a redefinition of a variable in the same scope.
Steve Naroff9324db12007-09-13 18:10:37 +0000671 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
672 D.getIdentifierLoc(), S);
Chris Lattner776fac82007-06-09 00:53:06 +0000673 if (PrevDecl && !S->isDeclScope(PrevDecl))
Chris Lattner01564d92007-01-27 19:27:06 +0000674 PrevDecl = 0; // If in outer scope, it isn't the same thing.
675
Steve Naroff9324db12007-09-13 18:10:37 +0000676 ScopedDecl *New;
Steve Narofff93b6722007-08-28 20:14:24 +0000677 bool InvalidDecl = false;
678
Chris Lattner07b201d2007-11-14 06:34:38 +0000679 QualType R = GetTypeForDeclarator(D, S);
680 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
681
Chris Lattner01a7c532007-01-25 23:09:03 +0000682 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner07b201d2007-11-14 06:34:38 +0000683 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner01564d92007-01-27 19:27:06 +0000684 if (!NewTD) return 0;
Steve Naroffa8fd9732007-06-11 00:35:03 +0000685
686 // Handle attributes prior to checking for duplicates in MergeVarDecl
687 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
688 D.getAttributes());
Chris Lattner01564d92007-01-27 19:27:06 +0000689 // Merge the decl with the existing one if appropriate.
690 if (PrevDecl) {
691 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
692 if (NewTD == 0) return 0;
693 }
694 New = NewTD;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000695 if (S->getParent() == 0) {
696 // C99 6.7.7p2: If a typedef name specifies a variably modified type
697 // then it shall have block scope.
Steve Naroff096dd942007-08-31 17:20:07 +0000698 if (const VariableArrayType *VAT =
699 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
700 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
701 VAT->getSizeExpr()->getSourceRange());
702 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000703 }
704 }
Chris Lattner07b201d2007-11-14 06:34:38 +0000705 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattnercc61bf52007-09-27 15:15:46 +0000706 FunctionDecl::StorageClass SC = FunctionDecl::None;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000707 switch (D.getDeclSpec().getStorageClassSpec()) {
708 default: assert(0 && "Unknown storage class!");
709 case DeclSpec::SCS_auto:
710 case DeclSpec::SCS_register:
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000711 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
712 R.getAsString());
Steve Narofff93b6722007-08-28 20:14:24 +0000713 InvalidDecl = true;
714 break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000715 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
716 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
717 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
718 }
719
Chris Lattner776fac82007-06-09 00:53:06 +0000720 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattnerb677a932007-08-26 04:02:13 +0000721 D.getDeclSpec().isInlineSpecified(),
Nate Begemana0f78972007-11-13 22:14:47 +0000722 LastDeclarator,
723 D.getDeclSpec().getAttributes());
724
725 // Transfer ownership of DeclSpec attributes to FunctionDecl
726 D.getDeclSpec().clearAttributes();
Chris Lattner01564d92007-01-27 19:27:06 +0000727
728 // Merge the decl with the existing one if appropriate.
729 if (PrevDecl) {
730 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
731 if (NewFD == 0) return 0;
732 }
733 New = NewFD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000734 } else {
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +0000735 if (R.getTypePtr()->isObjcInterfaceType()) {
736 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
737 D.getIdentifier()->getName());
738 InvalidDecl = true;
739 }
Chris Lattner01564d92007-01-27 19:27:06 +0000740
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000741 VarDecl *NewVD;
742 VarDecl::StorageClass SC;
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000743 switch (D.getDeclSpec().getStorageClassSpec()) {
744 default: assert(0 && "Unknown storage class!");
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000745 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
746 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
747 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
748 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
749 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
750 }
Steve Narofffc49d672007-04-01 21:27:45 +0000751 if (S->getParent() == 0) {
Bill Wendlingd6de6572007-06-02 09:40:07 +0000752 // C99 6.9p2: The storage-class specifiers auto and register shall not
753 // appear in the declaration specifiers in an external declaration.
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000754 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000755 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
756 R.getAsString());
Steve Naroffcf871f52007-08-28 18:45:29 +0000757 InvalidDecl = true;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000758 }
Chris Lattner776fac82007-06-09 00:53:06 +0000759 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff2fea1392007-09-02 02:04:30 +0000760 } else {
Chris Lattner776fac82007-06-09 00:53:06 +0000761 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcf871f52007-08-28 18:45:29 +0000762 }
Steve Naroffa8fd9732007-06-11 00:35:03 +0000763 // Handle attributes prior to checking for duplicates in MergeVarDecl
764 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
765 D.getAttributes());
766
Chris Lattner01564d92007-01-27 19:27:06 +0000767 // Merge the decl with the existing one if appropriate.
768 if (PrevDecl) {
769 NewVD = MergeVarDecl(NewVD, PrevDecl);
770 if (NewVD == 0) return 0;
771 }
772 New = NewVD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000773 }
Chris Lattner302b4be2006-11-19 02:31:38 +0000774
Chris Lattnere168f762006-11-10 05:29:30 +0000775 // If this has an identifier, add it to the scope stack.
776 if (II) {
Steve Naroff9324db12007-09-13 18:10:37 +0000777 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattnere168f762006-11-10 05:29:30 +0000778 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000779 S->AddDecl(New);
Chris Lattnere168f762006-11-10 05:29:30 +0000780 }
Steve Narofff93b6722007-08-28 20:14:24 +0000781 // If any semantic error occurred, mark the decl as invalid.
782 if (D.getInvalidType() || InvalidDecl)
783 New->setInvalidDecl();
Chris Lattnere168f762006-11-10 05:29:30 +0000784
785 return New;
786}
787
Steve Naroff61091402007-09-12 14:07:44 +0000788void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff437b4d82007-09-12 20:13:48 +0000789 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff61091402007-09-12 14:07:44 +0000790 Expr *Init = static_cast<Expr *>(init);
Chris Lattner8beb9de2007-10-19 20:10:30 +0000791 assert(Init && "missing initializer");
Steve Naroff61091402007-09-12 14:07:44 +0000792
Chris Lattner8beb9de2007-10-19 20:10:30 +0000793 // If there is no declaration, there was an error parsing it. Just ignore
794 // the initializer.
795 if (RealDecl == 0) {
796 delete Init;
797 return;
798 }
Steve Naroff61091402007-09-12 14:07:44 +0000799
Steve Naroff437b4d82007-09-12 20:13:48 +0000800 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
801 if (!VDecl) {
Steve Naroff9def2b12007-09-13 21:41:19 +0000802 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
803 diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +0000804 RealDecl->setInvalidDecl();
805 return;
806 }
Steve Naroff61091402007-09-12 14:07:44 +0000807 // Get the decls type and save a reference for later, since
808 // CheckInitializer may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +0000809 QualType DclT = VDecl->getType(), SavT = DclT;
810 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff61091402007-09-12 14:07:44 +0000811 VarDecl::StorageClass SC = BVD->getStorageClass();
812 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +0000813 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff61091402007-09-12 14:07:44 +0000814 BVD->setInvalidDecl();
815 } else if (!BVD->isInvalidDecl()) {
816 CheckInitializer(Init, DclT, SC == VarDecl::Static);
817 }
Steve Naroff437b4d82007-09-12 20:13:48 +0000818 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff61091402007-09-12 14:07:44 +0000819 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff437b4d82007-09-12 20:13:48 +0000820 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff61091402007-09-12 14:07:44 +0000821 if (!FVD->isInvalidDecl())
822 CheckInitializer(Init, DclT, true);
823 }
824 // If the type changed, it means we had an incomplete type that was
825 // completed by the initializer. For example:
826 // int ary[] = { 1, 3, 5 };
827 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb2ed9afd2007-11-29 19:09:19 +0000828 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff437b4d82007-09-12 20:13:48 +0000829 VDecl->setType(DclT);
Christopher Lamb2ed9afd2007-11-29 19:09:19 +0000830 Init->setType(DclT);
831 }
Steve Naroff61091402007-09-12 14:07:44 +0000832
833 // Attach the initializer to the decl.
Steve Naroff437b4d82007-09-12 20:13:48 +0000834 VDecl->setInit(Init);
Steve Naroff61091402007-09-12 14:07:44 +0000835 return;
836}
837
Chris Lattner776fac82007-06-09 00:53:06 +0000838/// The declarators are chained together backwards, reverse the list.
839Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
840 // Often we have single declarators, handle them quickly.
Steve Naroffa23cc792007-09-13 23:52:58 +0000841 Decl *GroupDecl = static_cast<Decl*>(group);
842 if (GroupDecl == 0)
Steve Naroff61091402007-09-12 14:07:44 +0000843 return 0;
Steve Naroffa23cc792007-09-13 23:52:58 +0000844
845 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
846 ScopedDecl *NewGroup = 0;
Steve Naroff61091402007-09-12 14:07:44 +0000847 if (Group->getNextDeclarator() == 0)
Chris Lattner776fac82007-06-09 00:53:06 +0000848 NewGroup = Group;
Steve Naroff61091402007-09-12 14:07:44 +0000849 else { // reverse the list.
850 while (Group) {
Steve Naroffa23cc792007-09-13 23:52:58 +0000851 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff61091402007-09-12 14:07:44 +0000852 Group->setNextDeclarator(NewGroup);
853 NewGroup = Group;
854 Group = Next;
855 }
856 }
857 // Perform semantic analysis that depends on having fully processed both
858 // the declarator and initializer.
Steve Naroffa23cc792007-09-13 23:52:58 +0000859 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff61091402007-09-12 14:07:44 +0000860 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
861 if (!IDecl)
862 continue;
863 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
864 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
865 QualType T = IDecl->getType();
866
867 // C99 6.7.5.2p2: If an identifier is declared to be an object with
868 // static storage duration, it shall not have a variable length array.
869 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
870 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
871 if (VLA->getSizeExpr()) {
872 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
873 IDecl->setInvalidDecl();
874 }
875 }
876 }
877 // Block scope. C99 6.7p7: If an identifier for an object is declared with
878 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
879 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
880 if (T->isIncompleteType()) {
Chris Lattner310369f2007-12-02 07:50:03 +0000881 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
882 T.getAsString());
Steve Naroff61091402007-09-12 14:07:44 +0000883 IDecl->setInvalidDecl();
884 }
885 }
886 // File scope. C99 6.9.2p2: A declaration of an identifier for and
887 // object that has file scope without an initializer, and without a
888 // storage-class specifier or with the storage-class specifier "static",
889 // constitutes a tentative definition. Note: A tentative definition with
890 // external linkage is valid (C99 6.2.2p5).
891 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
892 // C99 6.9.2p3: If the declaration of an identifier for an object is
893 // a tentative definition and has internal linkage (C99 6.2.2p3), the
894 // declared type shall not be an incomplete type.
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 }
Chris Lattner776fac82007-06-09 00:53:06 +0000901 }
902 return NewGroup;
903}
Steve Naroff7e6f7c22007-08-28 03:03:08 +0000904
905// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner53621a52007-06-13 20:44:40 +0000906ParmVarDecl *
Nate Begeman313f8ca2007-11-13 21:49:48 +0000907Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI, Scope *FnScope)
Steve Naroffd0bf5162007-11-12 03:44:46 +0000908{
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000909 IdentifierInfo *II = PI.Ident;
Chris Lattnerc284e9b2007-01-23 05:14:32 +0000910 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
911 // Can this happen for params? We already checked that they don't conflict
912 // among each other. Here they can only shadow globals, which is ok.
Chris Lattnerd2b88ab2007-07-13 03:05:23 +0000913 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Chris Lattner9561a0b2007-01-28 08:20:04 +0000914 PI.IdentLoc, FnScope)) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000915
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000916 }
917
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000918 // FIXME: Handle storage class (auto, register). No declarator?
Chris Lattner776fac82007-06-09 00:53:06 +0000919 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff773df5c2007-08-07 22:44:21 +0000920
921 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
922 // Doing the promotion here has a win and a loss. The win is the type for
923 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
924 // code generator). The loss is the orginal type isn't preserved. For example:
925 //
926 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
927 // int blockvardecl[5];
928 // sizeof(parmvardecl); // size == 4
929 // sizeof(blockvardecl); // size == 20
930 // }
931 //
932 // For expressions, all implicit conversions are captured using the
933 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
934 //
935 // FIXME: If a source translation tool needs to see the original type, then
936 // we need to consider storing both types (in ParmVarDecl)...
937 //
938 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
939 if (const ArrayType *AT = parmDeclType->getAsArrayType())
940 parmDeclType = Context.getPointerType(AT->getElementType());
941 else if (parmDeclType->isFunctionType())
942 parmDeclType = Context.getPointerType(parmDeclType);
943
944 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Nate Begemana0f78972007-11-13 22:14:47 +0000945 VarDecl::None, 0, PI.AttrList);
Steve Naroffcf871f52007-08-28 18:45:29 +0000946 if (PI.InvalidType)
947 New->setInvalidDecl();
948
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000949 // If this has an identifier, add it to the scope stack.
950 if (II) {
Steve Naroff9324db12007-09-13 18:10:37 +0000951 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000952 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000953 FnScope->AddDecl(New);
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000954 }
Chris Lattner229ce602006-11-21 01:21:07 +0000955
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000956 return New;
957}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +0000958
Chris Lattnera55a2cc2007-10-09 17:14:05 +0000959Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner229ce602006-11-21 01:21:07 +0000960 assert(CurFunctionDecl == 0 && "Function parsing confused");
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000961 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
962 "Not a function declarator!");
963 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
964
965 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
966 // for a K&R function.
967 if (!FTI.hasPrototype) {
968 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
969 if (FTI.ArgInfo[i].TypeInfo == 0) {
Chris Lattner843c5922007-06-10 23:40:34 +0000970 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000971 FTI.ArgInfo[i].Ident->getName());
972 // Implicitly declare the argument as type 'int' for lack of a better
973 // type.
974 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
975 }
976 }
977
978 // Since this is a function definition, act as though we have information
979 // about the arguments.
980 FTI.hasPrototype = true;
Chris Lattner2114d5e2006-12-04 07:40:24 +0000981 } else {
982 // FIXME: Diagnose arguments without names in C.
983
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000984 }
985
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000986 Scope *GlobalScope = FnBodyScope->getParent();
987
988 FunctionDecl *FD =
Steve Naroff30d242c2007-09-15 18:49:24 +0000989 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattner229ce602006-11-21 01:21:07 +0000990 CurFunctionDecl = FD;
Chris Lattner2114d5e2006-12-04 07:40:24 +0000991
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000992 // Create Decl objects for each parameter, adding them to the FunctionDecl.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000993 llvm::SmallVector<ParmVarDecl*, 16> Params;
Chris Lattnerf61c8a82007-01-21 19:04:43 +0000994
995 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
996 // no arguments, not a function that takes a single void argument.
997 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerdb2a6ef2007-11-28 18:51:29 +0000998 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getQualifiers() &&
999 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Chris Lattner99d31772007-01-21 22:37:37 +00001000 // empty arg list, don't push any params.
Chris Lattnerf61c8a82007-01-21 19:04:43 +00001001 } else {
Steve Naroffd0bf5162007-11-12 03:44:46 +00001002 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begeman313f8ca2007-11-13 21:49:48 +00001003 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroffd0bf5162007-11-12 03:44:46 +00001004 FnBodyScope));
1005 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00001006 }
Chris Lattner2114d5e2006-12-04 07:40:24 +00001007
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001008 FD->setParams(&Params[0], Params.size());
Chris Lattner2114d5e2006-12-04 07:40:24 +00001009
Chris Lattnere168f762006-11-10 05:29:30 +00001010 return FD;
1011}
1012
Steve Naroffb313fc32007-11-11 23:20:51 +00001013Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1014 Decl *dcl = static_cast<Decl *>(D);
1015 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1016 FD->setBody((Stmt*)Body);
1017 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroffd78c81b2007-12-13 18:18:56 +00001018 CurFunctionDecl = 0;
Steve Naroffb313fc32007-11-11 23:20:51 +00001019 } else if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(dcl)) {
1020 MD->setBody((Stmt*)Body);
Steve Naroffe3d1ab22007-11-12 13:56:41 +00001021 CurMethodDecl = 0;
Steve Naroffd78c81b2007-12-13 18:18:56 +00001022 }
Chris Lattnere2473062007-05-28 06:28:18 +00001023 // Verify and clean out per-function state.
1024
1025 // Check goto/label use.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001026 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1027 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
Chris Lattnere2473062007-05-28 06:28:18 +00001028 // Verify that we have no forward references left. If so, there was a goto
1029 // or address of a label taken, but no definition of it. Label fwd
1030 // definitions are indicated with a null substmt.
1031 if (I->second->getSubStmt() == 0) {
1032 LabelStmt *L = I->second;
1033 // Emit error.
Chris Lattnereefa10e2007-05-28 06:56:27 +00001034 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
Chris Lattnere2473062007-05-28 06:28:18 +00001035
1036 // At this point, we have gotos that use the bogus label. Stitch it into
1037 // the function body so that they aren't leaked and that the AST is well
1038 // formed.
1039 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1040 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1041 }
1042 }
1043 LabelMap.clear();
1044
Steve Naroffb313fc32007-11-11 23:20:51 +00001045 return D;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00001046}
1047
Chris Lattnerac18be92006-11-20 06:49:47 +00001048/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1049/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff2f742082007-09-16 16:16:00 +00001050ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1051 IdentifierInfo &II, Scope *S) {
Chris Lattnerac18be92006-11-20 06:49:47 +00001052 if (getLangOptions().C99) // Extension in C99.
1053 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1054 else // Legal in C90, but warn about it.
1055 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1056
1057 // FIXME: handle stuff like:
1058 // void foo() { extern float X(); }
1059 // void bar() { X(); } <-- implicit decl for X in another scope.
1060
1061 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00001062 const char *Dummy;
Chris Lattnerac18be92006-11-20 06:49:47 +00001063 DeclSpec DS;
Chris Lattnerb20e8942006-11-28 05:30:29 +00001064 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001065 Error = Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00001066 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00001067 Declarator D(DS, Declarator::BlockContext);
Chris Lattnercbc426d2006-12-02 06:43:02 +00001068 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
Chris Lattnerac18be92006-11-20 06:49:47 +00001069 D.SetIdentifier(&II, Loc);
1070
Chris Lattner62d2e662007-01-28 00:21:37 +00001071 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001072 if (Scope *FnS = S->getFnParent())
1073 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner62d2e662007-01-28 00:21:37 +00001074 while (S->getParent())
1075 S = S->getParent();
Chris Lattnerac18be92006-11-20 06:49:47 +00001076
Steve Naroff2f742082007-09-16 16:16:00 +00001077 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattnerac18be92006-11-20 06:49:47 +00001078}
1079
Chris Lattner302b4be2006-11-19 02:31:38 +00001080
Chris Lattner07b201d2007-11-14 06:34:38 +00001081TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroffa23cc792007-09-13 23:52:58 +00001082 ScopedDecl *LastDeclarator) {
Chris Lattner776fac82007-06-09 00:53:06 +00001083 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00001084 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001085
Chris Lattner18b19622007-01-22 07:39:13 +00001086 // Scope manipulation handled by caller.
Steve Narofff93b6722007-08-28 20:14:24 +00001087 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
1088 T, LastDeclarator);
1089 if (D.getInvalidType())
1090 NewTD->setInvalidDecl();
1091 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00001092}
1093
Steve Naroff30d242c2007-09-15 18:49:24 +00001094/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00001095/// former case, Name will be non-null. In the later case, Name will be null.
1096/// TagType indicates what kind of tag this is. TK indicates whether this is a
1097/// reference/declaration/definition of a tag.
Steve Naroff30d242c2007-09-15 18:49:24 +00001098Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001099 SourceLocation KWLoc, IdentifierInfo *Name,
Steve Naroffb3096442007-06-09 03:47:53 +00001100 SourceLocation NameLoc, AttributeList *Attr) {
Chris Lattner8799cf22007-01-23 01:57:16 +00001101 // If this is a use of an existing tag, it must have a name.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001102 assert((Name != 0 || TK == TK_Definition) &&
1103 "Nameless record must be a definition!");
Chris Lattner8799cf22007-01-23 01:57:16 +00001104
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001105 Decl::Kind Kind;
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001106 switch (TagType) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001107 default: assert(0 && "Unknown tag type!");
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001108 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1109 case DeclSpec::TST_union: Kind = Decl::Union; break;
1110//case DeclSpec::TST_class: Kind = Decl::Class; break;
1111 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001112 }
Chris Lattner7e783a12007-01-23 02:05:42 +00001113
Chris Lattner18b19622007-01-22 07:39:13 +00001114 // If this is a named struct, check to see if there was a previous forward
1115 // declaration or definition.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001116 if (TagDecl *PrevDecl =
Chris Lattner9561a0b2007-01-28 08:20:04 +00001117 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1118 NameLoc, S))) {
Chris Lattner8799cf22007-01-23 01:57:16 +00001119
1120 // If this is a use of a previous tag, or if the tag is already declared in
1121 // the same scope (so that the definition/declaration completes or
1122 // rementions the tag), reuse the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001123 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
Chris Lattner7e783a12007-01-23 02:05:42 +00001124 // Make sure that this wasn't declared as an enum and now used as a struct
1125 // or something similar.
1126 if (PrevDecl->getKind() != Kind) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001127 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
Chris Lattner7e783a12007-01-23 02:05:42 +00001128 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1129 }
Chris Lattner7b9ace62007-01-23 20:11:08 +00001130
1131 // If this is a use or a forward declaration, we're good.
1132 if (TK != TK_Definition)
1133 return PrevDecl;
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001134
Chris Lattner7b9ace62007-01-23 20:11:08 +00001135 // Diagnose attempts to redefine a tag.
1136 if (PrevDecl->isDefinition()) {
1137 Diag(NameLoc, diag::err_redefinition, Name->getName());
1138 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1139 // If this is a redefinition, recover by making this struct be
1140 // anonymous, which will make any later references get the previous
1141 // definition.
1142 Name = 0;
1143 } else {
1144 // Okay, this is definition of a previously declared or referenced tag.
1145 // Move the location of the decl to be the definition site.
1146 PrevDecl->setLocation(NameLoc);
Chris Lattner7b9ace62007-01-23 20:11:08 +00001147 return PrevDecl;
1148 }
Chris Lattner8799cf22007-01-23 01:57:16 +00001149 }
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001150 // If we get here, this is a definition of a new struct type in a nested
1151 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1152 // type.
Chris Lattner18b19622007-01-22 07:39:13 +00001153 }
1154
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001155 // If there is an identifier, use the location of the identifier as the
1156 // location of the decl, otherwise use the location of the struct/union
1157 // keyword.
1158 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1159
Chris Lattner18b19622007-01-22 07:39:13 +00001160 // Otherwise, if this is the first time we've seen this tag, create the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001161 TagDecl *New;
Chris Lattner720a0542007-01-25 00:44:24 +00001162 switch (Kind) {
1163 default: assert(0 && "Unknown tag kind!");
Chris Lattner5f521502007-01-25 06:27:24 +00001164 case Decl::Enum:
Chris Lattner776fac82007-06-09 00:53:06 +00001165 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1166 // enum X { A, B, C } D; D should chain to X.
1167 New = new EnumDecl(Loc, Name, 0);
Chris Lattner5f521502007-01-25 06:27:24 +00001168 // If this is an undefined enum, warn.
Chris Lattnerc1915e22007-01-25 07:29:02 +00001169 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Chris Lattner5f521502007-01-25 06:27:24 +00001170 break;
Chris Lattner720a0542007-01-25 00:44:24 +00001171 case Decl::Union:
1172 case Decl::Struct:
1173 case Decl::Class:
Chris Lattner776fac82007-06-09 00:53:06 +00001174 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1175 // struct X { int A; } D; D should chain to X.
1176 New = new RecordDecl(Kind, Loc, Name, 0);
Chris Lattner720a0542007-01-25 00:44:24 +00001177 break;
1178 }
Chris Lattner18b19622007-01-22 07:39:13 +00001179
1180 // If this has an identifier, add it to the scope stack.
1181 if (Name) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001182 // The scope passed in may not be a decl scope. Zip up the scope tree until
1183 // we find one that is.
1184 while ((S->getFlags() & Scope::DeclScope) == 0)
1185 S = S->getParent();
1186
1187 // Add it to the decl chain.
Steve Naroff9324db12007-09-13 18:10:37 +00001188 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner18b19622007-01-22 07:39:13 +00001189 Name->setFETokenInfo(New);
1190 S->AddDecl(New);
1191 }
Steve Naroff197616c2007-11-28 22:54:11 +00001192
Chris Lattner18b19622007-01-22 07:39:13 +00001193 return New;
1194}
Chris Lattner1300fb92007-01-23 23:42:53 +00001195
Steve Naroff30d242c2007-09-15 18:49:24 +00001196/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00001197/// to create a FieldDecl object for it.
Steve Naroff30d242c2007-09-15 18:49:24 +00001198Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Chris Lattner1300fb92007-01-23 23:42:53 +00001199 SourceLocation DeclStart,
1200 Declarator &D, ExprTy *BitfieldWidth) {
1201 IdentifierInfo *II = D.getIdentifier();
1202 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner1300fb92007-01-23 23:42:53 +00001203 SourceLocation Loc = DeclStart;
1204 if (II) Loc = D.getIdentifierLoc();
1205
Chris Lattner62d2e662007-01-28 00:21:37 +00001206 // FIXME: Unnamed fields can be handled in various different ways, for
1207 // example, unnamed unions inject all members into the struct namespace!
1208
1209
Chris Lattner1300fb92007-01-23 23:42:53 +00001210 if (BitWidth) {
1211 // TODO: Validate.
Steve Narofff84d11f2007-05-23 21:48:04 +00001212 //printf("WARNING: BITFIELDS IGNORED!\n");
Chris Lattner1300fb92007-01-23 23:42:53 +00001213
1214 // 6.7.2.1p3
1215 // 6.7.2.1p4
1216
1217 } else {
1218 // Not a bitfield.
1219
1220 // validate II.
1221
1222 }
1223
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001224 QualType T = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +00001225 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1226 bool InvalidDecl = false;
Steve Naroff096dd942007-08-31 17:20:07 +00001227
Steve Naroff8eeeb132007-05-08 21:09:37 +00001228 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1229 // than a variably modified type.
Steve Naroff096dd942007-08-31 17:20:07 +00001230 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1231 Diag(Loc, diag::err_typecheck_illegal_vla,
1232 VAT->getSizeExpr()->getSourceRange());
1233 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +00001234 }
Chris Lattner776fac82007-06-09 00:53:06 +00001235 // FIXME: Chain fielddecls together.
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001236 FieldDecl *NewFD;
1237
1238 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patel32714062007-11-01 16:29:56 +00001239 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Steve Naroff3434beb2007-11-12 04:22:52 +00001240 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1241 isa<ObjcImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroff9e0887cf2007-11-14 14:15:31 +00001242 isa<ObjcCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
1243 // FIXME: ivars are currently used to model properties, and
1244 // properties can appear within a protocol.
1245 // See corresponding FIXME in DeclObjC.h:ObjcPropertyDecl.
1246 isa<ObjcProtocolDecl>(static_cast<Decl *>(TagDecl)))
Steve Naroff1d4b5eae2007-09-14 02:20:46 +00001247 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001248 else
Steve Naroff30d242c2007-09-15 18:49:24 +00001249 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001250
Steve Narofff93b6722007-08-28 20:14:24 +00001251 if (D.getInvalidType() || InvalidDecl)
1252 NewFD->setInvalidDecl();
1253 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00001254}
1255
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001256/// TranslateIvarVisibility - Translate visibility from a token ID to an
1257/// AST enum value.
1258static ObjcIvarDecl::AccessControl
1259TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00001260 switch (ivarVisibility) {
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001261 case tok::objc_private: return ObjcIvarDecl::Private;
1262 case tok::objc_public: return ObjcIvarDecl::Public;
1263 case tok::objc_protected: return ObjcIvarDecl::Protected;
1264 case tok::objc_package: return ObjcIvarDecl::Package;
1265 default: assert(false && "Unknown visitibility kind");
Steve Naroff2e688fd2007-09-14 23:09:53 +00001266 }
1267}
1268
Fariborz Jahanian343f7092007-09-29 00:54:24 +00001269void Sema::ActOnFields(Scope* S,
Fariborz Jahanian67341402007-10-04 00:45:27 +00001270 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff30d242c2007-09-15 18:49:24 +00001271 DeclTy **Fields, unsigned NumFields,
Steve Naroff33a1e802007-10-29 21:38:07 +00001272 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff30d242c2007-09-15 18:49:24 +00001273 tok::ObjCKeywordKind *visibility) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00001274 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1275 assert(EnclosingDecl && "missing record or interface decl");
1276 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1277
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001278 if (Record && Record->isDefinition()) {
Chris Lattner1300fb92007-01-23 23:42:53 +00001279 // Diagnose code like:
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001280 // struct S { struct S {} X; };
Chris Lattner1300fb92007-01-23 23:42:53 +00001281 // We discover this when we complete the outer S. Reject and ignore the
1282 // outer S.
1283 Diag(Record->getLocation(), diag::err_nested_redefinition,
1284 Record->getKindName());
1285 Diag(RecLoc, diag::err_previous_definition);
Steve Naroffdb47ee22007-09-14 22:20:54 +00001286 Record->setInvalidDecl();
Chris Lattner1300fb92007-01-23 23:42:53 +00001287 return;
1288 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001289 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00001290 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +00001291 llvm::SmallVector<FieldDecl*, 32> RecFields;
1292 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroffdb47ee22007-09-14 22:20:54 +00001293
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001294 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001295
Steve Naroffdb47ee22007-09-14 22:20:54 +00001296 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1297 assert(FD && "missing field decl");
1298
1299 // Remember all fields.
1300 RecFields.push_back(FD);
Chris Lattner720a0542007-01-25 00:44:24 +00001301
1302 // Get the type for the field.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001303 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner720a0542007-01-25 00:44:24 +00001304
Steve Naroff2e688fd2007-09-14 23:09:53 +00001305 // If we have visibility info, make sure the AST is set accordingly.
1306 if (visibility)
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001307 cast<ObjcIvarDecl>(FD)->setAccessControl(
1308 TranslateIvarVisibility(visibility[i]));
Steve Naroff2e688fd2007-09-14 23:09:53 +00001309
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001310 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001311 if (FDTy->isFunctionType()) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00001312 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001313 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001314 FD->setInvalidDecl();
1315 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001316 continue;
1317 }
Chris Lattner82625602007-01-24 02:26:21 +00001318 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
Chris Lattner720a0542007-01-25 00:44:24 +00001319 if (FDTy->isIncompleteType()) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001320 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian67341402007-10-04 00:45:27 +00001321 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001322 FD->setInvalidDecl();
1323 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian67341402007-10-04 00:45:27 +00001324 continue;
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001325 }
Chris Lattner82625602007-01-24 02:26:21 +00001326 if (i != NumFields-1 || // ... that the last member ...
1327 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner0fd893e2007-07-31 21:33:24 +00001328 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner82625602007-01-24 02:26:21 +00001329 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001330 FD->setInvalidDecl();
1331 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00001332 continue;
1333 }
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001334 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner82625602007-01-24 02:26:21 +00001335 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1336 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001337 FD->setInvalidDecl();
1338 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00001339 continue;
1340 }
Chris Lattner720a0542007-01-25 00:44:24 +00001341 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001342 if (Record)
1343 Record->setHasFlexibleArrayMember(true);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001344 }
Chris Lattner720a0542007-01-25 00:44:24 +00001345 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1346 /// field of another structure or the element of an array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001347 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner720a0542007-01-25 00:44:24 +00001348 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1349 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001350 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner41943152007-01-25 04:52:46 +00001351 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00001352 } else {
1353 // If this is a struct/class and this is not the last element, reject
1354 // it. Note that GCC supports variable sized arrays in the middle of
1355 // structures.
1356 if (i != NumFields-1) {
1357 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1358 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001359 FD->setInvalidDecl();
1360 EnclosingDecl->setInvalidDecl();
Chris Lattner720a0542007-01-25 00:44:24 +00001361 continue;
1362 }
Chris Lattner720a0542007-01-25 00:44:24 +00001363 // We support flexible arrays at the end of structs in other structs
1364 // as an extension.
1365 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1366 FD->getName());
Fariborz Jahanian67341402007-10-04 00:45:27 +00001367 if (Record)
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001368 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00001369 }
1370 }
1371 }
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00001372 /// A field cannot be an Objective-c object
1373 if (FDTy->isObjcInterfaceType()) {
1374 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1375 FD->getName());
1376 FD->setInvalidDecl();
1377 EnclosingDecl->setInvalidDecl();
1378 continue;
1379 }
Chris Lattner82625602007-01-24 02:26:21 +00001380 // Keep track of the number of named members.
Chris Lattnere5a66562007-01-25 22:48:42 +00001381 if (IdentifierInfo *II = FD->getIdentifier()) {
1382 // Detect duplicate member names.
Chris Lattnerbaf33662007-01-27 02:14:08 +00001383 if (!FieldIDs.insert(II)) {
Chris Lattnere5a66562007-01-25 22:48:42 +00001384 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1385 // Find the previous decl.
1386 SourceLocation PrevLoc;
1387 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1388 assert(i != e && "Didn't find previous def!");
1389 if (RecFields[i]->getIdentifier() == II) {
1390 PrevLoc = RecFields[i]->getLocation();
1391 break;
1392 }
1393 }
1394 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroffdb47ee22007-09-14 22:20:54 +00001395 FD->setInvalidDecl();
1396 EnclosingDecl->setInvalidDecl();
Chris Lattnere5a66562007-01-25 22:48:42 +00001397 continue;
1398 }
Chris Lattner82625602007-01-24 02:26:21 +00001399 ++NumNamedMembers;
Chris Lattnere5a66562007-01-25 22:48:42 +00001400 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001401 }
Chris Lattner82625602007-01-24 02:26:21 +00001402
Chris Lattner82625602007-01-24 02:26:21 +00001403 // Okay, we successfully defined 'Record'.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001404 if (Record)
1405 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00001406 else {
1407 ObjcIvarDecl **ClsFields =
1408 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00001409 if (isa<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1410 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
Steve Naroff33a1e802007-10-29 21:38:07 +00001411 addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00001412 else if (isa<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1413 ObjcImplementationDecl* IMPDecl =
Fariborz Jahanian67341402007-10-04 00:45:27 +00001414 cast<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl));
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00001415 assert(IMPDecl && "ActOnFields - missing ObjcImplementationDecl");
1416 IMPDecl->ObjcAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian95b60762007-10-31 18:48:14 +00001417 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00001418 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00001419 }
Chris Lattner1300fb92007-01-23 23:42:53 +00001420}
1421
Steve Naroff30d242c2007-09-15 18:49:24 +00001422Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4ef40012007-06-11 01:28:17 +00001423 DeclTy *lastEnumConst,
Chris Lattnerc1915e22007-01-25 07:29:02 +00001424 SourceLocation IdLoc, IdentifierInfo *Id,
Chris Lattner4ef40012007-06-11 01:28:17 +00001425 SourceLocation EqualLoc, ExprTy *val) {
1426 theEnumDecl = theEnumDecl; // silence unused warning.
1427 EnumConstantDecl *LastEnumConst =
1428 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1429 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00001430
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001431 // The scope passed in may not be a decl scope. Zip up the scope tree until
1432 // we find one that is.
1433 while ((S->getFlags() & Scope::DeclScope) == 0)
1434 S = S->getParent();
1435
Chris Lattner8116d1b2007-01-25 22:38:29 +00001436 // Verify that there isn't already something declared with this name in this
1437 // scope.
Steve Naroff9def2b12007-09-13 21:41:19 +00001438 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1439 IdLoc, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00001440 if (S->isDeclScope(PrevDecl)) {
1441 if (isa<EnumConstantDecl>(PrevDecl))
1442 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1443 else
1444 Diag(IdLoc, diag::err_redefinition, Id->getName());
1445 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner4ef40012007-06-11 01:28:17 +00001446 // FIXME: Don't leak memory: delete Val;
Chris Lattner8116d1b2007-01-25 22:38:29 +00001447 return 0;
1448 }
1449 }
Chris Lattner4ef40012007-06-11 01:28:17 +00001450
Chris Lattner23b7eb62007-06-15 23:05:46 +00001451 llvm::APSInt EnumVal(32);
Chris Lattner4ef40012007-06-11 01:28:17 +00001452 QualType EltTy;
1453 if (Val) {
Chris Lattner0515e4b2007-08-27 21:16:18 +00001454 // Make sure to promote the operand type to int.
1455 UsualUnaryConversions(Val);
1456
Chris Lattner4ef40012007-06-11 01:28:17 +00001457 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1458 SourceLocation ExpLoc;
Chris Lattner0e9d6222007-07-15 23:26:56 +00001459 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Chris Lattner4ef40012007-06-11 01:28:17 +00001460 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1461 Id->getName());
1462 // FIXME: Don't leak memory: delete Val;
Chris Lattnerf283a372007-08-27 17:37:24 +00001463 Val = 0; // Just forget about it.
Chris Lattnerc92bc4c2007-08-29 16:03:41 +00001464 } else {
1465 EltTy = Val->getType();
Chris Lattner4ef40012007-06-11 01:28:17 +00001466 }
Chris Lattnerf283a372007-08-27 17:37:24 +00001467 }
1468
1469 if (!Val) {
1470 if (LastEnumConst) {
1471 // Assign the last value + 1.
1472 EnumVal = LastEnumConst->getInitVal();
1473 ++EnumVal;
Chris Lattner0515e4b2007-08-27 21:16:18 +00001474
1475 // Check for overflow on increment.
1476 if (EnumVal < LastEnumConst->getInitVal())
1477 Diag(IdLoc, diag::warn_enum_value_overflow);
1478
Chris Lattnerf283a372007-08-27 17:37:24 +00001479 EltTy = LastEnumConst->getType();
1480 } else {
1481 // First value, set to zero.
1482 EltTy = Context.IntTy;
Chris Lattner9cf21c52007-09-04 02:45:27 +00001483 EnumVal.zextOrTrunc(
1484 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerf283a372007-08-27 17:37:24 +00001485 }
Steve Naroff63969212007-05-07 21:22:42 +00001486 }
Chris Lattner4ef40012007-06-11 01:28:17 +00001487
Chris Lattner4ef40012007-06-11 01:28:17 +00001488 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1489 LastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +00001490
1491 // Register this decl in the current scope stack.
Steve Naroff9324db12007-09-13 18:10:37 +00001492 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner8116d1b2007-01-25 22:38:29 +00001493 Id->setFETokenInfo(New);
1494 S->AddDecl(New);
1495 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001496}
1497
Steve Naroff30d242c2007-09-15 18:49:24 +00001498void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattnerc1915e22007-01-25 07:29:02 +00001499 DeclTy **Elements, unsigned NumElements) {
1500 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1501 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1502
Chris Lattner67933c02007-08-28 05:10:31 +00001503 // TODO: If the result value doesn't fit in an int, it must be a long or long
1504 // long value. ISO C does not support this, but GCC does as an extension,
1505 // emit a warning.
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001506 unsigned IntWidth =
1507 Context.Target.getIntWidth(Context.getFullLoc(Enum->getLocation()));
Chris Lattner67933c02007-08-28 05:10:31 +00001508
1509
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001510 // Verify that all the values are okay, compute the size of the values, and
1511 // reverse the list.
1512 unsigned NumNegativeBits = 0;
1513 unsigned NumPositiveBits = 0;
1514
1515 // Keep track of whether all elements have type int.
1516 bool AllElementsInt = true;
1517
Chris Lattner4ef40012007-06-11 01:28:17 +00001518 EnumConstantDecl *EltList = 0;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001519 for (unsigned i = 0; i != NumElements; ++i) {
1520 EnumConstantDecl *ECD =
1521 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1522 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnerbf478cb2007-08-28 05:27:00 +00001523
1524 // If the enum value doesn't fit in an int, emit an extension warning.
1525 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1526 "Should have promoted value to int");
1527 const llvm::APSInt &InitVal = ECD->getInitVal();
1528 if (InitVal.getBitWidth() > IntWidth) {
1529 llvm::APSInt V(InitVal);
1530 V.trunc(IntWidth);
1531 V.extend(InitVal.getBitWidth());
1532 if (V != InitVal)
1533 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1534 InitVal.toString());
1535 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001536
1537 // Keep track of the size of positive and negative values.
1538 if (InitVal.isUnsigned() || !InitVal.isNegative())
1539 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1540 else
1541 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00001542
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001543 // Keep track of whether every enum element has type int (very commmon).
1544 if (AllElementsInt)
1545 AllElementsInt = ECD->getType() == Context.IntTy;
1546
Chris Lattner4ef40012007-06-11 01:28:17 +00001547 ECD->setNextDeclarator(EltList);
1548 EltList = ECD;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001549 }
1550
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001551 // Figure out the type that should be used for this enum.
1552 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1553 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001554 unsigned BestWidth;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001555
1556 if (NumNegativeBits) {
1557 // If there is a negative value, figure out the smallest integer type (of
1558 // int/long/longlong) that fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001559 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001560 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001561 BestWidth = IntWidth;
1562 } else {
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001563 BestWidth =
1564 Context.Target.getLongWidth(Context.getFullLoc(Enum->getLocation()));
1565
Chris Lattner3a370bf2007-08-29 17:31:48 +00001566 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001567 BestType = Context.LongTy;
1568 else {
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001569 BestWidth = Context.Target.getLongLongWidth(
1570 Context.getFullLoc(Enum->getLocation()));
1571
Chris Lattner3a370bf2007-08-29 17:31:48 +00001572 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001573 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1574 BestType = Context.LongLongTy;
1575 }
1576 }
1577 } else {
1578 // If there is no negative value, figure out which of uint, ulong, ulonglong
1579 // fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001580 if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001581 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001582 BestWidth = IntWidth;
1583 } else if (NumPositiveBits <=
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001584 (BestWidth = Context.Target.getLongWidth(
1585 Context.getFullLoc(Enum->getLocation()))))
1586
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001587 BestType = Context.UnsignedLongTy;
1588 else {
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001589 BestWidth =
1590 Context.Target.getLongLongWidth(Context.getFullLoc(Enum->getLocation()));
1591
Chris Lattner3a370bf2007-08-29 17:31:48 +00001592 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001593 "How could an initializer get larger than ULL?");
1594 BestType = Context.UnsignedLongLongTy;
1595 }
1596 }
1597
Chris Lattner3a370bf2007-08-29 17:31:48 +00001598 // Loop over all of the enumerator constants, changing their types to match
1599 // the type of the enum if needed.
1600 for (unsigned i = 0; i != NumElements; ++i) {
1601 EnumConstantDecl *ECD =
1602 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1603 if (!ECD) continue; // Already issued a diagnostic.
1604
1605 // Standard C says the enumerators have int type, but we allow, as an
1606 // extension, the enumerators to be larger than int size. If each
1607 // enumerator value fits in an int, type it as an int, otherwise type it the
1608 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1609 // that X has type 'int', not 'unsigned'.
1610 if (ECD->getType() == Context.IntTy)
1611 continue; // Already int type.
1612
1613 // Determine whether the value fits into an int.
1614 llvm::APSInt InitVal = ECD->getInitVal();
1615 bool FitsInInt;
1616 if (InitVal.isUnsigned() || !InitVal.isNegative())
1617 FitsInInt = InitVal.getActiveBits() < IntWidth;
1618 else
1619 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1620
1621 // If it fits into an integer type, force it. Otherwise force it to match
1622 // the enum decl type.
1623 QualType NewTy;
1624 unsigned NewWidth;
1625 bool NewSign;
1626 if (FitsInInt) {
1627 NewTy = Context.IntTy;
1628 NewWidth = IntWidth;
1629 NewSign = true;
1630 } else if (ECD->getType() == BestType) {
1631 // Already the right type!
1632 continue;
1633 } else {
1634 NewTy = BestType;
1635 NewWidth = BestWidth;
1636 NewSign = BestType->isSignedIntegerType();
1637 }
1638
1639 // Adjust the APSInt value.
1640 InitVal.extOrTrunc(NewWidth);
1641 InitVal.setIsSigned(NewSign);
1642 ECD->setInitVal(InitVal);
1643
1644 // Adjust the Expr initializer and type.
1645 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1646 ECD->setType(NewTy);
1647 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001648
Chris Lattner1c1f9322007-08-28 18:24:31 +00001649 Enum->defineElements(EltList, BestType);
Chris Lattnerc1915e22007-01-25 07:29:02 +00001650}
Chris Lattner1300fb92007-01-23 23:42:53 +00001651
Steve Naroffa8fd9732007-06-11 00:35:03 +00001652void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
Anders Carlsson081f1b42007-12-19 06:16:30 +00001653 const char *attrName = rawAttr->getAttributeName()->getName();
1654 unsigned attrLen = rawAttr->getAttributeName()->getLength();
1655
Anders Carlsson2c26cc22007-12-19 17:43:24 +00001656 // Normalize the attribute name, __foo__ becomes foo.
1657 if (attrLen > 4 && attrName[0] == '_' && attrName[1] == '_' &&
1658 attrName[attrLen - 2] == '_' && attrName[attrLen - 1] == '_') {
1659 attrName += 2;
1660 attrLen -= 4;
1661 }
1662
1663 if (attrLen == 11 && !memcmp(attrName, "vector_size", 11)) {
Steve Naroffa8fd9732007-06-11 00:35:03 +00001664 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001665 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001666 if (!newType.isNull()) // install the new vector type into the decl
1667 vDecl->setType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001668 }
1669 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001670 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1671 rawAttr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001672 if (!newType.isNull()) // install the new vector type into the decl
1673 tDecl->setUnderlyingType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001674 }
Anders Carlsson2c26cc22007-12-19 17:43:24 +00001675 } else if (attrLen == 15 && !memcmp(attrName, "ocu_vector_type", 15)) {
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001676 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1677 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1678 else
Steve Naroff91fcddb2007-07-18 18:00:27 +00001679 Diag(rawAttr->getAttributeLoc(),
1680 diag::err_typecheck_ocu_vector_not_typedef);
Anders Carlsson721f6012007-12-19 07:19:40 +00001681 } else if (attrLen == 7 && !memcmp(attrName, "aligned", 7)) {
1682 HandleAlignedAttribute(New, rawAttr);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001683 }
Anders Carlsson721f6012007-12-19 07:19:40 +00001684
Steve Naroffa8fd9732007-06-11 00:35:03 +00001685 // FIXME: add other attributes...
1686}
1687
1688void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1689 AttributeList *declarator_postfix) {
1690 while (declspec_prefix) {
1691 HandleDeclAttribute(New, declspec_prefix);
1692 declspec_prefix = declspec_prefix->getNext();
1693 }
1694 while (declarator_postfix) {
1695 HandleDeclAttribute(New, declarator_postfix);
1696 declarator_postfix = declarator_postfix->getNext();
1697 }
1698}
1699
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001700void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1701 AttributeList *rawAttr) {
1702 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson721f6012007-12-19 07:19:40 +00001703 // check the attribute arguments.
Steve Naroff91fcddb2007-07-18 18:00:27 +00001704 if (rawAttr->getNumArgs() != 1) {
1705 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1706 std::string("1"));
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001707 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001708 }
1709 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1710 llvm::APSInt vecSize(32);
1711 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1712 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1713 sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001714 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001715 }
1716 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1717 // in conjunction with complex types (pointers, arrays, functions, etc.).
1718 Type *canonType = curType.getCanonicalType().getTypePtr();
1719 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1720 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1721 curType.getCanonicalType().getAsString());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001722 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001723 }
1724 // unlike gcc's vector_size attribute, the size is specified as the
1725 // number of elements, not the number of bytes.
Chris Lattner9cf21c52007-09-04 02:45:27 +00001726 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001727
1728 if (vectorSize == 0) {
1729 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1730 sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001731 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001732 }
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001733 // Instantiate/Install the vector type, the number of elements is > 0.
1734 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1735 // Remember this typedef decl, we will need it later for diagnostics.
1736 OCUVectorDecls.push_back(tDecl);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001737}
1738
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001739QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattner983a8bb2007-07-13 22:13:22 +00001740 AttributeList *rawAttr) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001741 // check the attribute arugments.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001742 if (rawAttr->getNumArgs() != 1) {
1743 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1744 std::string("1"));
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001745 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001746 }
1747 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
Chris Lattner23b7eb62007-06-15 23:05:46 +00001748 llvm::APSInt vecSize(32);
Chris Lattner0e9d6222007-07-15 23:26:56 +00001749 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Steve Naroffa8fd9732007-06-11 00:35:03 +00001750 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1751 sizeExpr->getSourceRange());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001752 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001753 }
1754 // navigate to the base type - we need to provide for vector pointers,
1755 // vector arrays, and functions returning vectors.
1756 Type *canonType = curType.getCanonicalType().getTypePtr();
1757
Steve Naroff91fcddb2007-07-18 18:00:27 +00001758 if (canonType->isPointerType() || canonType->isArrayType() ||
1759 canonType->isFunctionType()) {
Chris Lattner0f8a39c2007-12-19 05:38:06 +00001760 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff91fcddb2007-07-18 18:00:27 +00001761 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1762 do {
1763 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1764 canonType = PT->getPointeeType().getTypePtr();
1765 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1766 canonType = AT->getElementType().getTypePtr();
1767 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1768 canonType = FT->getResultType().getTypePtr();
1769 } while (canonType->isPointerType() || canonType->isArrayType() ||
1770 canonType->isFunctionType());
1771 */
Steve Naroffa8fd9732007-06-11 00:35:03 +00001772 }
1773 // the base type must be integer or float.
1774 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1775 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1776 curType.getCanonicalType().getAsString());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001777 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001778 }
Chris Lattner9cf21c52007-09-04 02:45:27 +00001779 unsigned typeSize = static_cast<unsigned>(
1780 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001781 // vecSize is specified in bytes - convert to bits.
Chris Lattner9cf21c52007-09-04 02:45:27 +00001782 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001783
1784 // the vector size needs to be an integral multiple of the type size.
1785 if (vectorSize % typeSize) {
1786 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1787 sizeExpr->getSourceRange());
1788 return QualType();
1789 }
1790 if (vectorSize == 0) {
1791 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1792 sizeExpr->getSourceRange());
1793 return QualType();
1794 }
1795 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1796 // the number of elements to be a power of two (unlike GCC).
1797 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff91fcddb2007-07-18 18:00:27 +00001798 return Context.getVectorType(curType, vectorSize/typeSize);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001799}
1800
Anders Carlsson721f6012007-12-19 07:19:40 +00001801void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
1802{
1803 // check the attribute arguments.
Anders Carlsson2c26cc22007-12-19 17:43:24 +00001804 // FIXME: Handle the case where are no arguments.
Anders Carlsson721f6012007-12-19 07:19:40 +00001805 if (rawAttr->getNumArgs() != 1) {
1806 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1807 std::string("1"));
1808 return;
1809 }
1810
1811 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
1812 llvm::APSInt alignment(32);
1813 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
1814 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1815 alignmentExpr->getSourceRange());
1816 return;
1817 }
1818}