blob: 26528485db1cca7ecc32b5fb3c1fa587cad77804 [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 Lattner622c1932008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Chris Lattner5c5fbcc2006-12-03 08:41:30 +000016#include "clang/AST/ASTContext.h"
Anders Carlsson1a841062008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Chris Lattner9561a0b2007-01-28 08:20:04 +000018#include "clang/AST/Builtins.h"
Chris Lattnere168f762006-11-10 05:29:30 +000019#include "clang/AST/Decl.h"
Chris Lattner1300fb92007-01-23 23:42:53 +000020#include "clang/AST/Expr.h"
Chris Lattnerf84a79c2006-11-11 22:59:23 +000021#include "clang/AST/Type.h"
Chris Lattner591a6752006-11-19 23:16:18 +000022#include "clang/Parse/DeclSpec.h"
Chris Lattnere168f762006-11-10 05:29:30 +000023#include "clang/Parse/Scope.h"
Chris Lattnerac18be92006-11-20 06:49:47 +000024#include "clang/Basic/LangOptions.h"
Chris Lattner9561a0b2007-01-28 08:20:04 +000025#include "clang/Basic/TargetInfo.h"
Steve Naroffe101f952008-01-30 23:46:05 +000026#include "clang/Basic/SourceManager.h"
27// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner622c1932008-02-06 00:51:33 +000028#include "clang/Lex/Preprocessor.h"
Steve Naroffe101f952008-01-30 23:46:05 +000029#include "clang/Lex/HeaderSearch.h"
Steve Naroffd54978b2007-09-18 23:55:05 +000030#include "llvm/ADT/SmallString.h"
Chris Lattner38047f92007-01-27 06:24:01 +000031#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian458f7112007-10-05 18:00:57 +000032#include "llvm/ADT/DenseSet.h"
Chris Lattner697e5d62006-11-09 06:32:27 +000033using namespace clang;
34
Chris Lattner2ebe4bb2006-11-20 01:29:42 +000035Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Fariborz Jahaniand52cd412007-10-12 16:34:10 +000036 Decl *IIDecl = II.getFETokenInfo<Decl>();
37 // Find first occurance of none-tagged declaration
38 while(IIDecl && IIDecl->getIdentifierNamespace() != Decl::IDNS_Ordinary)
39 IIDecl = cast<ScopedDecl>(IIDecl)->getNext();
40 if (!IIDecl)
41 return 0;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000042 if (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl))
Fariborz Jahaniand52cd412007-10-12 16:34:10 +000043 return IIDecl;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000044 if (ObjCCompatibleAliasDecl *ADecl =
45 dyn_cast<ObjCCompatibleAliasDecl>(IIDecl))
Fariborz Jahaniand52cd412007-10-12 16:34:10 +000046 return ADecl->getClassInterface();
Steve Naroff09bf8152007-09-06 21:24:23 +000047 return 0;
Chris Lattnere168f762006-11-10 05:29:30 +000048}
49
Steve Naroffc62adb62007-10-09 22:01:59 +000050void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +000051 if (S->decl_empty()) return;
52 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
53
Chris Lattner302b4be2006-11-19 02:31:38 +000054 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
55 I != E; ++I) {
Steve Naroff9324db12007-09-13 18:10:37 +000056 Decl *TmpD = static_cast<Decl*>(*I);
57 assert(TmpD && "This decl didn't get pushed??");
58 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
59 assert(D && "This decl isn't a ScopedDecl?");
60
Chris Lattnerff65b6b2007-01-23 01:33:16 +000061 IdentifierInfo *II = D->getIdentifier();
62 if (!II) continue;
Chris Lattner302b4be2006-11-19 02:31:38 +000063
Chris Lattnerff65b6b2007-01-23 01:33:16 +000064 // Unlink this decl from the identifier. Because the scope contains decls
65 // in an unordered collection, and because we have multiple identifier
66 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
67 if (II->getFETokenInfo<Decl>() == D) {
68 // Normal case, no multiple decls in different namespaces.
69 II->setFETokenInfo(D->getNext());
70 } else {
71 // Scan ahead. There are only three namespaces in C, so this loop can
72 // never execute more than 3 times.
Steve Naroff9324db12007-09-13 18:10:37 +000073 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Chris Lattnerff65b6b2007-01-23 01:33:16 +000074 while (SomeDecl->getNext() != D) {
75 SomeDecl = SomeDecl->getNext();
76 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
77 }
78 SomeDecl->setNext(D->getNext());
79 }
Chris Lattner302b4be2006-11-19 02:31:38 +000080
Chris Lattner740b2f32006-11-21 01:32:20 +000081 // This will have to be revisited for C++: there we want to nest stuff in
82 // namespace decls etc. Even for C, we might want a top-level translation
83 // unit decl or something.
84 if (!CurFunctionDecl)
85 continue;
86
87 // Chain this decl to the containing function, it now owns the memory for
88 // the decl.
89 D->setNext(CurFunctionDecl->getDeclChain());
90 CurFunctionDecl->setDeclChain(D);
Chris Lattner302b4be2006-11-19 02:31:38 +000091 }
92}
93
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +000094/// LookupInterfaceDecl - Lookup interface declaration in the scope chain.
95/// Return the first declaration found (which may or may not be a class
Fariborz Jahanian02fbb682007-10-12 19:53:08 +000096/// declaration. Caller is responsible for handling the none-class case.
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +000097/// Bypassing the alias of a class by returning the aliased class.
98ScopedDecl *Sema::LookupInterfaceDecl(IdentifierInfo *ClassName) {
99 ScopedDecl *IDecl;
100 // Scan up the scope chain looking for a decl that matches this identifier
101 // that is in the appropriate namespace.
102 for (IDecl = ClassName->getFETokenInfo<ScopedDecl>(); IDecl;
103 IDecl = IDecl->getNext())
104 if (IDecl->getIdentifierNamespace() == Decl::IDNS_Ordinary)
105 break;
106
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000107 if (ObjCCompatibleAliasDecl *ADecl =
108 dyn_cast_or_null<ObjCCompatibleAliasDecl>(IDecl))
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +0000109 return ADecl->getClassInterface();
110 return IDecl;
111}
112
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000113/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian343f7092007-09-29 00:54:24 +0000114/// return 0 if one not found.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000115ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +0000116 ScopedDecl *IdDecl = LookupInterfaceDecl(Id);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000117 return cast_or_null<ObjCInterfaceDecl>(IdDecl);
Fariborz Jahanian343f7092007-09-29 00:54:24 +0000118}
119
Chris Lattner18b19622007-01-22 07:39:13 +0000120/// LookupScopedDecl - Look up the inner-most declaration in the specified
121/// namespace.
Steve Naroff9324db12007-09-13 18:10:37 +0000122ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
123 SourceLocation IdLoc, Scope *S) {
Chris Lattner18b19622007-01-22 07:39:13 +0000124 if (II == 0) return 0;
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000125 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
Chris Lattner18b19622007-01-22 07:39:13 +0000126
127 // Scan up the scope chain looking for a decl that matches this identifier
128 // that is in the appropriate namespace. This search should not take long, as
129 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroff9324db12007-09-13 18:10:37 +0000130 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner18b19622007-01-22 07:39:13 +0000131 if (D->getIdentifierNamespace() == NS)
132 return D;
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000133
Chris Lattner9561a0b2007-01-28 08:20:04 +0000134 // If we didn't find a use of this identifier, and if the identifier
135 // corresponds to a compiler builtin, create the decl object for the builtin
136 // now, injecting it into translation unit scope, and return it.
137 if (NS == Decl::IDNS_Ordinary) {
138 // If this is a builtin on some other target, or if this builtin varies
139 // across targets (e.g. in type), emit a diagnostic and mark the translation
140 // unit non-portable for using it.
141 if (II->isNonPortableBuiltin()) {
142 // Only emit this diagnostic once for this builtin.
143 II->setNonPortableBuiltin(false);
Ted Kremenek1daa3cf2007-12-12 22:39:36 +0000144 Context.Target.DiagnoseNonPortability(Context.getFullLoc(IdLoc),
Chris Lattner9561a0b2007-01-28 08:20:04 +0000145 diag::port_target_builtin_use);
146 }
Chris Lattner9561a0b2007-01-28 08:20:04 +0000147 // If this is a builtin on this (or all) targets, create the decl.
148 if (unsigned BuiltinID = II->getBuiltinID())
149 return LazilyCreateBuiltin(II, BuiltinID, S);
150 }
Chris Lattner18b19622007-01-22 07:39:13 +0000151 return 0;
152}
153
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000154void Sema::InitBuiltinVaListType()
155{
156 if (!Context.getBuiltinVaListType().isNull())
157 return;
158
159 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
160 ScopedDecl *VaDecl = LookupScopedDecl(VaIdent, Decl::IDNS_Ordinary,
161 SourceLocation(), TUScope);
Steve Naroffeee59eb2007-10-18 22:17:45 +0000162 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000163 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
164}
165
Chris Lattner9561a0b2007-01-28 08:20:04 +0000166/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
167/// lazily create a decl for it.
Chris Lattner9c7a0362007-10-10 23:42:28 +0000168ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
169 Scope *S) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000170 Builtin::ID BID = (Builtin::ID)bid;
171
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000172 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson24ebce62007-10-12 23:56:29 +0000173 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000174 BID == Builtin::BI__builtin_va_end)
175 InitBuiltinVaListType();
176
Anders Carlsson87c149b2007-10-11 01:00:40 +0000177 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner776fac82007-06-09 00:53:06 +0000178 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattnerb677a932007-08-26 04:02:13 +0000179 FunctionDecl::Extern, false, 0);
Chris Lattner9561a0b2007-01-28 08:20:04 +0000180
181 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000182 if (Scope *FnS = S->getFnParent())
183 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner9561a0b2007-01-28 08:20:04 +0000184 while (S->getParent())
185 S = S->getParent();
186 S->AddDecl(New);
187
188 // Add this decl to the end of the identifier info.
Steve Naroff9324db12007-09-13 18:10:37 +0000189 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000190 // Scan until we find the last (outermost) decl in the id chain.
191 while (LastDecl->getNext())
192 LastDecl = LastDecl->getNext();
193 // Insert before (outside) it.
194 LastDecl->setNext(New);
195 } else {
196 II->setFETokenInfo(New);
197 }
Chris Lattner9561a0b2007-01-28 08:20:04 +0000198 return New;
199}
200
Chris Lattner01564d92007-01-27 19:27:06 +0000201/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
202/// and scope as a previous declaration 'Old'. Figure out how to resolve this
203/// situation, merging decls or emitting diagnostics as appropriate.
204///
Steve Naroff9def2b12007-09-13 21:41:19 +0000205TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000206 // Verify the old decl was also a typedef.
207 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
208 if (!Old) {
209 Diag(New->getLocation(), diag::err_redefinition_different_kind,
210 New->getName());
211 Diag(OldD->getLocation(), diag::err_previous_definition);
212 return New;
213 }
214
Steve Naroff6d40db02007-10-31 18:42:27 +0000215 // Allow multiple definitions for ObjC built-in typedefs.
216 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000217 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff6d40db02007-10-31 18:42:27 +0000218 return Old;
Steve Naroffe101f952008-01-30 23:46:05 +0000219
220 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
221 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
222 // *either* declaration is in a system header. The code below implements
223 // this adhoc compatibility rule. FIXME: The following code will not
224 // work properly when compiling ".i" files (containing preprocessed output).
225 SourceManager &SrcMgr = Context.getSourceManager();
226 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
227 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
228 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
229 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
230 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
231
Steve Naroffb2c80c72008-02-07 03:50:06 +0000232 if ((OldDirType == DirectoryLookup::ExternCSystemHeaderDir ||
233 NewDirType == DirectoryLookup::ExternCSystemHeaderDir) ||
234 getLangOptions().Microsoft)
Steve Naroffe101f952008-01-30 23:46:05 +0000235 return New;
Steve Naroff6d40db02007-10-31 18:42:27 +0000236
Chris Lattner01564d92007-01-27 19:27:06 +0000237 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
238 // TODO: This is totally simplistic. It should handle merging functions
239 // together etc, merging extern int X; int X; ...
240 Diag(New->getLocation(), diag::err_redefinition, New->getName());
241 Diag(Old->getLocation(), diag::err_previous_definition);
242 return New;
243}
244
245/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
246/// and scope as a previous declaration 'Old'. Figure out how to resolve this
247/// situation, merging decls or emitting diagnostics as appropriate.
248///
Steve Naroff9def2b12007-09-13 21:41:19 +0000249FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000250 // Verify the old decl was also a function.
251 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
252 if (!Old) {
253 Diag(New->getLocation(), diag::err_redefinition_different_kind,
254 New->getName());
255 Diag(OldD->getLocation(), diag::err_previous_definition);
256 return New;
257 }
Chris Lattner8a8558b2008-02-29 16:48:43 +0000258
259 // FIXME: propagate old Attrs to the New decl
Chris Lattnerc511efb2007-01-27 19:32:14 +0000260
Chris Lattner5c3f1542007-11-20 19:04:50 +0000261 QualType OldQType = Old->getCanonicalType();
262 QualType NewQType = New->getCanonicalType();
263
Steve Naroff012484d2008-01-14 20:51:29 +0000264 // Function types need to be compatible, not identical. This handles
265 // duplicate function decls like "void f(int); void f(enum X);" properly.
266 if (Context.functionTypesAreCompatible(OldQType, NewQType))
267 return New;
Chris Lattner45d561a2007-11-06 06:07:26 +0000268
Steve Naroff17832a42008-01-16 15:01:34 +0000269 // A function that has already been declared has been redeclared or defined
270 // with a different type- show appropriate diagnostic
271 diag::kind PrevDiag = Old->getBody() ? diag::err_previous_definition :
272 diag::err_previous_declaration;
273
Chris Lattner01564d92007-01-27 19:27:06 +0000274 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
275 // TODO: This is totally simplistic. It should handle merging functions
276 // together etc, merging extern int X; int X; ...
Steve Naroff17832a42008-01-16 15:01:34 +0000277 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
278 Diag(Old->getLocation(), PrevDiag);
Chris Lattner01564d92007-01-27 19:27:06 +0000279 return New;
280}
281
Chris Lattner32097252007-11-06 04:28:31 +0000282/// equivalentArrayTypes - Used to determine whether two array types are
283/// equivalent.
284/// We need to check this explicitly as an incomplete array definition is
285/// considered a VariableArrayType, so will not match a complete array
286/// definition that would be otherwise equivalent.
287static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
288 const ArrayType *NewAT = NewQType->getAsArrayType();
289 const ArrayType *OldAT = OldQType->getAsArrayType();
290
291 if (!NewAT || !OldAT)
292 return false;
293
294 // If either (or both) array types in incomplete we need to strip off the
295 // outer VariableArrayType. Once the outer VAT is removed the remaining
296 // types must be identical if the array types are to be considered
297 // equivalent.
298 // eg. int[][1] and int[1][1] become
299 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
300 // removing the outermost VAT gives
301 // CAT(1, int) and CAT(1, int)
302 // which are equal, therefore the array types are equivalent.
Eli Friedman9e805b22008-02-15 12:53:51 +0000303 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattner32097252007-11-06 04:28:31 +0000304 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
305 return false;
Eli Friedman361de612008-01-29 07:51:12 +0000306 NewQType = NewAT->getElementType().getCanonicalType();
307 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattner32097252007-11-06 04:28:31 +0000308 }
309
310 return NewQType == OldQType;
311}
312
Chris Lattner01564d92007-01-27 19:27:06 +0000313/// MergeVarDecl - We just parsed a variable 'New' which has the same name
314/// and scope as a previous declaration 'Old'. Figure out how to resolve this
315/// situation, merging decls or emitting diagnostics as appropriate.
316///
Steve Narofffc49d672007-04-01 21:27:45 +0000317/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
318/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
319///
Steve Naroff9def2b12007-09-13 21:41:19 +0000320VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000321 // Verify the old decl was also a variable.
322 VarDecl *Old = dyn_cast<VarDecl>(OldD);
323 if (!Old) {
324 Diag(New->getLocation(), diag::err_redefinition_different_kind,
325 New->getName());
326 Diag(OldD->getLocation(), diag::err_previous_definition);
327 return New;
328 }
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000329 // Verify the types match.
Chris Lattner32097252007-11-06 04:28:31 +0000330 if (Old->getCanonicalType() != New->getCanonicalType() &&
331 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000332 Diag(New->getLocation(), diag::err_redefinition, New->getName());
333 Diag(Old->getLocation(), diag::err_previous_definition);
334 return New;
335 }
Steve Naroff1e787362008-01-30 00:44:01 +0000336 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
337 if (New->getStorageClass() == VarDecl::Static &&
338 (Old->getStorageClass() == VarDecl::None ||
339 Old->getStorageClass() == VarDecl::Extern)) {
340 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
341 Diag(Old->getLocation(), diag::err_previous_definition);
342 return New;
343 }
344 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
345 if (New->getStorageClass() != VarDecl::Static &&
346 Old->getStorageClass() == VarDecl::Static) {
347 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
348 Diag(Old->getLocation(), diag::err_previous_definition);
349 return New;
350 }
351 // We've verified the types match, now handle "tentative" definitions.
352 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
353 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
354
355 if (OldFSDecl && NewFSDecl) {
356 // Handle C "tentative" external object definitions (C99 6.9.2).
357 bool OldIsTentative = false;
358 bool NewIsTentative = false;
359
360 if (!OldFSDecl->getInit() &&
361 (OldFSDecl->getStorageClass() == VarDecl::None ||
362 OldFSDecl->getStorageClass() == VarDecl::Static))
363 OldIsTentative = true;
364
365 // FIXME: this check doesn't work (since the initializer hasn't been
366 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
367 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
368 // thrown out the old decl.
369 if (!NewFSDecl->getInit() &&
370 (NewFSDecl->getStorageClass() == VarDecl::None ||
371 NewFSDecl->getStorageClass() == VarDecl::Static))
372 ; // change to NewIsTentative = true; once the code is moved.
373
374 if (NewIsTentative || OldIsTentative)
375 return New;
376 }
377 if (Old->getStorageClass() != VarDecl::Extern &&
378 New->getStorageClass() != VarDecl::Extern) {
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000379 Diag(New->getLocation(), diag::err_redefinition, New->getName());
380 Diag(Old->getLocation(), diag::err_previous_definition);
381 }
Chris Lattner01564d92007-01-27 19:27:06 +0000382 return New;
383}
384
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000385/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
386/// no declarator (e.g. "struct foo;") is parsed.
387Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
388 // TODO: emit error on 'int;' or 'const enum foo;'.
389 // TODO: emit error on 'typedef int;'
390 // if (!DS.isMissingDeclaratorOk()) Diag(...);
391
Steve Naroff14f5f792007-11-17 21:37:36 +0000392 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000393}
394
Steve Naroff98f72032008-01-10 22:15:12 +0000395bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroff2fea1392007-09-02 02:04:30 +0000396 // Get the type before calling CheckSingleAssignmentConstraints(), since
397 // it can promote the expression.
Chris Lattner9bad62c2008-01-04 18:04:52 +0000398 QualType InitType = Init->getType();
Steve Naroff2fea1392007-09-02 02:04:30 +0000399
Chris Lattner9bad62c2008-01-04 18:04:52 +0000400 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
401 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
402 InitType, Init, "initializing");
Steve Naroff2fea1392007-09-02 02:04:30 +0000403}
404
Steve Naroff77b97002007-09-04 14:36:54 +0000405bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroff98f72032008-01-10 22:15:12 +0000406 QualType ElementType) {
Chris Lattnerf6412552007-12-11 23:15:04 +0000407 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff98f72032008-01-10 22:15:12 +0000408 if (CheckSingleInitializer(expr, ElementType))
Chris Lattnerf6412552007-12-11 23:15:04 +0000409 return true; // types weren't compatible.
410
Steve Naroff77b97002007-09-04 14:36:54 +0000411 if (savExpr != expr) // The type was promoted, update initializer list.
412 IList->setInit(slot, expr);
Steve Naroffac074b42007-09-04 02:20:04 +0000413 return false;
414}
415
Steve Naroffaf2a0222008-01-22 00:55:40 +0000416bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanbd258282008-02-15 18:16:39 +0000417 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffaf2a0222008-01-22 00:55:40 +0000418 // C99 6.7.8p14. We have an array of character type with unknown size
419 // being initialized to a string literal.
420 llvm::APSInt ConstVal(32);
421 ConstVal = strLiteral->getByteLength() + 1;
422 // Return a new array type (C99 6.7.8p22).
Eli Friedmanbd258282008-02-15 18:16:39 +0000423 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffaf2a0222008-01-22 00:55:40 +0000424 ArrayType::Normal, 0);
425 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
426 // C99 6.7.8p14. We have an array of character type with known size.
427 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
428 Diag(strLiteral->getSourceRange().getBegin(),
429 diag::warn_initializer_string_for_char_array_too_long,
430 strLiteral->getSourceRange());
431 } else {
432 assert(0 && "HandleStringLiteralInit(): Invalid array type");
433 }
434 // Set type from "char *" to "constant array of char".
435 strLiteral->setType(DeclT);
436 // For now, we always return false (meaning success).
437 return false;
438}
439
440StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffaf2a0222008-01-22 00:55:40 +0000441 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000442 if (AT && AT->getElementType()->isCharType()) {
443 return dyn_cast<StringLiteral>(Init);
444 }
Steve Naroffaf2a0222008-01-22 00:55:40 +0000445 return 0;
446}
447
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000448// CheckInitializerListTypes - Checks the types of elements of an initializer
449// list. This function is recursive: it calls itself to initialize subelements
450// of aggregate types. Note that the topLevel parameter essentially refers to
451// whether this expression "owns" the initializer list passed in, or if this
452// initialization is taking elements out of a parent initializer. Each
453// call to this function adds zero or more to startIndex, reports any errors,
454// and returns true if it found any inconsistent types.
455bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
456 bool topLevel, unsigned& startIndex) {
Steve Naroff91f78082007-12-10 22:44:33 +0000457 bool hadError = false;
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000458
459 if (DeclType->isScalarType()) {
460 // The simplest case: initializing a single scalar
461 if (topLevel) {
462 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
463 IList->getSourceRange());
464 }
465 if (startIndex < IList->getNumInits()) {
466 Expr* expr = IList->getInit(startIndex);
467 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
468 // FIXME: Should an error be reported here instead?
469 unsigned newIndex = 0;
470 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
471 } else {
472 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
473 }
474 ++startIndex;
475 }
476 // FIXME: Should an error be reported for empty initializer list + scalar?
477 } else if (DeclType->isVectorType()) {
478 if (startIndex < IList->getNumInits()) {
479 const VectorType *VT = DeclType->getAsVectorType();
480 int maxElements = VT->getNumElements();
481 QualType elementType = VT->getElementType();
482
483 for (int i = 0; i < maxElements; ++i) {
484 // Don't attempt to go past the end of the init list
485 if (startIndex >= IList->getNumInits())
486 break;
487 Expr* expr = IList->getInit(startIndex);
488 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
489 unsigned newIndex = 0;
490 hadError |= CheckInitializerListTypes(SubInitList, elementType,
491 true, newIndex);
492 ++startIndex;
493 } else {
494 hadError |= CheckInitializerListTypes(IList, elementType,
495 false, startIndex);
496 }
497 }
498 }
499 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
500 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroffaeb6b302008-01-28 02:00:41 +0000501 if (startIndex < IList->getNumInits() && !topLevel &&
502 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
503 DeclType)) {
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000504 // We found a compatible struct; per the standard, this initializes the
505 // struct. (The C standard technically says that this only applies for
506 // initializers for declarations with automatic scope; however, this
507 // construct is unambiguous anyway because a struct cannot contain
508 // a type compatible with itself. We'll output an error when we check
509 // if the initializer is constant.)
510 // FIXME: Is a call to CheckSingleInitializer required here?
511 ++startIndex;
512 } else {
513 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroff326389b2008-02-11 00:06:17 +0000514
Steve Naroffb5fc2552008-02-11 21:52:37 +0000515 // If the record is invalid, some of it's members are invalid. To avoid
516 // confusion, we forgo checking the intializer for the entire record.
Steve Naroff326389b2008-02-11 00:06:17 +0000517 if (structDecl->isInvalidDecl())
518 return true;
519
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000520 // If structDecl is a forward declaration, this loop won't do anything;
521 // That's okay, because an error should get printed out elsewhere. It
522 // might be worthwhile to skip over the rest of the initializer, though.
523 int numMembers = structDecl->getNumMembers() -
524 structDecl->hasFlexibleArrayMember();
525 for (int i = 0; i < numMembers; i++) {
526 // Don't attempt to go past the end of the init list
527 if (startIndex >= IList->getNumInits())
528 break;
529 FieldDecl * curField = structDecl->getMember(i);
530 if (!curField->getIdentifier()) {
531 // Don't initialize unnamed fields, e.g. "int : 20;"
532 continue;
533 }
534 QualType fieldType = curField->getType();
535 Expr* expr = IList->getInit(startIndex);
536 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
537 unsigned newStart = 0;
538 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
539 true, newStart);
540 ++startIndex;
541 } else {
542 hadError |= CheckInitializerListTypes(IList, fieldType,
543 false, startIndex);
544 }
545 if (DeclType->isUnionType())
546 break;
547 }
548 // FIXME: Implement flexible array initialization GCC extension (it's a
549 // really messy extension to implement, unfortunately...the necessary
550 // information isn't actually even here!)
551 }
552 } else if (DeclType->isArrayType()) {
553 // Check for the special-case of initializing an array with a string.
554 if (startIndex < IList->getNumInits()) {
555 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
556 DeclType)) {
557 CheckStringLiteralInit(lit, DeclType);
558 ++startIndex;
559 if (topLevel && startIndex < IList->getNumInits()) {
560 // We have leftover initializers; warn
561 Diag(IList->getInit(startIndex)->getLocStart(),
562 diag::err_excess_initializers_in_char_array_initializer,
563 IList->getInit(startIndex)->getSourceRange());
564 }
565 return false;
566 }
567 }
568 int maxElements;
Eli Friedmanbd258282008-02-15 18:16:39 +0000569 if (DeclType->isIncompleteArrayType()) {
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000570 // FIXME: use a proper constant
571 maxElements = 0x7FFFFFFF;
Chris Lattnerf1791902008-02-20 23:17:35 +0000572 } else if (const VariableArrayType *VAT =
573 DeclType->getAsVariableArrayType()) {
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000574 // Check for VLAs; in standard C it would be possible to check this
575 // earlier, but I don't know where clang accepts VLAs (gcc accepts
576 // them in all sorts of strange places).
Eli Friedmanbd258282008-02-15 18:16:39 +0000577 Diag(VAT->getSizeExpr()->getLocStart(),
578 diag::err_variable_object_no_init,
579 VAT->getSizeExpr()->getSourceRange());
580 hadError = true;
581 maxElements = 0x7FFFFFFF;
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000582 } else {
583 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
584 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
585 }
586 QualType elementType = DeclType->getAsArrayType()->getElementType();
587 int numElements = 0;
588 for (int i = 0; i < maxElements; ++i, ++numElements) {
589 // Don't attempt to go past the end of the init list
590 if (startIndex >= IList->getNumInits())
591 break;
592 Expr* expr = IList->getInit(startIndex);
593 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
594 unsigned newIndex = 0;
595 hadError |= CheckInitializerListTypes(SubInitList, elementType,
596 true, newIndex);
597 ++startIndex;
598 } else {
599 hadError |= CheckInitializerListTypes(IList, elementType,
600 false, startIndex);
601 }
602 }
Eli Friedman9e805b22008-02-15 12:53:51 +0000603 if (DeclType->isIncompleteArrayType()) {
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000604 // If this is an incomplete array type, the actual type needs to
605 // be calculated here
606 if (numElements == 0) {
607 // Sizing an array implicitly to zero is not allowed
608 // (It could in theory be allowed, but it doesn't really matter.)
609 Diag(IList->getLocStart(),
610 diag::err_at_least_one_initializer_needed_to_size_array);
611 hadError = true;
612 } else {
613 llvm::APSInt ConstVal(32);
614 ConstVal = numElements;
615 DeclType = Context.getConstantArrayType(elementType, ConstVal,
616 ArrayType::Normal, 0);
617 }
618 }
619 } else {
620 assert(0 && "Aggregate that isn't a function or array?!");
621 }
622 } else {
623 // In C, all types are either scalars or aggregates, but
624 // additional handling is needed here for C++ (and possibly others?).
625 assert(0 && "Unsupported initializer type");
626 }
627
628 // If this init list is a base list, we set the type; an initializer doesn't
629 // fundamentally have a type, but this makes the ASTs a bit easier to read
630 if (topLevel)
631 IList->setType(DeclType);
632
633 if (topLevel && startIndex < IList->getNumInits()) {
634 // We have leftover initializers; warn
635 Diag(IList->getInit(startIndex)->getLocStart(),
636 diag::warn_excess_initializers,
637 IList->getInit(startIndex)->getSourceRange());
638 }
639 return hadError;
640}
641
642bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Narofff9eb5982008-01-21 23:53:58 +0000643 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
644 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanbd258282008-02-15 18:16:39 +0000645 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Narofff9eb5982008-01-21 23:53:58 +0000646 return Diag(VAT->getSizeExpr()->getLocStart(),
647 diag::err_variable_object_no_init,
648 VAT->getSizeExpr()->getSourceRange());
649
Steve Naroff91f78082007-12-10 22:44:33 +0000650 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
651 if (!InitList) {
Steve Naroffaf2a0222008-01-22 00:55:40 +0000652 // FIXME: Handle wide strings
653 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
654 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman42978262008-02-08 00:48:24 +0000655
656 if (DeclType->isArrayType())
657 return Diag(Init->getLocStart(),
658 diag::err_array_init_list_required,
659 Init->getSourceRange());
660
Steve Naroff98f72032008-01-10 22:15:12 +0000661 return CheckSingleInitializer(Init, DeclType);
Steve Naroff91f78082007-12-10 22:44:33 +0000662 }
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000663 unsigned newIndex = 0;
664 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroff2fea1392007-09-02 02:04:30 +0000665}
666
Fariborz Jahanian56ff1462007-11-08 23:49:49 +0000667Sema::DeclTy *
Steve Naroff30d242c2007-09-15 18:49:24 +0000668Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroffa23cc792007-09-13 23:52:58 +0000669 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattnere168f762006-11-10 05:29:30 +0000670 IdentifierInfo *II = D.getIdentifier();
Chris Lattner302b4be2006-11-19 02:31:38 +0000671
Chris Lattner02c04392007-07-25 00:24:17 +0000672 // All of these full declarators require an identifier. If it doesn't have
673 // one, the ParsedFreeStandingDeclSpec action should be used.
674 if (II == 0) {
Chris Lattnera7c19fe2007-10-16 22:36:42 +0000675 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerc4f6d0c2007-08-28 06:17:15 +0000676 diag::err_declarator_need_ident,
Chris Lattner02c04392007-07-25 00:24:17 +0000677 D.getDeclSpec().getSourceRange(), D.getSourceRange());
678 return 0;
679 }
680
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000681 // The scope passed in may not be a decl scope. Zip up the scope tree until
682 // we find one that is.
683 while ((S->getFlags() & Scope::DeclScope) == 0)
684 S = S->getParent();
685
Chris Lattner01564d92007-01-27 19:27:06 +0000686 // See if this is a redefinition of a variable in the same scope.
Steve Naroff9324db12007-09-13 18:10:37 +0000687 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
688 D.getIdentifierLoc(), S);
Steve Naroff9324db12007-09-13 18:10:37 +0000689 ScopedDecl *New;
Steve Narofff93b6722007-08-28 20:14:24 +0000690 bool InvalidDecl = false;
691
Chris Lattner07b201d2007-11-14 06:34:38 +0000692 QualType R = GetTypeForDeclarator(D, S);
693 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
694
Chris Lattner01a7c532007-01-25 23:09:03 +0000695 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner07b201d2007-11-14 06:34:38 +0000696 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner01564d92007-01-27 19:27:06 +0000697 if (!NewTD) return 0;
Steve Naroffa8fd9732007-06-11 00:35:03 +0000698
699 // Handle attributes prior to checking for duplicates in MergeVarDecl
700 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
701 D.getAttributes());
Steve Naroffe6b0ec82008-01-09 23:34:55 +0000702 // Merge the decl with the existing one if appropriate. If the decl is
703 // in an outer scope, it isn't the same thing.
704 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner01564d92007-01-27 19:27:06 +0000705 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
706 if (NewTD == 0) return 0;
707 }
708 New = NewTD;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000709 if (S->getParent() == 0) {
710 // C99 6.7.7p2: If a typedef name specifies a variably modified type
711 // then it shall have block scope.
Eli Friedman9e805b22008-02-15 12:53:51 +0000712 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
713 // FIXME: Diagnostic needs to be fixed.
714 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff096dd942007-08-31 17:20:07 +0000715 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000716 }
717 }
Chris Lattner07b201d2007-11-14 06:34:38 +0000718 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattnercc61bf52007-09-27 15:15:46 +0000719 FunctionDecl::StorageClass SC = FunctionDecl::None;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000720 switch (D.getDeclSpec().getStorageClassSpec()) {
721 default: assert(0 && "Unknown storage class!");
722 case DeclSpec::SCS_auto:
723 case DeclSpec::SCS_register:
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000724 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
725 R.getAsString());
Steve Narofff93b6722007-08-28 20:14:24 +0000726 InvalidDecl = true;
727 break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000728 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
729 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
730 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff1f7f6922008-01-28 21:57:15 +0000731 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000732 }
733
Chris Lattner776fac82007-06-09 00:53:06 +0000734 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattnerb677a932007-08-26 04:02:13 +0000735 D.getDeclSpec().isInlineSpecified(),
Anders Carlsson1a841062008-02-15 07:04:12 +0000736 LastDeclarator);
Ted Kremenek49b61ab2008-02-27 22:18:07 +0000737 // Handle attributes.
738
739 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
740 D.getAttributes());
Chris Lattner01564d92007-01-27 19:27:06 +0000741
Steve Naroffe6b0ec82008-01-09 23:34:55 +0000742 // Merge the decl with the existing one if appropriate. Since C functions
743 // are in a flat namespace, make sure we consider decls in outer scopes.
Chris Lattner01564d92007-01-27 19:27:06 +0000744 if (PrevDecl) {
745 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
746 if (NewFD == 0) return 0;
747 }
748 New = NewFD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000749 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000750 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +0000751 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
752 D.getIdentifier()->getName());
753 InvalidDecl = true;
754 }
Chris Lattner01564d92007-01-27 19:27:06 +0000755
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000756 VarDecl *NewVD;
757 VarDecl::StorageClass SC;
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000758 switch (D.getDeclSpec().getStorageClassSpec()) {
759 default: assert(0 && "Unknown storage class!");
Steve Narofffda82092008-01-25 22:14:40 +0000760 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
761 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
762 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
763 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
764 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
765 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000766 }
Steve Narofffc49d672007-04-01 21:27:45 +0000767 if (S->getParent() == 0) {
Bill Wendlingd6de6572007-06-02 09:40:07 +0000768 // C99 6.9p2: The storage-class specifiers auto and register shall not
769 // appear in the declaration specifiers in an external declaration.
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000770 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000771 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
772 R.getAsString());
Steve Naroffcf871f52007-08-28 18:45:29 +0000773 InvalidDecl = true;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000774 }
Chris Lattner776fac82007-06-09 00:53:06 +0000775 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff2fea1392007-09-02 02:04:30 +0000776 } else {
Chris Lattner776fac82007-06-09 00:53:06 +0000777 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcf871f52007-08-28 18:45:29 +0000778 }
Steve Naroffa8fd9732007-06-11 00:35:03 +0000779 // Handle attributes prior to checking for duplicates in MergeVarDecl
780 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
781 D.getAttributes());
782
Steve Naroffe6b0ec82008-01-09 23:34:55 +0000783 // Merge the decl with the existing one if appropriate. If the decl is
784 // in an outer scope, it isn't the same thing.
785 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner01564d92007-01-27 19:27:06 +0000786 NewVD = MergeVarDecl(NewVD, PrevDecl);
787 if (NewVD == 0) return 0;
788 }
789 New = NewVD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000790 }
Chris Lattner302b4be2006-11-19 02:31:38 +0000791
Chris Lattnere168f762006-11-10 05:29:30 +0000792 // If this has an identifier, add it to the scope stack.
793 if (II) {
Steve Naroff9324db12007-09-13 18:10:37 +0000794 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattnere168f762006-11-10 05:29:30 +0000795 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000796 S->AddDecl(New);
Chris Lattnere168f762006-11-10 05:29:30 +0000797 }
Steve Narofff93b6722007-08-28 20:14:24 +0000798 // If any semantic error occurred, mark the decl as invalid.
799 if (D.getInvalidType() || InvalidDecl)
800 New->setInvalidDecl();
Chris Lattnere168f762006-11-10 05:29:30 +0000801
802 return New;
803}
804
Steve Naroff98f72032008-01-10 22:15:12 +0000805bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
806 SourceLocation loc;
807 // FIXME: Remove the isReference check and handle assignment to a reference.
808 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
809 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
810 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
811 return true;
812 }
813 return false;
814}
815
Steve Naroff61091402007-09-12 14:07:44 +0000816void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff437b4d82007-09-12 20:13:48 +0000817 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff61091402007-09-12 14:07:44 +0000818 Expr *Init = static_cast<Expr *>(init);
Chris Lattner8beb9de2007-10-19 20:10:30 +0000819 assert(Init && "missing initializer");
Steve Naroff61091402007-09-12 14:07:44 +0000820
Chris Lattner8beb9de2007-10-19 20:10:30 +0000821 // If there is no declaration, there was an error parsing it. Just ignore
822 // the initializer.
823 if (RealDecl == 0) {
824 delete Init;
825 return;
826 }
Steve Naroff61091402007-09-12 14:07:44 +0000827
Steve Naroff437b4d82007-09-12 20:13:48 +0000828 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
829 if (!VDecl) {
Steve Naroff9def2b12007-09-13 21:41:19 +0000830 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
831 diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +0000832 RealDecl->setInvalidDecl();
833 return;
834 }
Steve Naroff61091402007-09-12 14:07:44 +0000835 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +0000836 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +0000837 QualType DclT = VDecl->getType(), SavT = DclT;
838 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff61091402007-09-12 14:07:44 +0000839 VarDecl::StorageClass SC = BVD->getStorageClass();
840 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +0000841 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff61091402007-09-12 14:07:44 +0000842 BVD->setInvalidDecl();
843 } else if (!BVD->isInvalidDecl()) {
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000844 if (CheckInitializerTypes(Init, DclT))
845 BVD->setInvalidDecl();
Steve Naroff98f72032008-01-10 22:15:12 +0000846 if (SC == VarDecl::Static) // C99 6.7.8p4.
847 CheckForConstantInitializer(Init, DclT);
Steve Naroff61091402007-09-12 14:07:44 +0000848 }
Steve Naroff437b4d82007-09-12 20:13:48 +0000849 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff61091402007-09-12 14:07:44 +0000850 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff437b4d82007-09-12 20:13:48 +0000851 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff61091402007-09-12 14:07:44 +0000852 if (!FVD->isInvalidDecl())
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000853 if (CheckInitializerTypes(Init, DclT))
854 FVD->setInvalidDecl();
Steve Naroff98f72032008-01-10 22:15:12 +0000855
856 // C99 6.7.8p4. All file scoped initializers need to be constant.
857 CheckForConstantInitializer(Init, DclT);
Steve Naroff61091402007-09-12 14:07:44 +0000858 }
859 // If the type changed, it means we had an incomplete type that was
860 // completed by the initializer. For example:
861 // int ary[] = { 1, 3, 5 };
862 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb2ed9afd2007-11-29 19:09:19 +0000863 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff437b4d82007-09-12 20:13:48 +0000864 VDecl->setType(DclT);
Christopher Lamb2ed9afd2007-11-29 19:09:19 +0000865 Init->setType(DclT);
866 }
Steve Naroff61091402007-09-12 14:07:44 +0000867
868 // Attach the initializer to the decl.
Steve Naroff437b4d82007-09-12 20:13:48 +0000869 VDecl->setInit(Init);
Steve Naroff61091402007-09-12 14:07:44 +0000870 return;
871}
872
Chris Lattner776fac82007-06-09 00:53:06 +0000873/// The declarators are chained together backwards, reverse the list.
874Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
875 // Often we have single declarators, handle them quickly.
Steve Naroffa23cc792007-09-13 23:52:58 +0000876 Decl *GroupDecl = static_cast<Decl*>(group);
877 if (GroupDecl == 0)
Steve Naroff61091402007-09-12 14:07:44 +0000878 return 0;
Steve Naroffa23cc792007-09-13 23:52:58 +0000879
880 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
881 ScopedDecl *NewGroup = 0;
Steve Naroff61091402007-09-12 14:07:44 +0000882 if (Group->getNextDeclarator() == 0)
Chris Lattner776fac82007-06-09 00:53:06 +0000883 NewGroup = Group;
Steve Naroff61091402007-09-12 14:07:44 +0000884 else { // reverse the list.
885 while (Group) {
Steve Naroffa23cc792007-09-13 23:52:58 +0000886 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff61091402007-09-12 14:07:44 +0000887 Group->setNextDeclarator(NewGroup);
888 NewGroup = Group;
889 Group = Next;
890 }
891 }
892 // Perform semantic analysis that depends on having fully processed both
893 // the declarator and initializer.
Steve Naroffa23cc792007-09-13 23:52:58 +0000894 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff61091402007-09-12 14:07:44 +0000895 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
896 if (!IDecl)
897 continue;
898 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
899 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
900 QualType T = IDecl->getType();
901
902 // C99 6.7.5.2p2: If an identifier is declared to be an object with
903 // static storage duration, it shall not have a variable length array.
904 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman5c949092008-02-15 19:53:52 +0000905 if (T->getAsVariableArrayType()) {
Eli Friedmanbd258282008-02-15 18:16:39 +0000906 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
907 IDecl->setInvalidDecl();
Steve Naroff61091402007-09-12 14:07:44 +0000908 }
909 }
910 // Block scope. C99 6.7p7: If an identifier for an object is declared with
911 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
912 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
913 if (T->isIncompleteType()) {
Chris Lattner310369f2007-12-02 07:50:03 +0000914 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
915 T.getAsString());
Steve Naroff61091402007-09-12 14:07:44 +0000916 IDecl->setInvalidDecl();
917 }
918 }
919 // File scope. C99 6.9.2p2: A declaration of an identifier for and
920 // object that has file scope without an initializer, and without a
921 // storage-class specifier or with the storage-class specifier "static",
922 // constitutes a tentative definition. Note: A tentative definition with
923 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb716fba2008-01-18 00:39:39 +0000924 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
925 FVD->getStorageClass() == VarDecl::None)) {
Eli Friedman9e805b22008-02-15 12:53:51 +0000926 if (T->isIncompleteArrayType()) {
Steve Naroffacb6fa62008-01-18 20:40:52 +0000927 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
928 // array to be completed. Don't issue a diagnostic.
929 } else if (T->isIncompleteType()) {
930 // C99 6.9.2p3: If the declaration of an identifier for an object is
931 // a tentative definition and has internal linkage (C99 6.2.2p3), the
932 // declared type shall not be an incomplete type.
Chris Lattner310369f2007-12-02 07:50:03 +0000933 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
934 T.getAsString());
Steve Naroff61091402007-09-12 14:07:44 +0000935 IDecl->setInvalidDecl();
936 }
937 }
Chris Lattner776fac82007-06-09 00:53:06 +0000938 }
939 return NewGroup;
940}
Steve Naroff7e6f7c22007-08-28 03:03:08 +0000941
942// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner53621a52007-06-13 20:44:40 +0000943ParmVarDecl *
Nate Begemanf0e4a522008-02-17 21:02:04 +0000944Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI,
945 Scope *FnScope) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000946 IdentifierInfo *II = PI.Ident;
Chris Lattnerc284e9b2007-01-23 05:14:32 +0000947 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
948 // Can this happen for params? We already checked that they don't conflict
949 // among each other. Here they can only shadow globals, which is ok.
Chris Lattnerd2b88ab2007-07-13 03:05:23 +0000950 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Chris Lattner9561a0b2007-01-28 08:20:04 +0000951 PI.IdentLoc, FnScope)) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000952
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000953 }
954
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000955 // FIXME: Handle storage class (auto, register). No declarator?
Chris Lattner776fac82007-06-09 00:53:06 +0000956 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff773df5c2007-08-07 22:44:21 +0000957
958 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
959 // Doing the promotion here has a win and a loss. The win is the type for
960 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
961 // code generator). The loss is the orginal type isn't preserved. For example:
962 //
963 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
964 // int blockvardecl[5];
965 // sizeof(parmvardecl); // size == 4
966 // sizeof(blockvardecl); // size == 20
967 // }
968 //
969 // For expressions, all implicit conversions are captured using the
970 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
971 //
972 // FIXME: If a source translation tool needs to see the original type, then
973 // we need to consider storing both types (in ParmVarDecl)...
974 //
975 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattner4f203512008-01-02 22:50:48 +0000976 if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
977 // int x[restrict 4] -> int *restrict
Steve Naroff773df5c2007-08-07 22:44:21 +0000978 parmDeclType = Context.getPointerType(AT->getElementType());
Chris Lattner4f203512008-01-02 22:50:48 +0000979 parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
980 } else if (parmDeclType->isFunctionType())
Steve Naroff773df5c2007-08-07 22:44:21 +0000981 parmDeclType = Context.getPointerType(parmDeclType);
982
983 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Anders Carlsson1a841062008-02-15 07:04:12 +0000984 VarDecl::None, 0);
Anders Carlsson1a841062008-02-15 07:04:12 +0000985
Steve Naroffcf871f52007-08-28 18:45:29 +0000986 if (PI.InvalidType)
987 New->setInvalidDecl();
988
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000989 // If this has an identifier, add it to the scope stack.
990 if (II) {
Steve Naroff9324db12007-09-13 18:10:37 +0000991 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000992 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000993 FnScope->AddDecl(New);
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000994 }
Nate Begemand8c41562008-02-17 21:20:31 +0000995
996 HandleDeclAttributes(New, PI.AttrList, 0);
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000997 return New;
998}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +0000999
Chris Lattnera55a2cc2007-10-09 17:14:05 +00001000Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner229ce602006-11-21 01:21:07 +00001001 assert(CurFunctionDecl == 0 && "Function parsing confused");
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001002 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1003 "Not a function declarator!");
1004 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1005
1006 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1007 // for a K&R function.
1008 if (!FTI.hasPrototype) {
1009 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1010 if (FTI.ArgInfo[i].TypeInfo == 0) {
Chris Lattner843c5922007-06-10 23:40:34 +00001011 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001012 FTI.ArgInfo[i].Ident->getName());
1013 // Implicitly declare the argument as type 'int' for lack of a better
1014 // type.
1015 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
1016 }
1017 }
Chris Lattnerb080ed52008-02-17 19:31:09 +00001018
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001019 // Since this is a function definition, act as though we have information
1020 // about the arguments.
Chris Lattnerb080ed52008-02-17 19:31:09 +00001021 if (FTI.NumArgs)
1022 FTI.hasPrototype = true;
Chris Lattner2114d5e2006-12-04 07:40:24 +00001023 } else {
1024 // FIXME: Diagnose arguments without names in C.
1025
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001026 }
1027
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001028 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00001029
1030 // See if this is a redefinition.
1031 ScopedDecl *PrevDcl = LookupScopedDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1032 D.getIdentifierLoc(), GlobalScope);
1033 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1034 if (FD->getBody()) {
1035 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1036 D.getIdentifier()->getName());
1037 Diag(FD->getLocation(), diag::err_previous_definition);
1038 }
1039 }
Steve Naroffc1e22c72008-02-12 01:09:36 +00001040 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattner27055192008-02-16 01:20:36 +00001041 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattner229ce602006-11-21 01:21:07 +00001042 CurFunctionDecl = FD;
Chris Lattner2114d5e2006-12-04 07:40:24 +00001043
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001044 // Create Decl objects for each parameter, adding them to the FunctionDecl.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001045 llvm::SmallVector<ParmVarDecl*, 16> Params;
Chris Lattnerf61c8a82007-01-21 19:04:43 +00001046
1047 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1048 // no arguments, not a function that takes a single void argument.
1049 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner445fcab2008-02-20 20:55:12 +00001050 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getCVRQualifiers() &&
Chris Lattnerdb2a6ef2007-11-28 18:51:29 +00001051 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Chris Lattner99d31772007-01-21 22:37:37 +00001052 // empty arg list, don't push any params.
Chris Lattnerf61c8a82007-01-21 19:04:43 +00001053 } else {
Steve Naroffd0bf5162007-11-12 03:44:46 +00001054 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begeman313f8ca2007-11-13 21:49:48 +00001055 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroffd0bf5162007-11-12 03:44:46 +00001056 FnBodyScope));
1057 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00001058 }
Chris Lattner2114d5e2006-12-04 07:40:24 +00001059
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001060 FD->setParams(&Params[0], Params.size());
Chris Lattner2114d5e2006-12-04 07:40:24 +00001061
Chris Lattnere168f762006-11-10 05:29:30 +00001062 return FD;
1063}
1064
Steve Naroffb313fc32007-11-11 23:20:51 +00001065Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1066 Decl *dcl = static_cast<Decl *>(D);
1067 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1068 FD->setBody((Stmt*)Body);
1069 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroffd78c81b2007-12-13 18:18:56 +00001070 CurFunctionDecl = 0;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001071 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffb313fc32007-11-11 23:20:51 +00001072 MD->setBody((Stmt*)Body);
Steve Naroffe3d1ab22007-11-12 13:56:41 +00001073 CurMethodDecl = 0;
Steve Naroffd78c81b2007-12-13 18:18:56 +00001074 }
Chris Lattnere2473062007-05-28 06:28:18 +00001075 // Verify and clean out per-function state.
1076
1077 // Check goto/label use.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001078 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1079 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
Chris Lattnere2473062007-05-28 06:28:18 +00001080 // Verify that we have no forward references left. If so, there was a goto
1081 // or address of a label taken, but no definition of it. Label fwd
1082 // definitions are indicated with a null substmt.
1083 if (I->second->getSubStmt() == 0) {
1084 LabelStmt *L = I->second;
1085 // Emit error.
Chris Lattnereefa10e2007-05-28 06:56:27 +00001086 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
Chris Lattnere2473062007-05-28 06:28:18 +00001087
1088 // At this point, we have gotos that use the bogus label. Stitch it into
1089 // the function body so that they aren't leaked and that the AST is well
1090 // formed.
Chris Lattner3efff542008-01-25 00:01:10 +00001091 if (Body) {
1092 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1093 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1094 } else {
1095 // The whole function wasn't parsed correctly, just delete this.
1096 delete L;
1097 }
Chris Lattnere2473062007-05-28 06:28:18 +00001098 }
1099 }
1100 LabelMap.clear();
1101
Steve Naroffb313fc32007-11-11 23:20:51 +00001102 return D;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00001103}
1104
Chris Lattnerac18be92006-11-20 06:49:47 +00001105/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1106/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff2f742082007-09-16 16:16:00 +00001107ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1108 IdentifierInfo &II, Scope *S) {
Chris Lattnerac18be92006-11-20 06:49:47 +00001109 if (getLangOptions().C99) // Extension in C99.
1110 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1111 else // Legal in C90, but warn about it.
1112 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1113
1114 // FIXME: handle stuff like:
1115 // void foo() { extern float X(); }
1116 // void bar() { X(); } <-- implicit decl for X in another scope.
1117
1118 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00001119 const char *Dummy;
Chris Lattnerac18be92006-11-20 06:49:47 +00001120 DeclSpec DS;
Chris Lattnerb20e8942006-11-28 05:30:29 +00001121 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001122 Error = Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00001123 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00001124 Declarator D(DS, Declarator::BlockContext);
Chris Lattnercbc426d2006-12-02 06:43:02 +00001125 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
Chris Lattnerac18be92006-11-20 06:49:47 +00001126 D.SetIdentifier(&II, Loc);
1127
Chris Lattner62d2e662007-01-28 00:21:37 +00001128 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001129 if (Scope *FnS = S->getFnParent())
1130 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner62d2e662007-01-28 00:21:37 +00001131 while (S->getParent())
1132 S = S->getParent();
Chris Lattnerac18be92006-11-20 06:49:47 +00001133
Steve Naroff2f742082007-09-16 16:16:00 +00001134 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattnerac18be92006-11-20 06:49:47 +00001135}
1136
Chris Lattner302b4be2006-11-19 02:31:38 +00001137
Chris Lattner07b201d2007-11-14 06:34:38 +00001138TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroffa23cc792007-09-13 23:52:58 +00001139 ScopedDecl *LastDeclarator) {
Chris Lattner776fac82007-06-09 00:53:06 +00001140 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00001141 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001142
Chris Lattner18b19622007-01-22 07:39:13 +00001143 // Scope manipulation handled by caller.
Steve Narofff93b6722007-08-28 20:14:24 +00001144 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
1145 T, LastDeclarator);
1146 if (D.getInvalidType())
1147 NewTD->setInvalidDecl();
1148 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00001149}
1150
Steve Naroff30d242c2007-09-15 18:49:24 +00001151/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00001152/// former case, Name will be non-null. In the later case, Name will be null.
1153/// TagType indicates what kind of tag this is. TK indicates whether this is a
1154/// reference/declaration/definition of a tag.
Steve Naroff30d242c2007-09-15 18:49:24 +00001155Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001156 SourceLocation KWLoc, IdentifierInfo *Name,
Steve Naroffb3096442007-06-09 03:47:53 +00001157 SourceLocation NameLoc, AttributeList *Attr) {
Chris Lattner8799cf22007-01-23 01:57:16 +00001158 // If this is a use of an existing tag, it must have a name.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001159 assert((Name != 0 || TK == TK_Definition) &&
1160 "Nameless record must be a definition!");
Chris Lattner8799cf22007-01-23 01:57:16 +00001161
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001162 Decl::Kind Kind;
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001163 switch (TagType) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001164 default: assert(0 && "Unknown tag type!");
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001165 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1166 case DeclSpec::TST_union: Kind = Decl::Union; break;
1167//case DeclSpec::TST_class: Kind = Decl::Class; break;
1168 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001169 }
Chris Lattner7e783a12007-01-23 02:05:42 +00001170
Chris Lattner18b19622007-01-22 07:39:13 +00001171 // If this is a named struct, check to see if there was a previous forward
1172 // declaration or definition.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001173 if (TagDecl *PrevDecl =
Chris Lattner9561a0b2007-01-28 08:20:04 +00001174 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1175 NameLoc, S))) {
Chris Lattner8799cf22007-01-23 01:57:16 +00001176
1177 // If this is a use of a previous tag, or if the tag is already declared in
1178 // the same scope (so that the definition/declaration completes or
1179 // rementions the tag), reuse the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001180 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
Chris Lattner7e783a12007-01-23 02:05:42 +00001181 // Make sure that this wasn't declared as an enum and now used as a struct
1182 // or something similar.
1183 if (PrevDecl->getKind() != Kind) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001184 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
Chris Lattner7e783a12007-01-23 02:05:42 +00001185 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1186 }
Chris Lattner7b9ace62007-01-23 20:11:08 +00001187
1188 // If this is a use or a forward declaration, we're good.
1189 if (TK != TK_Definition)
1190 return PrevDecl;
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001191
Chris Lattner7b9ace62007-01-23 20:11:08 +00001192 // Diagnose attempts to redefine a tag.
1193 if (PrevDecl->isDefinition()) {
1194 Diag(NameLoc, diag::err_redefinition, Name->getName());
1195 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1196 // If this is a redefinition, recover by making this struct be
1197 // anonymous, which will make any later references get the previous
1198 // definition.
1199 Name = 0;
1200 } else {
1201 // Okay, this is definition of a previously declared or referenced tag.
1202 // Move the location of the decl to be the definition site.
1203 PrevDecl->setLocation(NameLoc);
Chris Lattner7b9ace62007-01-23 20:11:08 +00001204 return PrevDecl;
1205 }
Chris Lattner8799cf22007-01-23 01:57:16 +00001206 }
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001207 // If we get here, this is a definition of a new struct type in a nested
1208 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1209 // type.
Chris Lattner18b19622007-01-22 07:39:13 +00001210 }
1211
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001212 // If there is an identifier, use the location of the identifier as the
1213 // location of the decl, otherwise use the location of the struct/union
1214 // keyword.
1215 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1216
Chris Lattner18b19622007-01-22 07:39:13 +00001217 // Otherwise, if this is the first time we've seen this tag, create the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001218 TagDecl *New;
Chris Lattner720a0542007-01-25 00:44:24 +00001219 switch (Kind) {
1220 default: assert(0 && "Unknown tag kind!");
Chris Lattner5f521502007-01-25 06:27:24 +00001221 case Decl::Enum:
Chris Lattner776fac82007-06-09 00:53:06 +00001222 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1223 // enum X { A, B, C } D; D should chain to X.
1224 New = new EnumDecl(Loc, Name, 0);
Chris Lattner5f521502007-01-25 06:27:24 +00001225 // If this is an undefined enum, warn.
Chris Lattnerc1915e22007-01-25 07:29:02 +00001226 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Chris Lattner5f521502007-01-25 06:27:24 +00001227 break;
Chris Lattner720a0542007-01-25 00:44:24 +00001228 case Decl::Union:
1229 case Decl::Struct:
1230 case Decl::Class:
Chris Lattner776fac82007-06-09 00:53:06 +00001231 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1232 // struct X { int A; } D; D should chain to X.
1233 New = new RecordDecl(Kind, Loc, Name, 0);
Chris Lattner720a0542007-01-25 00:44:24 +00001234 break;
1235 }
Chris Lattner18b19622007-01-22 07:39:13 +00001236
1237 // If this has an identifier, add it to the scope stack.
1238 if (Name) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001239 // The scope passed in may not be a decl scope. Zip up the scope tree until
1240 // we find one that is.
1241 while ((S->getFlags() & Scope::DeclScope) == 0)
1242 S = S->getParent();
1243
1244 // Add it to the decl chain.
Steve Naroff9324db12007-09-13 18:10:37 +00001245 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner18b19622007-01-22 07:39:13 +00001246 Name->setFETokenInfo(New);
1247 S->AddDecl(New);
1248 }
Chris Lattner622c1932008-02-06 00:51:33 +00001249
Anders Carlsson28e71082008-02-16 00:29:18 +00001250 HandleDeclAttributes(New, Attr, 0);
Chris Lattner18b19622007-01-22 07:39:13 +00001251 return New;
1252}
Chris Lattner1300fb92007-01-23 23:42:53 +00001253
Steve Naroff30d242c2007-09-15 18:49:24 +00001254/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00001255/// to create a FieldDecl object for it.
Steve Naroff30d242c2007-09-15 18:49:24 +00001256Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Chris Lattner1300fb92007-01-23 23:42:53 +00001257 SourceLocation DeclStart,
1258 Declarator &D, ExprTy *BitfieldWidth) {
1259 IdentifierInfo *II = D.getIdentifier();
1260 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner1300fb92007-01-23 23:42:53 +00001261 SourceLocation Loc = DeclStart;
1262 if (II) Loc = D.getIdentifierLoc();
1263
Chris Lattner62d2e662007-01-28 00:21:37 +00001264 // FIXME: Unnamed fields can be handled in various different ways, for
1265 // example, unnamed unions inject all members into the struct namespace!
1266
1267
Chris Lattner1300fb92007-01-23 23:42:53 +00001268 if (BitWidth) {
1269 // TODO: Validate.
Steve Narofff84d11f2007-05-23 21:48:04 +00001270 //printf("WARNING: BITFIELDS IGNORED!\n");
Chris Lattner1300fb92007-01-23 23:42:53 +00001271
1272 // 6.7.2.1p3
1273 // 6.7.2.1p4
1274
1275 } else {
1276 // Not a bitfield.
1277
1278 // validate II.
1279
1280 }
1281
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001282 QualType T = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +00001283 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1284 bool InvalidDecl = false;
Steve Naroff096dd942007-08-31 17:20:07 +00001285
Steve Naroff8eeeb132007-05-08 21:09:37 +00001286 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1287 // than a variably modified type.
Eli Friedman9e805b22008-02-15 12:53:51 +00001288 if (T->isVariablyModifiedType()) {
1289 // FIXME: This diagnostic needs work
1290 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroff096dd942007-08-31 17:20:07 +00001291 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +00001292 }
Chris Lattner776fac82007-06-09 00:53:06 +00001293 // FIXME: Chain fielddecls together.
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001294 FieldDecl *NewFD;
1295
1296 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patel32714062007-11-01 16:29:56 +00001297 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001298 else if (isa<ObjCInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1299 isa<ObjCImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
1300 isa<ObjCCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroff9e0887cf2007-11-14 14:15:31 +00001301 // FIXME: ivars are currently used to model properties, and
1302 // properties can appear within a protocol.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001303 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1304 isa<ObjCProtocolDecl>(static_cast<Decl *>(TagDecl)))
1305 NewFD = new ObjCIvarDecl(Loc, II, T);
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001306 else
Steve Naroff30d242c2007-09-15 18:49:24 +00001307 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001308
Anders Carlsson28e71082008-02-16 00:29:18 +00001309 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1310 D.getAttributes());
1311
Steve Narofff93b6722007-08-28 20:14:24 +00001312 if (D.getInvalidType() || InvalidDecl)
1313 NewFD->setInvalidDecl();
1314 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00001315}
1316
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001317/// TranslateIvarVisibility - Translate visibility from a token ID to an
1318/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001319static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001320TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00001321 switch (ivarVisibility) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001322 case tok::objc_private: return ObjCIvarDecl::Private;
1323 case tok::objc_public: return ObjCIvarDecl::Public;
1324 case tok::objc_protected: return ObjCIvarDecl::Protected;
1325 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001326 default: assert(false && "Unknown visitibility kind");
Steve Naroff2e688fd2007-09-14 23:09:53 +00001327 }
1328}
1329
Fariborz Jahanian343f7092007-09-29 00:54:24 +00001330void Sema::ActOnFields(Scope* S,
Fariborz Jahanian67341402007-10-04 00:45:27 +00001331 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff30d242c2007-09-15 18:49:24 +00001332 DeclTy **Fields, unsigned NumFields,
Steve Naroff33a1e802007-10-29 21:38:07 +00001333 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff30d242c2007-09-15 18:49:24 +00001334 tok::ObjCKeywordKind *visibility) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00001335 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1336 assert(EnclosingDecl && "missing record or interface decl");
1337 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1338
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001339 if (Record && Record->isDefinition()) {
Chris Lattner1300fb92007-01-23 23:42:53 +00001340 // Diagnose code like:
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001341 // struct S { struct S {} X; };
Chris Lattner1300fb92007-01-23 23:42:53 +00001342 // We discover this when we complete the outer S. Reject and ignore the
1343 // outer S.
1344 Diag(Record->getLocation(), diag::err_nested_redefinition,
1345 Record->getKindName());
1346 Diag(RecLoc, diag::err_previous_definition);
Steve Naroffdb47ee22007-09-14 22:20:54 +00001347 Record->setInvalidDecl();
Chris Lattner1300fb92007-01-23 23:42:53 +00001348 return;
1349 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001350 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00001351 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +00001352 llvm::SmallVector<FieldDecl*, 32> RecFields;
1353 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroffdb47ee22007-09-14 22:20:54 +00001354
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001355 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001356
Steve Naroffdb47ee22007-09-14 22:20:54 +00001357 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1358 assert(FD && "missing field decl");
1359
1360 // Remember all fields.
1361 RecFields.push_back(FD);
Chris Lattner720a0542007-01-25 00:44:24 +00001362
1363 // Get the type for the field.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001364 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner720a0542007-01-25 00:44:24 +00001365
Steve Naroff2e688fd2007-09-14 23:09:53 +00001366 // If we have visibility info, make sure the AST is set accordingly.
1367 if (visibility)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001368 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001369 TranslateIvarVisibility(visibility[i]));
Steve Naroff2e688fd2007-09-14 23:09:53 +00001370
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001371 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001372 if (FDTy->isFunctionType()) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00001373 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001374 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001375 FD->setInvalidDecl();
1376 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001377 continue;
1378 }
Chris Lattner82625602007-01-24 02:26:21 +00001379 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
Chris Lattner720a0542007-01-25 00:44:24 +00001380 if (FDTy->isIncompleteType()) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001381 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian67341402007-10-04 00:45:27 +00001382 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001383 FD->setInvalidDecl();
1384 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian67341402007-10-04 00:45:27 +00001385 continue;
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001386 }
Chris Lattner82625602007-01-24 02:26:21 +00001387 if (i != NumFields-1 || // ... that the last member ...
1388 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner0fd893e2007-07-31 21:33:24 +00001389 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner82625602007-01-24 02:26:21 +00001390 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001391 FD->setInvalidDecl();
1392 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00001393 continue;
1394 }
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001395 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner82625602007-01-24 02:26:21 +00001396 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1397 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001398 FD->setInvalidDecl();
1399 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00001400 continue;
1401 }
Chris Lattner720a0542007-01-25 00:44:24 +00001402 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001403 if (Record)
1404 Record->setHasFlexibleArrayMember(true);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001405 }
Chris Lattner720a0542007-01-25 00:44:24 +00001406 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1407 /// field of another structure or the element of an array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001408 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner720a0542007-01-25 00:44:24 +00001409 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1410 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001411 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner41943152007-01-25 04:52:46 +00001412 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00001413 } else {
1414 // If this is a struct/class and this is not the last element, reject
1415 // it. Note that GCC supports variable sized arrays in the middle of
1416 // structures.
1417 if (i != NumFields-1) {
1418 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1419 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001420 FD->setInvalidDecl();
1421 EnclosingDecl->setInvalidDecl();
Chris Lattner720a0542007-01-25 00:44:24 +00001422 continue;
1423 }
Chris Lattner720a0542007-01-25 00:44:24 +00001424 // We support flexible arrays at the end of structs in other structs
1425 // as an extension.
1426 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1427 FD->getName());
Fariborz Jahanian67341402007-10-04 00:45:27 +00001428 if (Record)
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001429 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00001430 }
1431 }
1432 }
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00001433 /// A field cannot be an Objective-c object
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001434 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00001435 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1436 FD->getName());
1437 FD->setInvalidDecl();
1438 EnclosingDecl->setInvalidDecl();
1439 continue;
1440 }
Chris Lattner82625602007-01-24 02:26:21 +00001441 // Keep track of the number of named members.
Chris Lattnere5a66562007-01-25 22:48:42 +00001442 if (IdentifierInfo *II = FD->getIdentifier()) {
1443 // Detect duplicate member names.
Chris Lattnerbaf33662007-01-27 02:14:08 +00001444 if (!FieldIDs.insert(II)) {
Chris Lattnere5a66562007-01-25 22:48:42 +00001445 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1446 // Find the previous decl.
1447 SourceLocation PrevLoc;
1448 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1449 assert(i != e && "Didn't find previous def!");
1450 if (RecFields[i]->getIdentifier() == II) {
1451 PrevLoc = RecFields[i]->getLocation();
1452 break;
1453 }
1454 }
1455 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroffdb47ee22007-09-14 22:20:54 +00001456 FD->setInvalidDecl();
1457 EnclosingDecl->setInvalidDecl();
Chris Lattnere5a66562007-01-25 22:48:42 +00001458 continue;
1459 }
Chris Lattner82625602007-01-24 02:26:21 +00001460 ++NumNamedMembers;
Chris Lattnere5a66562007-01-25 22:48:42 +00001461 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001462 }
Chris Lattner82625602007-01-24 02:26:21 +00001463
Chris Lattner82625602007-01-24 02:26:21 +00001464 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +00001465 if (Record) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001466 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattner622c1932008-02-06 00:51:33 +00001467 Consumer.HandleTagDeclDefinition(Record);
1468 } else {
Chris Lattner9413a012008-02-05 22:40:55 +00001469 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1470 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1471 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1472 else if (ObjCImplementationDecl *IMPDecl =
1473 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001474 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1475 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian95b60762007-10-31 18:48:14 +00001476 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00001477 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00001478 }
Chris Lattner1300fb92007-01-23 23:42:53 +00001479}
1480
Steve Naroff30d242c2007-09-15 18:49:24 +00001481Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4ef40012007-06-11 01:28:17 +00001482 DeclTy *lastEnumConst,
Chris Lattnerc1915e22007-01-25 07:29:02 +00001483 SourceLocation IdLoc, IdentifierInfo *Id,
Chris Lattner4ef40012007-06-11 01:28:17 +00001484 SourceLocation EqualLoc, ExprTy *val) {
1485 theEnumDecl = theEnumDecl; // silence unused warning.
1486 EnumConstantDecl *LastEnumConst =
1487 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1488 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00001489
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001490 // The scope passed in may not be a decl scope. Zip up the scope tree until
1491 // we find one that is.
1492 while ((S->getFlags() & Scope::DeclScope) == 0)
1493 S = S->getParent();
1494
Chris Lattner8116d1b2007-01-25 22:38:29 +00001495 // Verify that there isn't already something declared with this name in this
1496 // scope.
Steve Naroff9def2b12007-09-13 21:41:19 +00001497 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1498 IdLoc, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00001499 if (S->isDeclScope(PrevDecl)) {
1500 if (isa<EnumConstantDecl>(PrevDecl))
1501 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1502 else
1503 Diag(IdLoc, diag::err_redefinition, Id->getName());
1504 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner77683132008-02-26 00:33:57 +00001505 delete Val;
Chris Lattner8116d1b2007-01-25 22:38:29 +00001506 return 0;
1507 }
1508 }
Chris Lattner4ef40012007-06-11 01:28:17 +00001509
Chris Lattner23b7eb62007-06-15 23:05:46 +00001510 llvm::APSInt EnumVal(32);
Chris Lattner4ef40012007-06-11 01:28:17 +00001511 QualType EltTy;
1512 if (Val) {
Chris Lattner0515e4b2007-08-27 21:16:18 +00001513 // Make sure to promote the operand type to int.
1514 UsualUnaryConversions(Val);
1515
Chris Lattner4ef40012007-06-11 01:28:17 +00001516 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1517 SourceLocation ExpLoc;
Chris Lattner0e9d6222007-07-15 23:26:56 +00001518 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Chris Lattner4ef40012007-06-11 01:28:17 +00001519 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1520 Id->getName());
Chris Lattner77683132008-02-26 00:33:57 +00001521 delete Val;
Chris Lattnerf283a372007-08-27 17:37:24 +00001522 Val = 0; // Just forget about it.
Chris Lattnerc92bc4c2007-08-29 16:03:41 +00001523 } else {
1524 EltTy = Val->getType();
Chris Lattner4ef40012007-06-11 01:28:17 +00001525 }
Chris Lattnerf283a372007-08-27 17:37:24 +00001526 }
1527
1528 if (!Val) {
1529 if (LastEnumConst) {
1530 // Assign the last value + 1.
1531 EnumVal = LastEnumConst->getInitVal();
1532 ++EnumVal;
Chris Lattner0515e4b2007-08-27 21:16:18 +00001533
1534 // Check for overflow on increment.
1535 if (EnumVal < LastEnumConst->getInitVal())
1536 Diag(IdLoc, diag::warn_enum_value_overflow);
1537
Chris Lattnerf283a372007-08-27 17:37:24 +00001538 EltTy = LastEnumConst->getType();
1539 } else {
1540 // First value, set to zero.
1541 EltTy = Context.IntTy;
Chris Lattner9cf21c52007-09-04 02:45:27 +00001542 EnumVal.zextOrTrunc(
1543 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerf283a372007-08-27 17:37:24 +00001544 }
Steve Naroff63969212007-05-07 21:22:42 +00001545 }
Chris Lattner4ef40012007-06-11 01:28:17 +00001546
Chris Lattner4ef40012007-06-11 01:28:17 +00001547 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1548 LastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +00001549
1550 // Register this decl in the current scope stack.
Steve Naroff9324db12007-09-13 18:10:37 +00001551 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner8116d1b2007-01-25 22:38:29 +00001552 Id->setFETokenInfo(New);
1553 S->AddDecl(New);
1554 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001555}
1556
Steve Naroff30d242c2007-09-15 18:49:24 +00001557void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattnerc1915e22007-01-25 07:29:02 +00001558 DeclTy **Elements, unsigned NumElements) {
1559 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1560 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1561
Chris Lattner67933c02007-08-28 05:10:31 +00001562 // TODO: If the result value doesn't fit in an int, it must be a long or long
1563 // long value. ISO C does not support this, but GCC does as an extension,
1564 // emit a warning.
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001565 unsigned IntWidth =
1566 Context.Target.getIntWidth(Context.getFullLoc(Enum->getLocation()));
Chris Lattner67933c02007-08-28 05:10:31 +00001567
1568
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001569 // Verify that all the values are okay, compute the size of the values, and
1570 // reverse the list.
1571 unsigned NumNegativeBits = 0;
1572 unsigned NumPositiveBits = 0;
1573
1574 // Keep track of whether all elements have type int.
1575 bool AllElementsInt = true;
1576
Chris Lattner4ef40012007-06-11 01:28:17 +00001577 EnumConstantDecl *EltList = 0;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001578 for (unsigned i = 0; i != NumElements; ++i) {
1579 EnumConstantDecl *ECD =
1580 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1581 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnerbf478cb2007-08-28 05:27:00 +00001582
1583 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnerbf478cb2007-08-28 05:27:00 +00001584 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner77683132008-02-26 00:33:57 +00001585 assert(InitVal.getBitWidth() >= IntWidth &&
1586 "Should have promoted value to int");
Chris Lattnerbf478cb2007-08-28 05:27:00 +00001587 if (InitVal.getBitWidth() > IntWidth) {
1588 llvm::APSInt V(InitVal);
1589 V.trunc(IntWidth);
1590 V.extend(InitVal.getBitWidth());
1591 if (V != InitVal)
1592 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1593 InitVal.toString());
1594 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001595
1596 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +00001597 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +00001598 NumPositiveBits = std::max(NumPositiveBits,
1599 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001600 else
Chris Lattner49f980c2008-01-14 21:47:29 +00001601 NumNegativeBits = std::max(NumNegativeBits,
1602 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00001603
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001604 // Keep track of whether every enum element has type int (very commmon).
1605 if (AllElementsInt)
1606 AllElementsInt = ECD->getType() == Context.IntTy;
1607
Chris Lattner4ef40012007-06-11 01:28:17 +00001608 ECD->setNextDeclarator(EltList);
1609 EltList = ECD;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001610 }
1611
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001612 // Figure out the type that should be used for this enum.
1613 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1614 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001615 unsigned BestWidth;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001616
1617 if (NumNegativeBits) {
1618 // If there is a negative value, figure out the smallest integer type (of
1619 // int/long/longlong) that fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001620 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001621 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001622 BestWidth = IntWidth;
1623 } else {
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001624 BestWidth =
1625 Context.Target.getLongWidth(Context.getFullLoc(Enum->getLocation()));
1626
Chris Lattner3a370bf2007-08-29 17:31:48 +00001627 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001628 BestType = Context.LongTy;
1629 else {
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001630 BestWidth = Context.Target.getLongLongWidth(
1631 Context.getFullLoc(Enum->getLocation()));
1632
Chris Lattner3a370bf2007-08-29 17:31:48 +00001633 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001634 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1635 BestType = Context.LongLongTy;
1636 }
1637 }
1638 } else {
1639 // If there is no negative value, figure out which of uint, ulong, ulonglong
1640 // fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001641 if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001642 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001643 BestWidth = IntWidth;
1644 } else if (NumPositiveBits <=
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001645 (BestWidth = Context.Target.getLongWidth(
1646 Context.getFullLoc(Enum->getLocation()))))
1647
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001648 BestType = Context.UnsignedLongTy;
1649 else {
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001650 BestWidth =
1651 Context.Target.getLongLongWidth(Context.getFullLoc(Enum->getLocation()));
1652
Chris Lattner3a370bf2007-08-29 17:31:48 +00001653 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001654 "How could an initializer get larger than ULL?");
1655 BestType = Context.UnsignedLongLongTy;
1656 }
1657 }
1658
Chris Lattner3a370bf2007-08-29 17:31:48 +00001659 // Loop over all of the enumerator constants, changing their types to match
1660 // the type of the enum if needed.
1661 for (unsigned i = 0; i != NumElements; ++i) {
1662 EnumConstantDecl *ECD =
1663 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1664 if (!ECD) continue; // Already issued a diagnostic.
1665
1666 // Standard C says the enumerators have int type, but we allow, as an
1667 // extension, the enumerators to be larger than int size. If each
1668 // enumerator value fits in an int, type it as an int, otherwise type it the
1669 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1670 // that X has type 'int', not 'unsigned'.
Chris Lattner77683132008-02-26 00:33:57 +00001671 if (ECD->getType() == Context.IntTy) {
1672 // Make sure the init value is signed.
1673 llvm::APSInt IV = ECD->getInitVal();
1674 IV.setIsSigned(true);
1675 ECD->setInitVal(IV);
Chris Lattner3a370bf2007-08-29 17:31:48 +00001676 continue; // Already int type.
Chris Lattner77683132008-02-26 00:33:57 +00001677 }
Chris Lattner3a370bf2007-08-29 17:31:48 +00001678
1679 // Determine whether the value fits into an int.
1680 llvm::APSInt InitVal = ECD->getInitVal();
1681 bool FitsInInt;
1682 if (InitVal.isUnsigned() || !InitVal.isNegative())
1683 FitsInInt = InitVal.getActiveBits() < IntWidth;
1684 else
1685 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1686
1687 // If it fits into an integer type, force it. Otherwise force it to match
1688 // the enum decl type.
1689 QualType NewTy;
1690 unsigned NewWidth;
1691 bool NewSign;
1692 if (FitsInInt) {
1693 NewTy = Context.IntTy;
1694 NewWidth = IntWidth;
1695 NewSign = true;
1696 } else if (ECD->getType() == BestType) {
1697 // Already the right type!
1698 continue;
1699 } else {
1700 NewTy = BestType;
1701 NewWidth = BestWidth;
1702 NewSign = BestType->isSignedIntegerType();
1703 }
1704
1705 // Adjust the APSInt value.
1706 InitVal.extOrTrunc(NewWidth);
1707 InitVal.setIsSigned(NewSign);
1708 ECD->setInitVal(InitVal);
1709
1710 // Adjust the Expr initializer and type.
1711 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1712 ECD->setType(NewTy);
1713 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001714
Chris Lattner1c1f9322007-08-28 18:24:31 +00001715 Enum->defineElements(EltList, BestType);
Chris Lattner622c1932008-02-06 00:51:33 +00001716 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +00001717}
Chris Lattner1300fb92007-01-23 23:42:53 +00001718
Anders Carlsson5c6c0592008-02-08 00:33:21 +00001719Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1720 ExprTy *expr) {
1721 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1722
1723 return new FileScopeAsmDecl(Loc, AsmString);
1724}
1725
Chris Lattner38376f12008-01-12 07:05:38 +00001726Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnereb85ab42008-02-25 21:04:36 +00001727 SourceLocation LBrace,
1728 SourceLocation RBrace,
1729 const char *Lang,
1730 unsigned StrSize,
1731 DeclTy *D) {
Chris Lattner38376f12008-01-12 07:05:38 +00001732 LinkageSpecDecl::LanguageIDs Language;
1733 Decl *dcl = static_cast<Decl *>(D);
1734 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1735 Language = LinkageSpecDecl::lang_c;
1736 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1737 Language = LinkageSpecDecl::lang_cxx;
1738 else {
1739 Diag(Loc, diag::err_bad_language);
1740 return 0;
1741 }
1742
1743 // FIXME: Add all the various semantics of linkage specifications
1744 return new LinkageSpecDecl(Loc, Language, dcl);
1745}
1746
Chris Lattneree0d2712008-02-21 00:48:22 +00001747void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson081f1b42007-12-19 06:16:30 +00001748
Chris Lattneree0d2712008-02-21 00:48:22 +00001749 switch (Attr->getKind()) {
Chris Lattnerf1791902008-02-20 23:17:35 +00001750 case AttributeList::AT_vector_size:
Steve Naroffa8fd9732007-06-11 00:35:03 +00001751 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattneree0d2712008-02-21 00:48:22 +00001752 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001753 if (!newType.isNull()) // install the new vector type into the decl
1754 vDecl->setType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001755 }
1756 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001757 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattneree0d2712008-02-21 00:48:22 +00001758 Attr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001759 if (!newType.isNull()) // install the new vector type into the decl
1760 tDecl->setUnderlyingType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001761 }
Chris Lattnerf1791902008-02-20 23:17:35 +00001762 break;
1763 case AttributeList::AT_ocu_vector_type:
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001764 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Chris Lattneree0d2712008-02-21 00:48:22 +00001765 HandleOCUVectorTypeAttribute(tDecl, Attr);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001766 else
Chris Lattneree0d2712008-02-21 00:48:22 +00001767 Diag(Attr->getLoc(),
Steve Naroff91fcddb2007-07-18 18:00:27 +00001768 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattnerf1791902008-02-20 23:17:35 +00001769 break;
1770 case AttributeList::AT_address_space:
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001771 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1772 QualType newType = HandleAddressSpaceTypeAttribute(
1773 tDecl->getUnderlyingType(),
Chris Lattneree0d2712008-02-21 00:48:22 +00001774 Attr);
1775 tDecl->setUnderlyingType(newType);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001776 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1777 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattneree0d2712008-02-21 00:48:22 +00001778 Attr);
1779 // install the new addr spaced type into the decl
1780 vDecl->setType(newType);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001781 }
Chris Lattnerf1791902008-02-20 23:17:35 +00001782 break;
Chris Lattner8a8558b2008-02-29 16:48:43 +00001783 case AttributeList::AT_deprecated:
1784 New->addAttr(new DeprecatedAttr());
1785 break;
Chris Lattnerf1791902008-02-20 23:17:35 +00001786 case AttributeList::AT_aligned:
Chris Lattneree0d2712008-02-21 00:48:22 +00001787 HandleAlignedAttribute(New, Attr);
Chris Lattnerf1791902008-02-20 23:17:35 +00001788 break;
1789 case AttributeList::AT_packed:
Chris Lattneree0d2712008-02-21 00:48:22 +00001790 HandlePackedAttribute(New, Attr);
Chris Lattnerf1791902008-02-20 23:17:35 +00001791 break;
Nate Begemand45d38d2008-02-21 19:30:49 +00001792 case AttributeList::AT_annotate:
1793 HandleAnnotateAttribute(New, Attr);
1794 break;
Ted Kremenekf7146ca2008-02-27 20:43:06 +00001795 case AttributeList::AT_noreturn:
1796 HandleNoReturnAttribute(New, Attr);
1797 break;
Chris Lattnerf1791902008-02-20 23:17:35 +00001798 default:
Chris Lattner8a8558b2008-02-29 16:48:43 +00001799#if 0
1800 // TODO: when we have the full set of attributes, warn about unknown ones.
1801 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1802 Attr->getName()->getName());
1803#endif
Chris Lattnerf1791902008-02-20 23:17:35 +00001804 break;
1805 }
Steve Naroffa8fd9732007-06-11 00:35:03 +00001806}
1807
1808void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1809 AttributeList *declarator_postfix) {
1810 while (declspec_prefix) {
1811 HandleDeclAttribute(New, declspec_prefix);
1812 declspec_prefix = declspec_prefix->getNext();
1813 }
1814 while (declarator_postfix) {
1815 HandleDeclAttribute(New, declarator_postfix);
1816 declarator_postfix = declarator_postfix->getNext();
1817 }
1818}
1819
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001820void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1821 AttributeList *rawAttr) {
1822 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson721f6012007-12-19 07:19:40 +00001823 // check the attribute arguments.
Steve Naroff91fcddb2007-07-18 18:00:27 +00001824 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001825 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff91fcddb2007-07-18 18:00:27 +00001826 std::string("1"));
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001827 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001828 }
1829 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1830 llvm::APSInt vecSize(32);
1831 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001832 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson6e3ace52008-02-16 19:51:27 +00001833 "ocu_vector_type", sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001834 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001835 }
1836 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1837 // in conjunction with complex types (pointers, arrays, functions, etc.).
1838 Type *canonType = curType.getCanonicalType().getTypePtr();
1839 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001840 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff91fcddb2007-07-18 18:00:27 +00001841 curType.getCanonicalType().getAsString());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001842 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001843 }
1844 // unlike gcc's vector_size attribute, the size is specified as the
1845 // number of elements, not the number of bytes.
Chris Lattner9cf21c52007-09-04 02:45:27 +00001846 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001847
1848 if (vectorSize == 0) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001849 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff91fcddb2007-07-18 18:00:27 +00001850 sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001851 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001852 }
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001853 // Instantiate/Install the vector type, the number of elements is > 0.
1854 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1855 // Remember this typedef decl, we will need it later for diagnostics.
1856 OCUVectorDecls.push_back(tDecl);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001857}
1858
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001859QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattner983a8bb2007-07-13 22:13:22 +00001860 AttributeList *rawAttr) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001861 // check the attribute arugments.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001862 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001863 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroffa8fd9732007-06-11 00:35:03 +00001864 std::string("1"));
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001865 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001866 }
1867 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
Chris Lattner23b7eb62007-06-15 23:05:46 +00001868 llvm::APSInt vecSize(32);
Chris Lattner0e9d6222007-07-15 23:26:56 +00001869 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001870 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson6e3ace52008-02-16 19:51:27 +00001871 "vector_size", sizeExpr->getSourceRange());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001872 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001873 }
1874 // navigate to the base type - we need to provide for vector pointers,
1875 // vector arrays, and functions returning vectors.
1876 Type *canonType = curType.getCanonicalType().getTypePtr();
1877
Steve Naroff91fcddb2007-07-18 18:00:27 +00001878 if (canonType->isPointerType() || canonType->isArrayType() ||
1879 canonType->isFunctionType()) {
Chris Lattner0f8a39c2007-12-19 05:38:06 +00001880 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff91fcddb2007-07-18 18:00:27 +00001881 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1882 do {
1883 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1884 canonType = PT->getPointeeType().getTypePtr();
1885 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1886 canonType = AT->getElementType().getTypePtr();
1887 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1888 canonType = FT->getResultType().getTypePtr();
1889 } while (canonType->isPointerType() || canonType->isArrayType() ||
1890 canonType->isFunctionType());
1891 */
Steve Naroffa8fd9732007-06-11 00:35:03 +00001892 }
1893 // the base type must be integer or float.
1894 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001895 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroffa8fd9732007-06-11 00:35:03 +00001896 curType.getCanonicalType().getAsString());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001897 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001898 }
Chris Lattner9cf21c52007-09-04 02:45:27 +00001899 unsigned typeSize = static_cast<unsigned>(
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001900 Context.getTypeSize(curType, rawAttr->getLoc()));
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001901 // vecSize is specified in bytes - convert to bits.
Chris Lattner9cf21c52007-09-04 02:45:27 +00001902 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001903
1904 // the vector size needs to be an integral multiple of the type size.
1905 if (vectorSize % typeSize) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001906 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001907 sizeExpr->getSourceRange());
1908 return QualType();
1909 }
1910 if (vectorSize == 0) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001911 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001912 sizeExpr->getSourceRange());
1913 return QualType();
1914 }
Nate Begemand45d38d2008-02-21 19:30:49 +00001915 // Instantiate the vector type, the number of elements is > 0, and not
1916 // required to be a power of 2, unlike GCC.
Steve Naroff91fcddb2007-07-18 18:00:27 +00001917 return Context.getVectorType(curType, vectorSize/typeSize);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001918}
1919
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001920void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlsson28e71082008-02-16 00:29:18 +00001921 // check the attribute arguments.
1922 if (rawAttr->getNumArgs() > 0) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001923 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson28e71082008-02-16 00:29:18 +00001924 std::string("0"));
1925 return;
1926 }
1927
1928 if (TagDecl *TD = dyn_cast<TagDecl>(d))
1929 TD->addAttr(new PackedAttr);
1930 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
1931 // If the alignment is less than or equal to 8 bits, the packed attribute
1932 // has no effect.
1933 if (Context.getTypeAlign(FD->getType(), SourceLocation()) <= 8)
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001934 Diag(rawAttr->getLoc(),
Anders Carlsson28e71082008-02-16 00:29:18 +00001935 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001936 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlsson28e71082008-02-16 00:29:18 +00001937 else
Anders Carlsson4b939792008-02-16 00:39:40 +00001938 FD->addAttr(new PackedAttr);
Anders Carlsson28e71082008-02-16 00:29:18 +00001939 } else
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001940 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
1941 rawAttr->getName()->getName());
Anders Carlsson28e71082008-02-16 00:29:18 +00001942}
Nate Begemand45d38d2008-02-21 19:30:49 +00001943
Ted Kremenekf7146ca2008-02-27 20:43:06 +00001944void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
1945 // check the attribute arguments.
1946 if (rawAttr->getNumArgs() != 0) {
1947 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
1948 std::string("0"));
1949 return;
1950 }
1951
1952 d->addAttr(new NoReturnAttr());
1953}
1954
Nate Begemand45d38d2008-02-21 19:30:49 +00001955void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
1956 // check the attribute arguments.
1957 if (rawAttr->getNumArgs() != 1) {
1958 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
1959 std::string("1"));
1960 return;
1961 }
1962 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
1963 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlsson28e71082008-02-16 00:29:18 +00001964
Nate Begemand45d38d2008-02-21 19:30:49 +00001965 // Make sure that there is a string literal as the annotation's single
1966 // argument.
1967 if (!SE) {
1968 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
1969 return;
1970 }
1971 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
1972 SE->getByteLength())));
1973}
1974
Anders Carlsson721f6012007-12-19 07:19:40 +00001975void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
1976{
1977 // check the attribute arguments.
Eli Friedman3780d352008-01-30 17:38:42 +00001978 if (rawAttr->getNumArgs() > 1) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001979 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson721f6012007-12-19 07:19:40 +00001980 std::string("1"));
1981 return;
1982 }
Eli Friedman3780d352008-01-30 17:38:42 +00001983
Anders Carlsson6e3ace52008-02-16 19:51:27 +00001984 unsigned Align = 0;
1985
1986 if (rawAttr->getNumArgs() == 0) {
1987 // FIXME: This should be the target specific maximum alignment.
1988 // (For now we just use 128 bits which is the maximum on X86.
1989 Align = 128;
Eli Friedman3780d352008-01-30 17:38:42 +00001990 return;
Anders Carlsson6e3ace52008-02-16 19:51:27 +00001991 } else {
1992 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
1993 llvm::APSInt alignment(32);
1994 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001995 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson6e3ace52008-02-16 19:51:27 +00001996 "aligned", alignmentExpr->getSourceRange());
1997 return;
1998 }
1999
2000 Align = alignment.getZExtValue() * 8;
2001 }
Eli Friedman3780d352008-01-30 17:38:42 +00002002
Anders Carlsson6e3ace52008-02-16 19:51:27 +00002003 d->addAttr(new AlignedAttr(Align));
Anders Carlsson721f6012007-12-19 07:19:40 +00002004}