blob: cc0682a8da5ae9918a61d002d09651000c6743fe [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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"
22#include "clang/Lex/IdentifierTable.h"
Chris Lattnerac18be92006-11-20 06:49:47 +000023#include "clang/Basic/LangOptions.h"
Chris Lattner9561a0b2007-01-28 08:20:04 +000024#include "clang/Basic/TargetInfo.h"
Chris Lattner38047f92007-01-27 06:24:01 +000025#include "llvm/ADT/SmallSet.h"
Chris Lattner697e5d62006-11-09 06:32:27 +000026using namespace clang;
27
Steve Naroffd57fa942007-08-30 22:35:45 +000028// C99 6.7.2.1p8: Used by ParseDeclarator/ParseField to make sure we have
29// a constant expression. We return true if we don't have a ConstantArrayType.
Chris Lattner6046e002007-06-05 06:39:23 +000030bool Sema::VerifyConstantArrayType(const ArrayType *Array,
31 SourceLocation DeclLoc) {
Steve Naroff5c131802007-08-30 01:06:46 +000032 if (const VariableArrayType *VLA = dyn_cast<VariableArrayType>(Array)) {
33 Expr *Size = VLA->getSizeExpr();
Steve Naroffd57fa942007-08-30 22:35:45 +000034 if (Size) {
Steve Naroff5c131802007-08-30 01:06:46 +000035 // FIXME: This emits the diagnostic to enforce 6.7.2.1p8, but the message
36 // is wrong. It is also wrong for static variables.
37 // FIXME: This is also wrong for:
38 // int sub1(int i, char *pi) { typedef int foo[i];
39 // struct bar {foo f1; int f2:3; int f3:4} *p; }
40 Diag(DeclLoc, diag::err_typecheck_illegal_vla, Size->getSourceRange());
Steve Naroff5c131802007-08-30 01:06:46 +000041 }
Chris Lattner6046e002007-06-05 06:39:23 +000042 return true;
Steve Naroff8eeeb132007-05-08 21:09:37 +000043 }
Chris Lattner6046e002007-06-05 06:39:23 +000044 return false;
Steve Naroff8eeeb132007-05-08 21:09:37 +000045}
Chris Lattnere168f762006-11-10 05:29:30 +000046
Chris Lattner2ebe4bb2006-11-20 01:29:42 +000047Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Chris Lattner32d920b2007-01-26 02:01:53 +000048 return dyn_cast_or_null<TypedefDecl>(II.getFETokenInfo<Decl>());
Chris Lattnere168f762006-11-10 05:29:30 +000049}
50
Chris Lattner302b4be2006-11-19 02:31:38 +000051void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +000052 if (S->decl_empty()) return;
53 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
54
Chris Lattner302b4be2006-11-19 02:31:38 +000055 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
56 I != E; ++I) {
Chris Lattner99d31772007-01-21 22:37:37 +000057 Decl *D = static_cast<Decl*>(*I);
Chris Lattner302b4be2006-11-19 02:31:38 +000058 assert(D && "This decl didn't get pushed??");
Chris Lattnerff65b6b2007-01-23 01:33:16 +000059 IdentifierInfo *II = D->getIdentifier();
60 if (!II) continue;
Chris Lattner302b4be2006-11-19 02:31:38 +000061
Chris Lattnerff65b6b2007-01-23 01:33:16 +000062 // Unlink this decl from the identifier. Because the scope contains decls
63 // in an unordered collection, and because we have multiple identifier
64 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
65 if (II->getFETokenInfo<Decl>() == D) {
66 // Normal case, no multiple decls in different namespaces.
67 II->setFETokenInfo(D->getNext());
68 } else {
69 // Scan ahead. There are only three namespaces in C, so this loop can
70 // never execute more than 3 times.
71 Decl *SomeDecl = II->getFETokenInfo<Decl>();
72 while (SomeDecl->getNext() != D) {
73 SomeDecl = SomeDecl->getNext();
74 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
75 }
76 SomeDecl->setNext(D->getNext());
77 }
Chris Lattner302b4be2006-11-19 02:31:38 +000078
Chris Lattner740b2f32006-11-21 01:32:20 +000079 // This will have to be revisited for C++: there we want to nest stuff in
80 // namespace decls etc. Even for C, we might want a top-level translation
81 // unit decl or something.
82 if (!CurFunctionDecl)
83 continue;
84
85 // Chain this decl to the containing function, it now owns the memory for
86 // the decl.
87 D->setNext(CurFunctionDecl->getDeclChain());
88 CurFunctionDecl->setDeclChain(D);
Chris Lattner302b4be2006-11-19 02:31:38 +000089 }
90}
91
Chris Lattner18b19622007-01-22 07:39:13 +000092/// LookupScopedDecl - Look up the inner-most declaration in the specified
93/// namespace.
Chris Lattner9561a0b2007-01-28 08:20:04 +000094Decl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
95 SourceLocation IdLoc, Scope *S) {
Chris Lattner18b19622007-01-22 07:39:13 +000096 if (II == 0) return 0;
Chris Lattnerb6738ec2007-01-28 00:38:24 +000097 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
Chris Lattner18b19622007-01-22 07:39:13 +000098
99 // Scan up the scope chain looking for a decl that matches this identifier
100 // that is in the appropriate namespace. This search should not take long, as
101 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
102 for (Decl *D = II->getFETokenInfo<Decl>(); D; D = D->getNext())
103 if (D->getIdentifierNamespace() == NS)
104 return D;
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000105
Chris Lattner9561a0b2007-01-28 08:20:04 +0000106 // If we didn't find a use of this identifier, and if the identifier
107 // corresponds to a compiler builtin, create the decl object for the builtin
108 // now, injecting it into translation unit scope, and return it.
109 if (NS == Decl::IDNS_Ordinary) {
110 // If this is a builtin on some other target, or if this builtin varies
111 // across targets (e.g. in type), emit a diagnostic and mark the translation
112 // unit non-portable for using it.
113 if (II->isNonPortableBuiltin()) {
114 // Only emit this diagnostic once for this builtin.
115 II->setNonPortableBuiltin(false);
116 Context.Target.DiagnoseNonPortability(IdLoc,
117 diag::port_target_builtin_use);
118 }
Chris Lattner9561a0b2007-01-28 08:20:04 +0000119 // If this is a builtin on this (or all) targets, create the decl.
120 if (unsigned BuiltinID = II->getBuiltinID())
121 return LazilyCreateBuiltin(II, BuiltinID, S);
122 }
Chris Lattner18b19622007-01-22 07:39:13 +0000123 return 0;
124}
125
Chris Lattner9561a0b2007-01-28 08:20:04 +0000126/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
127/// lazily create a decl for it.
128Decl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
129 Builtin::ID BID = (Builtin::ID)bid;
130
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000131 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner776fac82007-06-09 00:53:06 +0000132 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattnerb677a932007-08-26 04:02:13 +0000133 FunctionDecl::Extern, false, 0);
Chris Lattner9561a0b2007-01-28 08:20:04 +0000134
135 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000136 if (Scope *FnS = S->getFnParent())
137 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner9561a0b2007-01-28 08:20:04 +0000138 while (S->getParent())
139 S = S->getParent();
140 S->AddDecl(New);
141
142 // Add this decl to the end of the identifier info.
143 if (Decl *LastDecl = II->getFETokenInfo<Decl>()) {
144 // Scan until we find the last (outermost) decl in the id chain.
145 while (LastDecl->getNext())
146 LastDecl = LastDecl->getNext();
147 // Insert before (outside) it.
148 LastDecl->setNext(New);
149 } else {
150 II->setFETokenInfo(New);
151 }
152 // Make sure clients iterating over decls see this.
153 LastInGroupList.push_back(New);
154
155 return New;
156}
157
Chris Lattner01564d92007-01-27 19:27:06 +0000158/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
159/// and scope as a previous declaration 'Old'. Figure out how to resolve this
160/// situation, merging decls or emitting diagnostics as appropriate.
161///
Chris Lattnerc511efb2007-01-27 19:32:14 +0000162TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
163 // Verify the old decl was also a typedef.
164 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
165 if (!Old) {
166 Diag(New->getLocation(), diag::err_redefinition_different_kind,
167 New->getName());
168 Diag(OldD->getLocation(), diag::err_previous_definition);
169 return New;
170 }
171
Chris Lattner01564d92007-01-27 19:27:06 +0000172 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
173 // TODO: This is totally simplistic. It should handle merging functions
174 // together etc, merging extern int X; int X; ...
175 Diag(New->getLocation(), diag::err_redefinition, New->getName());
176 Diag(Old->getLocation(), diag::err_previous_definition);
177 return New;
178}
179
180/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
181/// and scope as a previous declaration 'Old'. Figure out how to resolve this
182/// situation, merging decls or emitting diagnostics as appropriate.
183///
Chris Lattnerc511efb2007-01-27 19:32:14 +0000184FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
185 // Verify the old decl was also a function.
186 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
187 if (!Old) {
188 Diag(New->getLocation(), diag::err_redefinition_different_kind,
189 New->getName());
190 Diag(OldD->getLocation(), diag::err_previous_definition);
191 return New;
192 }
193
Chris Lattnerefe4aea2007-01-27 19:35:39 +0000194 // This is not right, but it's a start. If 'Old' is a function prototype with
195 // the same type as 'New', silently allow this. FIXME: We should link up decl
196 // objects here.
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000197 if (Old->getBody() == 0 &&
198 Old->getCanonicalType() == New->getCanonicalType()) {
Chris Lattnerefe4aea2007-01-27 19:35:39 +0000199 return New;
200 }
Chris Lattnerc511efb2007-01-27 19:32:14 +0000201
Chris Lattner01564d92007-01-27 19:27:06 +0000202 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
203 // TODO: This is totally simplistic. It should handle merging functions
204 // together etc, merging extern int X; int X; ...
205 Diag(New->getLocation(), diag::err_redefinition, New->getName());
206 Diag(Old->getLocation(), diag::err_previous_definition);
207 return New;
208}
209
210/// MergeVarDecl - We just parsed a variable 'New' which has the same name
211/// and scope as a previous declaration 'Old'. Figure out how to resolve this
212/// situation, merging decls or emitting diagnostics as appropriate.
213///
Steve Narofffc49d672007-04-01 21:27:45 +0000214/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
215/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
216///
Chris Lattnerc511efb2007-01-27 19:32:14 +0000217VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
218 // Verify the old decl was also a variable.
219 VarDecl *Old = dyn_cast<VarDecl>(OldD);
220 if (!Old) {
221 Diag(New->getLocation(), diag::err_redefinition_different_kind,
222 New->getName());
223 Diag(OldD->getLocation(), diag::err_previous_definition);
224 return New;
225 }
Steve Naroff5c131802007-08-30 01:06:46 +0000226 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
227 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
228 bool OldIsTentative = false;
229
230 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
231 // Handle C "tentative" external object definitions. FIXME: finish!
232 if (!OldFSDecl->getInit() &&
233 (OldFSDecl->getStorageClass() == VarDecl::None ||
234 OldFSDecl->getStorageClass() == VarDecl::Static))
235 OldIsTentative = true;
236 }
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000237 // Verify the types match.
238 if (Old->getCanonicalType() != New->getCanonicalType()) {
239 Diag(New->getLocation(), diag::err_redefinition, New->getName());
240 Diag(Old->getLocation(), diag::err_previous_definition);
241 return New;
242 }
243 // We've verified the types match, now check if Old is "extern".
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000244 if (Old->getStorageClass() != VarDecl::Extern) {
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000245 Diag(New->getLocation(), diag::err_redefinition, New->getName());
246 Diag(Old->getLocation(), diag::err_previous_definition);
247 }
Chris Lattner01564d92007-01-27 19:27:06 +0000248 return New;
249}
250
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000251/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
252/// no declarator (e.g. "struct foo;") is parsed.
253Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
254 // TODO: emit error on 'int;' or 'const enum foo;'.
255 // TODO: emit error on 'typedef int;'
256 // if (!DS.isMissingDeclaratorOk()) Diag(...);
257
258 return 0;
259}
260
Chris Lattner776fac82007-06-09 00:53:06 +0000261Sema::DeclTy *
Chris Lattner79c57592007-07-12 00:36:32 +0000262Sema::ParseDeclarator(Scope *S, Declarator &D, ExprTy *init,
Chris Lattner776fac82007-06-09 00:53:06 +0000263 DeclTy *lastDeclarator) {
264 Decl *LastDeclarator = (Decl*)lastDeclarator;
Chris Lattner79c57592007-07-12 00:36:32 +0000265 Expr *Init = static_cast<Expr*>(init);
Chris Lattnere168f762006-11-10 05:29:30 +0000266 IdentifierInfo *II = D.getIdentifier();
Chris Lattner302b4be2006-11-19 02:31:38 +0000267
Chris Lattner02c04392007-07-25 00:24:17 +0000268 // All of these full declarators require an identifier. If it doesn't have
269 // one, the ParsedFreeStandingDeclSpec action should be used.
270 if (II == 0) {
Chris Lattnerc4f6d0c2007-08-28 06:17:15 +0000271 Diag(D.getDeclSpec().getSourceRange().Begin(),
272 diag::err_declarator_need_ident,
Chris Lattner02c04392007-07-25 00:24:17 +0000273 D.getDeclSpec().getSourceRange(), D.getSourceRange());
274 return 0;
275 }
276
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000277 // The scope passed in may not be a decl scope. Zip up the scope tree until
278 // we find one that is.
279 while ((S->getFlags() & Scope::DeclScope) == 0)
280 S = S->getParent();
281
Chris Lattner01564d92007-01-27 19:27:06 +0000282 // See if this is a redefinition of a variable in the same scope.
Chris Lattner9561a0b2007-01-28 08:20:04 +0000283 Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
284 D.getIdentifierLoc(), S);
Chris Lattner776fac82007-06-09 00:53:06 +0000285 if (PrevDecl && !S->isDeclScope(PrevDecl))
Chris Lattner01564d92007-01-27 19:27:06 +0000286 PrevDecl = 0; // If in outer scope, it isn't the same thing.
287
Chris Lattnere168f762006-11-10 05:29:30 +0000288 Decl *New;
Steve Narofff93b6722007-08-28 20:14:24 +0000289 bool InvalidDecl = false;
290
Chris Lattner01a7c532007-01-25 23:09:03 +0000291 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner79c57592007-07-12 00:36:32 +0000292 assert(Init == 0 && "Can't have initializer for a typedef!");
Chris Lattner776fac82007-06-09 00:53:06 +0000293 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
Chris Lattner01564d92007-01-27 19:27:06 +0000294 if (!NewTD) return 0;
Steve Naroffa8fd9732007-06-11 00:35:03 +0000295
296 // Handle attributes prior to checking for duplicates in MergeVarDecl
297 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
298 D.getAttributes());
Chris Lattner01564d92007-01-27 19:27:06 +0000299 // Merge the decl with the existing one if appropriate.
300 if (PrevDecl) {
301 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
302 if (NewTD == 0) return 0;
303 }
304 New = NewTD;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000305 if (S->getParent() == 0) {
306 // C99 6.7.7p2: If a typedef name specifies a variably modified type
307 // then it shall have block scope.
308 if (ArrayType *ary = dyn_cast<ArrayType>(NewTD->getUnderlyingType())) {
Chris Lattner6046e002007-06-05 06:39:23 +0000309 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
Steve Narofff93b6722007-08-28 20:14:24 +0000310 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000311 }
312 }
Chris Lattner01a7c532007-01-25 23:09:03 +0000313 } else if (D.isFunctionDeclarator()) {
Chris Lattner79c57592007-07-12 00:36:32 +0000314 assert(Init == 0 && "Can't have an initializer for a functiondecl!");
Steve Narofff93b6722007-08-28 20:14:24 +0000315
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000316 QualType R = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +0000317 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff7a5af782007-07-13 16:58:59 +0000318
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000319 FunctionDecl::StorageClass SC;
320 switch (D.getDeclSpec().getStorageClassSpec()) {
321 default: assert(0 && "Unknown storage class!");
322 case DeclSpec::SCS_auto:
323 case DeclSpec::SCS_register:
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000324 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
325 R.getAsString());
Steve Narofff93b6722007-08-28 20:14:24 +0000326 InvalidDecl = true;
327 break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000328 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
329 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
330 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
331 }
332
Chris Lattner776fac82007-06-09 00:53:06 +0000333 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattnerb677a932007-08-26 04:02:13 +0000334 D.getDeclSpec().isInlineSpecified(),
Chris Lattner776fac82007-06-09 00:53:06 +0000335 LastDeclarator);
Chris Lattner01564d92007-01-27 19:27:06 +0000336
337 // Merge the decl with the existing one if appropriate.
338 if (PrevDecl) {
339 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
340 if (NewFD == 0) return 0;
341 }
342 New = NewFD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000343 } else {
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000344 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffcf871f52007-08-28 18:45:29 +0000345 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner01564d92007-01-27 19:27:06 +0000346
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000347 VarDecl *NewVD;
348 VarDecl::StorageClass SC;
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000349 switch (D.getDeclSpec().getStorageClassSpec()) {
350 default: assert(0 && "Unknown storage class!");
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000351 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
352 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
353 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
354 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
355 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
356 }
Steve Narofffc49d672007-04-01 21:27:45 +0000357 if (S->getParent() == 0) {
358 // File scope. C99 6.9.2p2: A declaration of an identifier for and
359 // object that has file scope without an initializer, and without a
360 // storage-class specifier or with the storage-class specifier "static",
361 // constitutes a tentative definition. Note: A tentative definition with
362 // external linkage is valid (C99 6.2.2p5).
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000363 if (!Init && SC == VarDecl::Static) {
Steve Narofffc49d672007-04-01 21:27:45 +0000364 // C99 6.9.2p3: If the declaration of an identifier for an object is
365 // a tentative definition and has internal linkage (C99 6.2.2p3), the
366 // declared type shall not be an incomplete type.
367 if (R->isIncompleteType()) {
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000368 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
369 R.getAsString());
Steve Naroffcf871f52007-08-28 18:45:29 +0000370 InvalidDecl = true;
Steve Narofffc49d672007-04-01 21:27:45 +0000371 }
Steve Naroffca8f7122007-04-01 01:41:35 +0000372 }
Bill Wendlingd6de6572007-06-02 09:40:07 +0000373 // C99 6.9p2: The storage-class specifiers auto and register shall not
374 // appear in the declaration specifiers in an external declaration.
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000375 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000376 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
377 R.getAsString());
Steve Naroffcf871f52007-08-28 18:45:29 +0000378 InvalidDecl = true;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000379 }
Steve Naroff8eeeb132007-05-08 21:09:37 +0000380 // C99 6.7.5.2p2: If an identifier is declared to be an object with
381 // static storage duration, it shall not have a variable length array.
Chris Lattner0fd893e2007-07-31 21:33:24 +0000382 if (const ArrayType *ary = R->getAsArrayType()) {
Chris Lattner6046e002007-06-05 06:39:23 +0000383 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
Steve Naroffcf871f52007-08-28 18:45:29 +0000384 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000385 }
Chris Lattner776fac82007-06-09 00:53:06 +0000386 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofffc49d672007-04-01 21:27:45 +0000387 } else {
388 // Block scope. C99 6.7p7: If an identifier for an object is declared with
389 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000390 if (SC != VarDecl::Extern) {
Steve Narofffc49d672007-04-01 21:27:45 +0000391 if (R->isIncompleteType()) {
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000392 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
393 R.getAsString());
Steve Naroffcf871f52007-08-28 18:45:29 +0000394 InvalidDecl = true;
Steve Narofffc49d672007-04-01 21:27:45 +0000395 }
396 }
Steve Naroff8eeeb132007-05-08 21:09:37 +0000397 if (SC == VarDecl::Static) {
398 // C99 6.7.5.2p2: If an identifier is declared to be an object with
399 // static storage duration, it shall not have a variable length array.
Chris Lattner0fd893e2007-07-31 21:33:24 +0000400 if (const ArrayType *ary = R->getAsArrayType()) {
Chris Lattner6046e002007-06-05 06:39:23 +0000401 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
Steve Naroffcf871f52007-08-28 18:45:29 +0000402 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000403 }
404 }
Chris Lattner776fac82007-06-09 00:53:06 +0000405 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcf871f52007-08-28 18:45:29 +0000406 }
Steve Naroffa8fd9732007-06-11 00:35:03 +0000407 // Handle attributes prior to checking for duplicates in MergeVarDecl
408 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
409 D.getAttributes());
410
Chris Lattner01564d92007-01-27 19:27:06 +0000411 // Merge the decl with the existing one if appropriate.
412 if (PrevDecl) {
413 NewVD = MergeVarDecl(NewVD, PrevDecl);
414 if (NewVD == 0) return 0;
415 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +0000416 if (Init) {
417 AssignmentCheckResult result;
418 result = CheckSingleAssignmentConstraints(R, Init);
419 // FIXME: emit errors if appropriate.
420 NewVD->setInit(Init);
421 }
Chris Lattner01564d92007-01-27 19:27:06 +0000422 New = NewVD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000423 }
Chris Lattner302b4be2006-11-19 02:31:38 +0000424
Chris Lattnere168f762006-11-10 05:29:30 +0000425 // If this has an identifier, add it to the scope stack.
426 if (II) {
Chris Lattner18b19622007-01-22 07:39:13 +0000427 New->setNext(II->getFETokenInfo<Decl>());
Chris Lattnere168f762006-11-10 05:29:30 +0000428 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000429 S->AddDecl(New);
Chris Lattnere168f762006-11-10 05:29:30 +0000430 }
431
Steve Naroff26c8ea52007-03-21 21:08:52 +0000432 if (S->getParent() == 0)
Chris Lattner776fac82007-06-09 00:53:06 +0000433 AddTopLevelDecl(New, LastDeclarator);
Steve Narofff93b6722007-08-28 20:14:24 +0000434
435 // If any semantic error occurred, mark the decl as invalid.
436 if (D.getInvalidType() || InvalidDecl)
437 New->setInvalidDecl();
Chris Lattnere168f762006-11-10 05:29:30 +0000438
439 return New;
440}
441
Chris Lattner776fac82007-06-09 00:53:06 +0000442/// The declarators are chained together backwards, reverse the list.
443Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
444 // Often we have single declarators, handle them quickly.
445 Decl *Group = static_cast<Decl*>(group);
Chris Lattnerb2dd2412007-06-09 06:16:32 +0000446 if (Group == 0 || Group->getNextDeclarator() == 0) return Group;
Chris Lattner776fac82007-06-09 00:53:06 +0000447
448 Decl *NewGroup = 0;
449 while (Group) {
450 Decl *Next = Group->getNextDeclarator();
451 Group->setNextDeclarator(NewGroup);
452 NewGroup = Group;
453 Group = Next;
454 }
455 return NewGroup;
456}
Steve Naroff7e6f7c22007-08-28 03:03:08 +0000457
458// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner53621a52007-06-13 20:44:40 +0000459ParmVarDecl *
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000460Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
461 Scope *FnScope) {
462 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
Chris Lattner200bdc32006-11-19 02:43:37 +0000463
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000464 IdentifierInfo *II = PI.Ident;
Chris Lattnerc284e9b2007-01-23 05:14:32 +0000465 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
466 // Can this happen for params? We already checked that they don't conflict
467 // among each other. Here they can only shadow globals, which is ok.
Chris Lattnerd2b88ab2007-07-13 03:05:23 +0000468 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Chris Lattner9561a0b2007-01-28 08:20:04 +0000469 PI.IdentLoc, FnScope)) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000470
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000471 }
472
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000473 // FIXME: Handle storage class (auto, register). No declarator?
Chris Lattner776fac82007-06-09 00:53:06 +0000474 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff773df5c2007-08-07 22:44:21 +0000475
476 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
477 // Doing the promotion here has a win and a loss. The win is the type for
478 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
479 // code generator). The loss is the orginal type isn't preserved. For example:
480 //
481 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
482 // int blockvardecl[5];
483 // sizeof(parmvardecl); // size == 4
484 // sizeof(blockvardecl); // size == 20
485 // }
486 //
487 // For expressions, all implicit conversions are captured using the
488 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
489 //
490 // FIXME: If a source translation tool needs to see the original type, then
491 // we need to consider storing both types (in ParmVarDecl)...
492 //
493 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
494 if (const ArrayType *AT = parmDeclType->getAsArrayType())
495 parmDeclType = Context.getPointerType(AT->getElementType());
496 else if (parmDeclType->isFunctionType())
497 parmDeclType = Context.getPointerType(parmDeclType);
498
499 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffcf871f52007-08-28 18:45:29 +0000500 VarDecl::None, 0);
501 if (PI.InvalidType)
502 New->setInvalidDecl();
503
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000504 // If this has an identifier, add it to the scope stack.
505 if (II) {
Chris Lattner18b19622007-01-22 07:39:13 +0000506 New->setNext(II->getFETokenInfo<Decl>());
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000507 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000508 FnScope->AddDecl(New);
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000509 }
Chris Lattner229ce602006-11-21 01:21:07 +0000510
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000511 return New;
512}
513
514
515Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner229ce602006-11-21 01:21:07 +0000516 assert(CurFunctionDecl == 0 && "Function parsing confused");
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000517 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
518 "Not a function declarator!");
519 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
520
521 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
522 // for a K&R function.
523 if (!FTI.hasPrototype) {
524 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
525 if (FTI.ArgInfo[i].TypeInfo == 0) {
Chris Lattner843c5922007-06-10 23:40:34 +0000526 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000527 FTI.ArgInfo[i].Ident->getName());
528 // Implicitly declare the argument as type 'int' for lack of a better
529 // type.
530 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
531 }
532 }
533
534 // Since this is a function definition, act as though we have information
535 // about the arguments.
536 FTI.hasPrototype = true;
Chris Lattner2114d5e2006-12-04 07:40:24 +0000537 } else {
538 // FIXME: Diagnose arguments without names in C.
539
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000540 }
541
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000542 Scope *GlobalScope = FnBodyScope->getParent();
543
544 FunctionDecl *FD =
545 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0, 0));
Chris Lattner229ce602006-11-21 01:21:07 +0000546 CurFunctionDecl = FD;
Chris Lattner2114d5e2006-12-04 07:40:24 +0000547
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000548 // Create Decl objects for each parameter, adding them to the FunctionDecl.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000549 llvm::SmallVector<ParmVarDecl*, 16> Params;
Chris Lattnerf61c8a82007-01-21 19:04:43 +0000550
551 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
552 // no arguments, not a function that takes a single void argument.
553 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
554 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
Chris Lattner99d31772007-01-21 22:37:37 +0000555 // empty arg list, don't push any params.
Chris Lattnerf61c8a82007-01-21 19:04:43 +0000556 } else {
557 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
558 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
559 }
Chris Lattner2114d5e2006-12-04 07:40:24 +0000560
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000561 FD->setParams(&Params[0], Params.size());
Chris Lattner2114d5e2006-12-04 07:40:24 +0000562
Chris Lattnere168f762006-11-10 05:29:30 +0000563 return FD;
564}
565
Chris Lattner229ce602006-11-21 01:21:07 +0000566Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
567 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
568 FD->setBody((Stmt*)Body);
569
570 assert(FD == CurFunctionDecl && "Function parsing confused");
571 CurFunctionDecl = 0;
Chris Lattnere2473062007-05-28 06:28:18 +0000572
573 // Verify and clean out per-function state.
574
575 // Check goto/label use.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000576 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
577 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
Chris Lattnere2473062007-05-28 06:28:18 +0000578 // Verify that we have no forward references left. If so, there was a goto
579 // or address of a label taken, but no definition of it. Label fwd
580 // definitions are indicated with a null substmt.
581 if (I->second->getSubStmt() == 0) {
582 LabelStmt *L = I->second;
583 // Emit error.
Chris Lattnereefa10e2007-05-28 06:56:27 +0000584 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
Chris Lattnere2473062007-05-28 06:28:18 +0000585
586 // At this point, we have gotos that use the bogus label. Stitch it into
587 // the function body so that they aren't leaked and that the AST is well
588 // formed.
589 L->setSubStmt(new NullStmt(L->getIdentLoc()));
590 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
591 }
592 }
593 LabelMap.clear();
594
Chris Lattner229ce602006-11-21 01:21:07 +0000595 return FD;
596}
597
598
Chris Lattnerac18be92006-11-20 06:49:47 +0000599/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
600/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
601Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
602 Scope *S) {
603 if (getLangOptions().C99) // Extension in C99.
604 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
605 else // Legal in C90, but warn about it.
606 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
607
608 // FIXME: handle stuff like:
609 // void foo() { extern float X(); }
610 // void bar() { X(); } <-- implicit decl for X in another scope.
611
612 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +0000613 const char *Dummy;
Chris Lattnerac18be92006-11-20 06:49:47 +0000614 DeclSpec DS;
Chris Lattnerb20e8942006-11-28 05:30:29 +0000615 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
Chris Lattnerb055f2d2007-02-11 08:19:57 +0000616 Error = Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +0000617 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +0000618 Declarator D(DS, Declarator::BlockContext);
Chris Lattnercbc426d2006-12-02 06:43:02 +0000619 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
Chris Lattnerac18be92006-11-20 06:49:47 +0000620 D.SetIdentifier(&II, Loc);
621
Chris Lattner62d2e662007-01-28 00:21:37 +0000622 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000623 if (Scope *FnS = S->getFnParent())
624 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner62d2e662007-01-28 00:21:37 +0000625 while (S->getParent())
626 S = S->getParent();
Chris Lattnerac18be92006-11-20 06:49:47 +0000627
Chris Lattner62d2e662007-01-28 00:21:37 +0000628 return static_cast<Decl*>(ParseDeclarator(S, D, 0, 0));
Chris Lattnerac18be92006-11-20 06:49:47 +0000629}
630
Chris Lattner302b4be2006-11-19 02:31:38 +0000631
Chris Lattner776fac82007-06-09 00:53:06 +0000632TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
633 Decl *LastDeclarator) {
634 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Chris Lattner302b4be2006-11-19 02:31:38 +0000635
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000636 QualType T = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +0000637 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner0d8b1a12006-11-20 04:34:45 +0000638
Chris Lattner18b19622007-01-22 07:39:13 +0000639 // Scope manipulation handled by caller.
Steve Narofff93b6722007-08-28 20:14:24 +0000640 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
641 T, LastDeclarator);
642 if (D.getInvalidType())
643 NewTD->setInvalidDecl();
644 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +0000645}
646
Chris Lattner18b19622007-01-22 07:39:13 +0000647
Chris Lattner1300fb92007-01-23 23:42:53 +0000648/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
649/// former case, Name will be non-null. In the later case, Name will be null.
650/// TagType indicates what kind of tag this is. TK indicates whether this is a
651/// reference/declaration/definition of a tag.
Chris Lattner7b9ace62007-01-23 20:11:08 +0000652Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000653 SourceLocation KWLoc, IdentifierInfo *Name,
Steve Naroffb3096442007-06-09 03:47:53 +0000654 SourceLocation NameLoc, AttributeList *Attr) {
Chris Lattner8799cf22007-01-23 01:57:16 +0000655 // If this is a use of an existing tag, it must have a name.
Chris Lattner7b9ace62007-01-23 20:11:08 +0000656 assert((Name != 0 || TK == TK_Definition) &&
657 "Nameless record must be a definition!");
Chris Lattner8799cf22007-01-23 01:57:16 +0000658
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000659 Decl::Kind Kind;
Chris Lattnerbf0b7982007-01-23 04:27:41 +0000660 switch (TagType) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000661 default: assert(0 && "Unknown tag type!");
Chris Lattnerbf0b7982007-01-23 04:27:41 +0000662 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
663 case DeclSpec::TST_union: Kind = Decl::Union; break;
664//case DeclSpec::TST_class: Kind = Decl::Class; break;
665 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000666 }
Chris Lattner7e783a12007-01-23 02:05:42 +0000667
Chris Lattner18b19622007-01-22 07:39:13 +0000668 // If this is a named struct, check to see if there was a previous forward
669 // declaration or definition.
Chris Lattner7b9ace62007-01-23 20:11:08 +0000670 if (TagDecl *PrevDecl =
Chris Lattner9561a0b2007-01-28 08:20:04 +0000671 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
672 NameLoc, S))) {
Chris Lattner8799cf22007-01-23 01:57:16 +0000673
674 // If this is a use of a previous tag, or if the tag is already declared in
675 // the same scope (so that the definition/declaration completes or
676 // rementions the tag), reuse the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +0000677 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
Chris Lattner7e783a12007-01-23 02:05:42 +0000678 // Make sure that this wasn't declared as an enum and now used as a struct
679 // or something similar.
680 if (PrevDecl->getKind() != Kind) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000681 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
Chris Lattner7e783a12007-01-23 02:05:42 +0000682 Diag(PrevDecl->getLocation(), diag::err_previous_use);
683 }
Chris Lattner7b9ace62007-01-23 20:11:08 +0000684
685 // If this is a use or a forward declaration, we're good.
686 if (TK != TK_Definition)
687 return PrevDecl;
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000688
Chris Lattner7b9ace62007-01-23 20:11:08 +0000689 // Diagnose attempts to redefine a tag.
690 if (PrevDecl->isDefinition()) {
691 Diag(NameLoc, diag::err_redefinition, Name->getName());
692 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
693 // If this is a redefinition, recover by making this struct be
694 // anonymous, which will make any later references get the previous
695 // definition.
696 Name = 0;
697 } else {
698 // Okay, this is definition of a previously declared or referenced tag.
699 // Move the location of the decl to be the definition site.
700 PrevDecl->setLocation(NameLoc);
Chris Lattner7b9ace62007-01-23 20:11:08 +0000701 return PrevDecl;
702 }
Chris Lattner8799cf22007-01-23 01:57:16 +0000703 }
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000704 // If we get here, this is a definition of a new struct type in a nested
705 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
706 // type.
Chris Lattner18b19622007-01-22 07:39:13 +0000707 }
708
Chris Lattnerbf0b7982007-01-23 04:27:41 +0000709 // If there is an identifier, use the location of the identifier as the
710 // location of the decl, otherwise use the location of the struct/union
711 // keyword.
712 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
713
Chris Lattner18b19622007-01-22 07:39:13 +0000714 // Otherwise, if this is the first time we've seen this tag, create the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +0000715 TagDecl *New;
Chris Lattner720a0542007-01-25 00:44:24 +0000716 switch (Kind) {
717 default: assert(0 && "Unknown tag kind!");
Chris Lattner5f521502007-01-25 06:27:24 +0000718 case Decl::Enum:
Chris Lattner776fac82007-06-09 00:53:06 +0000719 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
720 // enum X { A, B, C } D; D should chain to X.
721 New = new EnumDecl(Loc, Name, 0);
Chris Lattner5f521502007-01-25 06:27:24 +0000722 // If this is an undefined enum, warn.
Chris Lattnerc1915e22007-01-25 07:29:02 +0000723 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Chris Lattner5f521502007-01-25 06:27:24 +0000724 break;
Chris Lattner720a0542007-01-25 00:44:24 +0000725 case Decl::Union:
726 case Decl::Struct:
727 case Decl::Class:
Chris Lattner776fac82007-06-09 00:53:06 +0000728 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
729 // struct X { int A; } D; D should chain to X.
730 New = new RecordDecl(Kind, Loc, Name, 0);
Chris Lattner720a0542007-01-25 00:44:24 +0000731 break;
732 }
Chris Lattner18b19622007-01-22 07:39:13 +0000733
734 // If this has an identifier, add it to the scope stack.
735 if (Name) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000736 // The scope passed in may not be a decl scope. Zip up the scope tree until
737 // we find one that is.
738 while ((S->getFlags() & Scope::DeclScope) == 0)
739 S = S->getParent();
740
741 // Add it to the decl chain.
Chris Lattner18b19622007-01-22 07:39:13 +0000742 New->setNext(Name->getFETokenInfo<Decl>());
743 Name->setFETokenInfo(New);
744 S->AddDecl(New);
745 }
746
747 return New;
748}
Chris Lattner1300fb92007-01-23 23:42:53 +0000749
750/// ParseField - Each field of a struct/union/class is passed into this in order
751/// to create a FieldDecl object for it.
752Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
753 SourceLocation DeclStart,
754 Declarator &D, ExprTy *BitfieldWidth) {
755 IdentifierInfo *II = D.getIdentifier();
756 Expr *BitWidth = (Expr*)BitfieldWidth;
757
758 SourceLocation Loc = DeclStart;
759 if (II) Loc = D.getIdentifierLoc();
760
Chris Lattner62d2e662007-01-28 00:21:37 +0000761 // FIXME: Unnamed fields can be handled in various different ways, for
762 // example, unnamed unions inject all members into the struct namespace!
763
764
Chris Lattner1300fb92007-01-23 23:42:53 +0000765 if (BitWidth) {
766 // TODO: Validate.
Steve Narofff84d11f2007-05-23 21:48:04 +0000767 //printf("WARNING: BITFIELDS IGNORED!\n");
Chris Lattner1300fb92007-01-23 23:42:53 +0000768
769 // 6.7.2.1p3
770 // 6.7.2.1p4
771
772 } else {
773 // Not a bitfield.
774
775 // validate II.
776
777 }
778
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000779 QualType T = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +0000780 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
781 bool InvalidDecl = false;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000782
783 // C99 6.7.2.1p8: A member of a structure or union may have any type other
784 // than a variably modified type.
Chris Lattner0fd893e2007-07-31 21:33:24 +0000785 if (const ArrayType *ary = T->getAsArrayType()) {
Chris Lattner6046e002007-06-05 06:39:23 +0000786 if (VerifyConstantArrayType(ary, Loc))
Steve Narofff93b6722007-08-28 20:14:24 +0000787 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000788 }
Chris Lattner776fac82007-06-09 00:53:06 +0000789
790 // FIXME: Chain fielddecls together.
Steve Narofff93b6722007-08-28 20:14:24 +0000791 FieldDecl *NewFD = new FieldDecl(Loc, II, T, 0);
792 if (D.getInvalidType() || InvalidDecl)
793 NewFD->setInvalidDecl();
794 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +0000795}
796
797void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
798 DeclTy **Fields, unsigned NumFields) {
Chris Lattnerc1915e22007-01-25 07:29:02 +0000799 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
Chris Lattner1300fb92007-01-23 23:42:53 +0000800 if (Record->isDefinition()) {
801 // Diagnose code like:
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000802 // struct S { struct S {} X; };
Chris Lattner1300fb92007-01-23 23:42:53 +0000803 // We discover this when we complete the outer S. Reject and ignore the
804 // outer S.
805 Diag(Record->getLocation(), diag::err_nested_redefinition,
806 Record->getKindName());
807 Diag(RecLoc, diag::err_previous_definition);
808 return;
809 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000810
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000811 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +0000812 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000813 llvm::SmallVector<FieldDecl*, 32> RecFields;
814 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Chris Lattnere5a66562007-01-25 22:48:42 +0000815
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000816 for (unsigned i = 0; i != NumFields; ++i) {
817 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
818 if (!FD) continue; // Already issued a diagnostic.
Chris Lattner720a0542007-01-25 00:44:24 +0000819
820 // Get the type for the field.
Chris Lattner0fd893e2007-07-31 21:33:24 +0000821 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner720a0542007-01-25 00:44:24 +0000822
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000823 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner0fd893e2007-07-31 21:33:24 +0000824 if (FDTy->isFunctionType()) {
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000825 Diag(FD->getLocation(), diag::err_field_declared_as_function,
826 FD->getName());
Chris Lattner82625602007-01-24 02:26:21 +0000827 delete FD;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000828 continue;
829 }
830
Chris Lattner82625602007-01-24 02:26:21 +0000831 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
Chris Lattner720a0542007-01-25 00:44:24 +0000832 if (FDTy->isIncompleteType()) {
Chris Lattner82625602007-01-24 02:26:21 +0000833 if (i != NumFields-1 || // ... that the last member ...
834 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner0fd893e2007-07-31 21:33:24 +0000835 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner82625602007-01-24 02:26:21 +0000836 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
837 delete FD;
838 continue;
839 }
Chris Lattner720a0542007-01-25 00:44:24 +0000840 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner82625602007-01-24 02:26:21 +0000841 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
842 FD->getName());
843 delete FD;
844 continue;
845 }
Chris Lattner720a0542007-01-25 00:44:24 +0000846
847 // Okay, we have a legal flexible array member at the end of the struct.
Chris Lattner41943152007-01-25 04:52:46 +0000848 Record->setHasFlexibleArrayMember(true);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000849 }
Chris Lattner720a0542007-01-25 00:44:24 +0000850
851
852 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
853 /// field of another structure or the element of an array.
Chris Lattner0fd893e2007-07-31 21:33:24 +0000854 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner720a0542007-01-25 00:44:24 +0000855 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
856 // If this is a member of a union, then entire union becomes "flexible".
857 if (Record->getKind() == Decl::Union) {
Chris Lattner41943152007-01-25 04:52:46 +0000858 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +0000859 } else {
860 // If this is a struct/class and this is not the last element, reject
861 // it. Note that GCC supports variable sized arrays in the middle of
862 // structures.
863 if (i != NumFields-1) {
864 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
865 FD->getName());
866 delete FD;
867 continue;
868 }
869
870 // We support flexible arrays at the end of structs in other structs
871 // as an extension.
872 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
873 FD->getName());
Chris Lattner41943152007-01-25 04:52:46 +0000874 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +0000875 }
876 }
877 }
878
Chris Lattner82625602007-01-24 02:26:21 +0000879 // Keep track of the number of named members.
Chris Lattnere5a66562007-01-25 22:48:42 +0000880 if (IdentifierInfo *II = FD->getIdentifier()) {
881 // Detect duplicate member names.
Chris Lattnerbaf33662007-01-27 02:14:08 +0000882 if (!FieldIDs.insert(II)) {
Chris Lattnere5a66562007-01-25 22:48:42 +0000883 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
884 // Find the previous decl.
885 SourceLocation PrevLoc;
886 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
887 assert(i != e && "Didn't find previous def!");
888 if (RecFields[i]->getIdentifier() == II) {
889 PrevLoc = RecFields[i]->getLocation();
890 break;
891 }
892 }
893 Diag(PrevLoc, diag::err_previous_definition);
894 delete FD;
895 continue;
896 }
Chris Lattner82625602007-01-24 02:26:21 +0000897 ++NumNamedMembers;
Chris Lattnere5a66562007-01-25 22:48:42 +0000898 }
Chris Lattner41943152007-01-25 04:52:46 +0000899
900 // Remember good fields.
901 RecFields.push_back(FD);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000902 }
Chris Lattner82625602007-01-24 02:26:21 +0000903
904
905 // Okay, we successfully defined 'Record'.
Chris Lattner41943152007-01-25 04:52:46 +0000906 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattner1300fb92007-01-23 23:42:53 +0000907}
908
Chris Lattner4ef40012007-06-11 01:28:17 +0000909Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
910 DeclTy *lastEnumConst,
Chris Lattnerc1915e22007-01-25 07:29:02 +0000911 SourceLocation IdLoc, IdentifierInfo *Id,
Chris Lattner4ef40012007-06-11 01:28:17 +0000912 SourceLocation EqualLoc, ExprTy *val) {
913 theEnumDecl = theEnumDecl; // silence unused warning.
914 EnumConstantDecl *LastEnumConst =
915 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
916 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +0000917
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000918 // The scope passed in may not be a decl scope. Zip up the scope tree until
919 // we find one that is.
920 while ((S->getFlags() & Scope::DeclScope) == 0)
921 S = S->getParent();
922
Chris Lattner8116d1b2007-01-25 22:38:29 +0000923 // Verify that there isn't already something declared with this name in this
924 // scope.
Chris Lattner9561a0b2007-01-28 08:20:04 +0000925 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +0000926 if (S->isDeclScope(PrevDecl)) {
927 if (isa<EnumConstantDecl>(PrevDecl))
928 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
929 else
930 Diag(IdLoc, diag::err_redefinition, Id->getName());
931 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner4ef40012007-06-11 01:28:17 +0000932 // FIXME: Don't leak memory: delete Val;
Chris Lattner8116d1b2007-01-25 22:38:29 +0000933 return 0;
934 }
935 }
Chris Lattner4ef40012007-06-11 01:28:17 +0000936
Chris Lattner23b7eb62007-06-15 23:05:46 +0000937 llvm::APSInt EnumVal(32);
Chris Lattner4ef40012007-06-11 01:28:17 +0000938 QualType EltTy;
939 if (Val) {
Chris Lattner0515e4b2007-08-27 21:16:18 +0000940 // Make sure to promote the operand type to int.
941 UsualUnaryConversions(Val);
942
Chris Lattner4ef40012007-06-11 01:28:17 +0000943 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
944 SourceLocation ExpLoc;
Chris Lattner0e9d6222007-07-15 23:26:56 +0000945 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Chris Lattner4ef40012007-06-11 01:28:17 +0000946 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
947 Id->getName());
948 // FIXME: Don't leak memory: delete Val;
Chris Lattnerf283a372007-08-27 17:37:24 +0000949 Val = 0; // Just forget about it.
Chris Lattnerc92bc4c2007-08-29 16:03:41 +0000950 } else {
951 EltTy = Val->getType();
Chris Lattner4ef40012007-06-11 01:28:17 +0000952 }
Chris Lattnerf283a372007-08-27 17:37:24 +0000953 }
954
955 if (!Val) {
956 if (LastEnumConst) {
957 // Assign the last value + 1.
958 EnumVal = LastEnumConst->getInitVal();
959 ++EnumVal;
Chris Lattner0515e4b2007-08-27 21:16:18 +0000960
961 // Check for overflow on increment.
962 if (EnumVal < LastEnumConst->getInitVal())
963 Diag(IdLoc, diag::warn_enum_value_overflow);
964
Chris Lattnerf283a372007-08-27 17:37:24 +0000965 EltTy = LastEnumConst->getType();
966 } else {
967 // First value, set to zero.
968 EltTy = Context.IntTy;
Chris Lattner0515e4b2007-08-27 21:16:18 +0000969 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy, IdLoc));
Chris Lattnerf283a372007-08-27 17:37:24 +0000970 }
Steve Naroff63969212007-05-07 21:22:42 +0000971 }
Chris Lattner4ef40012007-06-11 01:28:17 +0000972
Chris Lattner4ef40012007-06-11 01:28:17 +0000973 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
974 LastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +0000975
976 // Register this decl in the current scope stack.
977 New->setNext(Id->getFETokenInfo<Decl>());
978 Id->setFETokenInfo(New);
979 S->AddDecl(New);
980 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +0000981}
982
983void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
984 DeclTy **Elements, unsigned NumElements) {
985 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
986 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
987
Chris Lattner67933c02007-08-28 05:10:31 +0000988 // TODO: If the result value doesn't fit in an int, it must be a long or long
989 // long value. ISO C does not support this, but GCC does as an extension,
990 // emit a warning.
Chris Lattnerb8a501c2007-08-28 06:15:15 +0000991 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner67933c02007-08-28 05:10:31 +0000992
993
Chris Lattnerb8a501c2007-08-28 06:15:15 +0000994 // Verify that all the values are okay, compute the size of the values, and
995 // reverse the list.
996 unsigned NumNegativeBits = 0;
997 unsigned NumPositiveBits = 0;
998
999 // Keep track of whether all elements have type int.
1000 bool AllElementsInt = true;
1001
Chris Lattner4ef40012007-06-11 01:28:17 +00001002 EnumConstantDecl *EltList = 0;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001003 for (unsigned i = 0; i != NumElements; ++i) {
1004 EnumConstantDecl *ECD =
1005 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1006 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnerbf478cb2007-08-28 05:27:00 +00001007
1008 // If the enum value doesn't fit in an int, emit an extension warning.
1009 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1010 "Should have promoted value to int");
1011 const llvm::APSInt &InitVal = ECD->getInitVal();
1012 if (InitVal.getBitWidth() > IntWidth) {
1013 llvm::APSInt V(InitVal);
1014 V.trunc(IntWidth);
1015 V.extend(InitVal.getBitWidth());
1016 if (V != InitVal)
1017 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1018 InitVal.toString());
1019 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001020
1021 // Keep track of the size of positive and negative values.
1022 if (InitVal.isUnsigned() || !InitVal.isNegative())
1023 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1024 else
1025 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00001026
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001027 // Keep track of whether every enum element has type int (very commmon).
1028 if (AllElementsInt)
1029 AllElementsInt = ECD->getType() == Context.IntTy;
1030
Chris Lattner4ef40012007-06-11 01:28:17 +00001031 ECD->setNextDeclarator(EltList);
1032 EltList = ECD;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001033 }
1034
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001035 // Figure out the type that should be used for this enum.
1036 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1037 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001038 unsigned BestWidth;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001039
1040 if (NumNegativeBits) {
1041 // If there is a negative value, figure out the smallest integer type (of
1042 // int/long/longlong) that fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001043 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001044 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001045 BestWidth = IntWidth;
1046 } else {
1047 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1048 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001049 BestType = Context.LongTy;
1050 else {
Chris Lattner3a370bf2007-08-29 17:31:48 +00001051 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1052 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001053 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1054 BestType = Context.LongLongTy;
1055 }
1056 }
1057 } else {
1058 // If there is no negative value, figure out which of uint, ulong, ulonglong
1059 // fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001060 if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001061 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001062 BestWidth = IntWidth;
1063 } else if (NumPositiveBits <=
1064 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001065 BestType = Context.UnsignedLongTy;
1066 else {
Chris Lattner3a370bf2007-08-29 17:31:48 +00001067 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1068 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001069 "How could an initializer get larger than ULL?");
1070 BestType = Context.UnsignedLongLongTy;
1071 }
1072 }
1073
Chris Lattner3a370bf2007-08-29 17:31:48 +00001074 // Loop over all of the enumerator constants, changing their types to match
1075 // the type of the enum if needed.
1076 for (unsigned i = 0; i != NumElements; ++i) {
1077 EnumConstantDecl *ECD =
1078 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1079 if (!ECD) continue; // Already issued a diagnostic.
1080
1081 // Standard C says the enumerators have int type, but we allow, as an
1082 // extension, the enumerators to be larger than int size. If each
1083 // enumerator value fits in an int, type it as an int, otherwise type it the
1084 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1085 // that X has type 'int', not 'unsigned'.
1086 if (ECD->getType() == Context.IntTy)
1087 continue; // Already int type.
1088
1089 // Determine whether the value fits into an int.
1090 llvm::APSInt InitVal = ECD->getInitVal();
1091 bool FitsInInt;
1092 if (InitVal.isUnsigned() || !InitVal.isNegative())
1093 FitsInInt = InitVal.getActiveBits() < IntWidth;
1094 else
1095 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1096
1097 // If it fits into an integer type, force it. Otherwise force it to match
1098 // the enum decl type.
1099 QualType NewTy;
1100 unsigned NewWidth;
1101 bool NewSign;
1102 if (FitsInInt) {
1103 NewTy = Context.IntTy;
1104 NewWidth = IntWidth;
1105 NewSign = true;
1106 } else if (ECD->getType() == BestType) {
1107 // Already the right type!
1108 continue;
1109 } else {
1110 NewTy = BestType;
1111 NewWidth = BestWidth;
1112 NewSign = BestType->isSignedIntegerType();
1113 }
1114
1115 // Adjust the APSInt value.
1116 InitVal.extOrTrunc(NewWidth);
1117 InitVal.setIsSigned(NewSign);
1118 ECD->setInitVal(InitVal);
1119
1120 // Adjust the Expr initializer and type.
1121 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1122 ECD->setType(NewTy);
1123 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001124
Chris Lattner1c1f9322007-08-28 18:24:31 +00001125 Enum->defineElements(EltList, BestType);
Chris Lattnerc1915e22007-01-25 07:29:02 +00001126}
Chris Lattner1300fb92007-01-23 23:42:53 +00001127
Steve Naroff26c8ea52007-03-21 21:08:52 +00001128void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1129 if (!current) return;
1130
1131 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1132 // remember this in the LastInGroupList list.
Chris Lattner776fac82007-06-09 00:53:06 +00001133 if (last)
Steve Naroff26c8ea52007-03-21 21:08:52 +00001134 LastInGroupList.push_back((Decl*)last);
Steve Naroff26c8ea52007-03-21 21:08:52 +00001135}
Steve Naroffa8fd9732007-06-11 00:35:03 +00001136
1137void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1138 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1139 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001140 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001141 if (!newType.isNull()) // install the new vector type into the decl
1142 vDecl->setType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001143 }
1144 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001145 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1146 rawAttr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001147 if (!newType.isNull()) // install the new vector type into the decl
1148 tDecl->setUnderlyingType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001149 }
1150 }
Steve Naroff91fcddb2007-07-18 18:00:27 +00001151 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001152 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1153 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1154 else
Steve Naroff91fcddb2007-07-18 18:00:27 +00001155 Diag(rawAttr->getAttributeLoc(),
1156 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001157 }
Steve Naroffa8fd9732007-06-11 00:35:03 +00001158 // FIXME: add other attributes...
1159}
1160
1161void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1162 AttributeList *declarator_postfix) {
1163 while (declspec_prefix) {
1164 HandleDeclAttribute(New, declspec_prefix);
1165 declspec_prefix = declspec_prefix->getNext();
1166 }
1167 while (declarator_postfix) {
1168 HandleDeclAttribute(New, declarator_postfix);
1169 declarator_postfix = declarator_postfix->getNext();
1170 }
1171}
1172
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001173void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1174 AttributeList *rawAttr) {
1175 QualType curType = tDecl->getUnderlyingType();
Steve Naroff91fcddb2007-07-18 18:00:27 +00001176 // check the attribute arugments.
1177 if (rawAttr->getNumArgs() != 1) {
1178 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1179 std::string("1"));
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001180 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001181 }
1182 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1183 llvm::APSInt vecSize(32);
1184 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1185 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1186 sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001187 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001188 }
1189 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1190 // in conjunction with complex types (pointers, arrays, functions, etc.).
1191 Type *canonType = curType.getCanonicalType().getTypePtr();
1192 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1193 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1194 curType.getCanonicalType().getAsString());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001195 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001196 }
1197 // unlike gcc's vector_size attribute, the size is specified as the
1198 // number of elements, not the number of bytes.
1199 unsigned vectorSize = vecSize.getZExtValue();
1200
1201 if (vectorSize == 0) {
1202 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1203 sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001204 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001205 }
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001206 // Instantiate/Install the vector type, the number of elements is > 0.
1207 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1208 // Remember this typedef decl, we will need it later for diagnostics.
1209 OCUVectorDecls.push_back(tDecl);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001210}
1211
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001212QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattner983a8bb2007-07-13 22:13:22 +00001213 AttributeList *rawAttr) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001214 // check the attribute arugments.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001215 if (rawAttr->getNumArgs() != 1) {
1216 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1217 std::string("1"));
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001218 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001219 }
1220 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
Chris Lattner23b7eb62007-06-15 23:05:46 +00001221 llvm::APSInt vecSize(32);
Chris Lattner0e9d6222007-07-15 23:26:56 +00001222 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Steve Naroffa8fd9732007-06-11 00:35:03 +00001223 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1224 sizeExpr->getSourceRange());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001225 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001226 }
1227 // navigate to the base type - we need to provide for vector pointers,
1228 // vector arrays, and functions returning vectors.
1229 Type *canonType = curType.getCanonicalType().getTypePtr();
1230
Steve Naroff91fcddb2007-07-18 18:00:27 +00001231 if (canonType->isPointerType() || canonType->isArrayType() ||
1232 canonType->isFunctionType()) {
1233 assert(1 && "HandleVector(): Complex type construction unimplemented");
1234 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1235 do {
1236 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1237 canonType = PT->getPointeeType().getTypePtr();
1238 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1239 canonType = AT->getElementType().getTypePtr();
1240 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1241 canonType = FT->getResultType().getTypePtr();
1242 } while (canonType->isPointerType() || canonType->isArrayType() ||
1243 canonType->isFunctionType());
1244 */
Steve Naroffa8fd9732007-06-11 00:35:03 +00001245 }
1246 // the base type must be integer or float.
1247 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1248 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1249 curType.getCanonicalType().getAsString());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001250 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001251 }
Chris Lattner4481b422007-07-14 01:29:45 +00001252 unsigned typeSize = Context.getTypeSize(curType, rawAttr->getAttributeLoc());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001253 // vecSize is specified in bytes - convert to bits.
1254 unsigned vectorSize = vecSize.getZExtValue() * 8;
1255
1256 // the vector size needs to be an integral multiple of the type size.
1257 if (vectorSize % typeSize) {
1258 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1259 sizeExpr->getSourceRange());
1260 return QualType();
1261 }
1262 if (vectorSize == 0) {
1263 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1264 sizeExpr->getSourceRange());
1265 return QualType();
1266 }
1267 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1268 // the number of elements to be a power of two (unlike GCC).
1269 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff91fcddb2007-07-18 18:00:27 +00001270 return Context.getVectorType(curType, vectorSize/typeSize);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001271}
1272