blob: fc60a7a4aa59aafa58500a45c4182f0241a347a8 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Builtins.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/Type.h"
21#include "clang/Parse/DeclSpec.h"
22#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000025#include "clang/Basic/SourceManager.h"
26// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000027#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000028#include "clang/Lex/HeaderSearch.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000029#include "llvm/ADT/SmallString.h"
Chris Lattner4b009652007-07-25 00:24:17 +000030#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian67907bd2007-10-05 18:00:57 +000031#include "llvm/ADT/DenseSet.h"
Chris Lattner4b009652007-07-25 00:24:17 +000032using namespace clang;
33
Chris Lattner4b009652007-07-25 00:24:17 +000034Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000035 Decl *IIDecl = II.getFETokenInfo<Decl>();
36 // Find first occurance of none-tagged declaration
37 while(IIDecl && IIDecl->getIdentifierNamespace() != Decl::IDNS_Ordinary)
38 IIDecl = cast<ScopedDecl>(IIDecl)->getNext();
39 if (!IIDecl)
40 return 0;
Ted Kremenek42730c52008-01-07 19:49:32 +000041 if (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000042 return IIDecl;
Ted Kremenek42730c52008-01-07 19:49:32 +000043 if (ObjCCompatibleAliasDecl *ADecl =
44 dyn_cast<ObjCCompatibleAliasDecl>(IIDecl))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000045 return ADecl->getClassInterface();
Steve Naroff81f1bba2007-09-06 21:24:23 +000046 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000047}
48
Steve Naroff9637a9b2007-10-09 22:01:59 +000049void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000050 if (S->decl_empty()) return;
51 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
52
Chris Lattner4b009652007-07-25 00:24:17 +000053 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
54 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +000055 Decl *TmpD = static_cast<Decl*>(*I);
56 assert(TmpD && "This decl didn't get pushed??");
57 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
58 assert(D && "This decl isn't a ScopedDecl?");
59
Chris Lattner4b009652007-07-25 00:24:17 +000060 IdentifierInfo *II = D->getIdentifier();
61 if (!II) continue;
62
63 // Unlink this decl from the identifier. Because the scope contains decls
64 // in an unordered collection, and because we have multiple identifier
65 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
66 if (II->getFETokenInfo<Decl>() == D) {
67 // Normal case, no multiple decls in different namespaces.
68 II->setFETokenInfo(D->getNext());
69 } else {
70 // Scan ahead. There are only three namespaces in C, so this loop can
71 // never execute more than 3 times.
Steve Naroffd21bc0d2007-09-13 18:10:37 +000072 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Chris Lattner4b009652007-07-25 00:24:17 +000073 while (SomeDecl->getNext() != D) {
74 SomeDecl = SomeDecl->getNext();
75 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
76 }
77 SomeDecl->setNext(D->getNext());
78 }
79
80 // This will have to be revisited for C++: there we want to nest stuff in
81 // namespace decls etc. Even for C, we might want a top-level translation
82 // unit decl or something.
83 if (!CurFunctionDecl)
84 continue;
85
86 // Chain this decl to the containing function, it now owns the memory for
87 // the decl.
88 D->setNext(CurFunctionDecl->getDeclChain());
89 CurFunctionDecl->setDeclChain(D);
90 }
91}
92
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +000093/// LookupInterfaceDecl - Lookup interface declaration in the scope chain.
94/// Return the first declaration found (which may or may not be a class
Fariborz Jahanian8eaeff52007-10-12 19:53:08 +000095/// declaration. Caller is responsible for handling the none-class case.
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +000096/// Bypassing the alias of a class by returning the aliased class.
97ScopedDecl *Sema::LookupInterfaceDecl(IdentifierInfo *ClassName) {
98 ScopedDecl *IDecl;
99 // Scan up the scope chain looking for a decl that matches this identifier
100 // that is in the appropriate namespace.
101 for (IDecl = ClassName->getFETokenInfo<ScopedDecl>(); IDecl;
102 IDecl = IDecl->getNext())
103 if (IDecl->getIdentifierNamespace() == Decl::IDNS_Ordinary)
104 break;
105
Ted Kremenek42730c52008-01-07 19:49:32 +0000106 if (ObjCCompatibleAliasDecl *ADecl =
107 dyn_cast_or_null<ObjCCompatibleAliasDecl>(IDecl))
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000108 return ADecl->getClassInterface();
109 return IDecl;
110}
111
Ted Kremenek42730c52008-01-07 19:49:32 +0000112/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +0000113/// return 0 if one not found.
Ted Kremenek42730c52008-01-07 19:49:32 +0000114ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000115 ScopedDecl *IdDecl = LookupInterfaceDecl(Id);
Ted Kremenek42730c52008-01-07 19:49:32 +0000116 return cast_or_null<ObjCInterfaceDecl>(IdDecl);
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +0000117}
118
Chris Lattner4b009652007-07-25 00:24:17 +0000119/// LookupScopedDecl - Look up the inner-most declaration in the specified
120/// namespace.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000121ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
122 SourceLocation IdLoc, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000123 if (II == 0) return 0;
124 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
125
126 // Scan up the scope chain looking for a decl that matches this identifier
127 // that is in the appropriate namespace. This search should not take long, as
128 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000129 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner4b009652007-07-25 00:24:17 +0000130 if (D->getIdentifierNamespace() == NS)
131 return D;
132
133 // If we didn't find a use of this identifier, and if the identifier
134 // corresponds to a compiler builtin, create the decl object for the builtin
135 // now, injecting it into translation unit scope, and return it.
136 if (NS == Decl::IDNS_Ordinary) {
137 // If this is a builtin on some other target, or if this builtin varies
138 // across targets (e.g. in type), emit a diagnostic and mark the translation
139 // unit non-portable for using it.
140 if (II->isNonPortableBuiltin()) {
141 // Only emit this diagnostic once for this builtin.
142 II->setNonPortableBuiltin(false);
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000143 Context.Target.DiagnoseNonPortability(Context.getFullLoc(IdLoc),
Chris Lattner4b009652007-07-25 00:24:17 +0000144 diag::port_target_builtin_use);
145 }
146 // If this is a builtin on this (or all) targets, create the decl.
147 if (unsigned BuiltinID = II->getBuiltinID())
148 return LazilyCreateBuiltin(II, BuiltinID, S);
149 }
150 return 0;
151}
152
Anders Carlsson36760332007-10-15 20:28:48 +0000153void Sema::InitBuiltinVaListType()
154{
155 if (!Context.getBuiltinVaListType().isNull())
156 return;
157
158 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
159 ScopedDecl *VaDecl = LookupScopedDecl(VaIdent, Decl::IDNS_Ordinary,
160 SourceLocation(), TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000161 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000162 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
163}
164
Chris Lattner4b009652007-07-25 00:24:17 +0000165/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
166/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000167ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
168 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000169 Builtin::ID BID = (Builtin::ID)bid;
170
Anders Carlsson36760332007-10-15 20:28:48 +0000171 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000172 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson36760332007-10-15 20:28:48 +0000173 BID == Builtin::BI__builtin_va_end)
174 InitBuiltinVaListType();
175
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000176 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner4b009652007-07-25 00:24:17 +0000177 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner987058a2007-08-26 04:02:13 +0000178 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000179
180 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000181 if (Scope *FnS = S->getFnParent())
182 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000183 while (S->getParent())
184 S = S->getParent();
185 S->AddDecl(New);
186
187 // Add this decl to the end of the identifier info.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000188 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000189 // Scan until we find the last (outermost) decl in the id chain.
190 while (LastDecl->getNext())
191 LastDecl = LastDecl->getNext();
192 // Insert before (outside) it.
193 LastDecl->setNext(New);
194 } else {
195 II->setFETokenInfo(New);
196 }
Chris Lattner4b009652007-07-25 00:24:17 +0000197 return New;
198}
199
200/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
201/// and scope as a previous declaration 'Old'. Figure out how to resolve this
202/// situation, merging decls or emitting diagnostics as appropriate.
203///
Steve Naroffcb597472007-09-13 21:41:19 +0000204TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000205 // Verify the old decl was also a typedef.
206 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
207 if (!Old) {
208 Diag(New->getLocation(), diag::err_redefinition_different_kind,
209 New->getName());
210 Diag(OldD->getLocation(), diag::err_previous_definition);
211 return New;
212 }
213
Steve Naroffae84af82007-10-31 18:42:27 +0000214 // Allow multiple definitions for ObjC built-in typedefs.
215 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek42730c52008-01-07 19:49:32 +0000216 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroffae84af82007-10-31 18:42:27 +0000217 return Old;
Steve Naroffa9eae582008-01-30 23:46:05 +0000218
219 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
220 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
221 // *either* declaration is in a system header. The code below implements
222 // this adhoc compatibility rule. FIXME: The following code will not
223 // work properly when compiling ".i" files (containing preprocessed output).
224 SourceManager &SrcMgr = Context.getSourceManager();
225 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
226 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
227 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
228 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
229 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
230
Steve Naroff73a07032008-02-07 03:50:06 +0000231 if ((OldDirType == DirectoryLookup::ExternCSystemHeaderDir ||
232 NewDirType == DirectoryLookup::ExternCSystemHeaderDir) ||
233 getLangOptions().Microsoft)
Steve Naroffa9eae582008-01-30 23:46:05 +0000234 return New;
Steve Naroffae84af82007-10-31 18:42:27 +0000235
Chris Lattner4b009652007-07-25 00:24:17 +0000236 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
237 // TODO: This is totally simplistic. It should handle merging functions
238 // together etc, merging extern int X; int X; ...
239 Diag(New->getLocation(), diag::err_redefinition, New->getName());
240 Diag(Old->getLocation(), diag::err_previous_definition);
241 return New;
242}
243
244/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
245/// and scope as a previous declaration 'Old'. Figure out how to resolve this
246/// situation, merging decls or emitting diagnostics as appropriate.
247///
Steve Naroffcb597472007-09-13 21:41:19 +0000248FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000249 // Verify the old decl was also a function.
250 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
251 if (!Old) {
252 Diag(New->getLocation(), diag::err_redefinition_different_kind,
253 New->getName());
254 Diag(OldD->getLocation(), diag::err_previous_definition);
255 return New;
256 }
257
Chris Lattner60476ff2007-11-20 19:04:50 +0000258 QualType OldQType = Old->getCanonicalType();
259 QualType NewQType = New->getCanonicalType();
260
Steve Naroff1d5bd642008-01-14 20:51:29 +0000261 // Function types need to be compatible, not identical. This handles
262 // duplicate function decls like "void f(int); void f(enum X);" properly.
263 if (Context.functionTypesAreCompatible(OldQType, NewQType))
264 return New;
Chris Lattner1470b072007-11-06 06:07:26 +0000265
Steve Naroff6c9e7922008-01-16 15:01:34 +0000266 // A function that has already been declared has been redeclared or defined
267 // with a different type- show appropriate diagnostic
268 diag::kind PrevDiag = Old->getBody() ? diag::err_previous_definition :
269 diag::err_previous_declaration;
270
Chris Lattner4b009652007-07-25 00:24:17 +0000271 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
272 // TODO: This is totally simplistic. It should handle merging functions
273 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000274 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
275 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000276 return New;
277}
278
Chris Lattnerf9167d12007-11-06 04:28:31 +0000279
280/// hasUndefinedLength - Used by equivalentArrayTypes to determine whether the
281/// the outermost VariableArrayType has no size defined.
282static bool hasUndefinedLength(const ArrayType *Array) {
283 const VariableArrayType *VAT = Array->getAsVariableArrayType();
284 return VAT && !VAT->getSizeExpr();
285}
286
287/// equivalentArrayTypes - Used to determine whether two array types are
288/// equivalent.
289/// We need to check this explicitly as an incomplete array definition is
290/// considered a VariableArrayType, so will not match a complete array
291/// definition that would be otherwise equivalent.
292static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
293 const ArrayType *NewAT = NewQType->getAsArrayType();
294 const ArrayType *OldAT = OldQType->getAsArrayType();
295
296 if (!NewAT || !OldAT)
297 return false;
298
299 // If either (or both) array types in incomplete we need to strip off the
300 // outer VariableArrayType. Once the outer VAT is removed the remaining
301 // types must be identical if the array types are to be considered
302 // equivalent.
303 // eg. int[][1] and int[1][1] become
304 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
305 // removing the outermost VAT gives
306 // CAT(1, int) and CAT(1, int)
307 // which are equal, therefore the array types are equivalent.
308 if (hasUndefinedLength(NewAT) || hasUndefinedLength(OldAT)) {
309 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
310 return false;
Eli Friedmand32157f2008-01-29 07:51:12 +0000311 NewQType = NewAT->getElementType().getCanonicalType();
312 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerf9167d12007-11-06 04:28:31 +0000313 }
314
315 return NewQType == OldQType;
316}
317
Chris Lattner4b009652007-07-25 00:24:17 +0000318/// MergeVarDecl - We just parsed a variable 'New' which has the same name
319/// and scope as a previous declaration 'Old'. Figure out how to resolve this
320/// situation, merging decls or emitting diagnostics as appropriate.
321///
322/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
323/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
324///
Steve Naroffcb597472007-09-13 21:41:19 +0000325VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000326 // Verify the old decl was also a variable.
327 VarDecl *Old = dyn_cast<VarDecl>(OldD);
328 if (!Old) {
329 Diag(New->getLocation(), diag::err_redefinition_different_kind,
330 New->getName());
331 Diag(OldD->getLocation(), diag::err_previous_definition);
332 return New;
333 }
334 // Verify the types match.
Chris Lattnerf9167d12007-11-06 04:28:31 +0000335 if (Old->getCanonicalType() != New->getCanonicalType() &&
336 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Chris Lattner4b009652007-07-25 00:24:17 +0000337 Diag(New->getLocation(), diag::err_redefinition, New->getName());
338 Diag(Old->getLocation(), diag::err_previous_definition);
339 return New;
340 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000341 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
342 if (New->getStorageClass() == VarDecl::Static &&
343 (Old->getStorageClass() == VarDecl::None ||
344 Old->getStorageClass() == VarDecl::Extern)) {
345 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
346 Diag(Old->getLocation(), diag::err_previous_definition);
347 return New;
348 }
349 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
350 if (New->getStorageClass() != VarDecl::Static &&
351 Old->getStorageClass() == VarDecl::Static) {
352 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
353 Diag(Old->getLocation(), diag::err_previous_definition);
354 return New;
355 }
356 // We've verified the types match, now handle "tentative" definitions.
357 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
358 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
359
360 if (OldFSDecl && NewFSDecl) {
361 // Handle C "tentative" external object definitions (C99 6.9.2).
362 bool OldIsTentative = false;
363 bool NewIsTentative = false;
364
365 if (!OldFSDecl->getInit() &&
366 (OldFSDecl->getStorageClass() == VarDecl::None ||
367 OldFSDecl->getStorageClass() == VarDecl::Static))
368 OldIsTentative = true;
369
370 // FIXME: this check doesn't work (since the initializer hasn't been
371 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
372 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
373 // thrown out the old decl.
374 if (!NewFSDecl->getInit() &&
375 (NewFSDecl->getStorageClass() == VarDecl::None ||
376 NewFSDecl->getStorageClass() == VarDecl::Static))
377 ; // change to NewIsTentative = true; once the code is moved.
378
379 if (NewIsTentative || OldIsTentative)
380 return New;
381 }
382 if (Old->getStorageClass() != VarDecl::Extern &&
383 New->getStorageClass() != VarDecl::Extern) {
Chris Lattner4b009652007-07-25 00:24:17 +0000384 Diag(New->getLocation(), diag::err_redefinition, New->getName());
385 Diag(Old->getLocation(), diag::err_previous_definition);
386 }
387 return New;
388}
389
390/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
391/// no declarator (e.g. "struct foo;") is parsed.
392Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
393 // TODO: emit error on 'int;' or 'const enum foo;'.
394 // TODO: emit error on 'typedef int;'
395 // if (!DS.isMissingDeclaratorOk()) Diag(...);
396
Steve Naroffedafc0b2007-11-17 21:37:36 +0000397 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000398}
399
Steve Narofff0b23542008-01-10 22:15:12 +0000400bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000401 // Get the type before calling CheckSingleAssignmentConstraints(), since
402 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000403 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000404
Chris Lattner005ed752008-01-04 18:04:52 +0000405 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
406 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
407 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000408}
409
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000410bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Narofff0b23542008-01-10 22:15:12 +0000411 QualType ElementType) {
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000412 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Narofff0b23542008-01-10 22:15:12 +0000413 if (CheckSingleInitializer(expr, ElementType))
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000414 return true; // types weren't compatible.
415
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000416 if (savExpr != expr) // The type was promoted, update initializer list.
417 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000418 return false;
419}
420
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000421bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
422 if (const VariableArrayType *VAT = DeclT->getAsIncompleteArrayType()) {
423 // C99 6.7.8p14. We have an array of character type with unknown size
424 // being initialized to a string literal.
425 llvm::APSInt ConstVal(32);
426 ConstVal = strLiteral->getByteLength() + 1;
427 // Return a new array type (C99 6.7.8p22).
428 DeclT = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
429 ArrayType::Normal, 0);
430 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
431 // C99 6.7.8p14. We have an array of character type with known size.
432 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
433 Diag(strLiteral->getSourceRange().getBegin(),
434 diag::warn_initializer_string_for_char_array_too_long,
435 strLiteral->getSourceRange());
436 } else {
437 assert(0 && "HandleStringLiteralInit(): Invalid array type");
438 }
439 // Set type from "char *" to "constant array of char".
440 strLiteral->setType(DeclT);
441 // For now, we always return false (meaning success).
442 return false;
443}
444
445StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000446 const ArrayType *AT = DeclType->getAsArrayType();
Steve Narofff3cb5142008-01-25 00:51:06 +0000447 if (AT && AT->getElementType()->isCharType()) {
448 return dyn_cast<StringLiteral>(Init);
449 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000450 return 0;
451}
452
Steve Narofff3cb5142008-01-25 00:51:06 +0000453// CheckInitializerListTypes - Checks the types of elements of an initializer
454// list. This function is recursive: it calls itself to initialize subelements
455// of aggregate types. Note that the topLevel parameter essentially refers to
456// whether this expression "owns" the initializer list passed in, or if this
457// initialization is taking elements out of a parent initializer. Each
458// call to this function adds zero or more to startIndex, reports any errors,
459// and returns true if it found any inconsistent types.
460bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
461 bool topLevel, unsigned& startIndex) {
Steve Naroffcb69fb72007-12-10 22:44:33 +0000462 bool hadError = false;
Steve Narofff3cb5142008-01-25 00:51:06 +0000463
464 if (DeclType->isScalarType()) {
465 // The simplest case: initializing a single scalar
466 if (topLevel) {
467 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
468 IList->getSourceRange());
469 }
470 if (startIndex < IList->getNumInits()) {
471 Expr* expr = IList->getInit(startIndex);
472 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
473 // FIXME: Should an error be reported here instead?
474 unsigned newIndex = 0;
475 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
476 } else {
477 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
478 }
479 ++startIndex;
480 }
481 // FIXME: Should an error be reported for empty initializer list + scalar?
482 } else if (DeclType->isVectorType()) {
483 if (startIndex < IList->getNumInits()) {
484 const VectorType *VT = DeclType->getAsVectorType();
485 int maxElements = VT->getNumElements();
486 QualType elementType = VT->getElementType();
487
488 for (int i = 0; i < maxElements; ++i) {
489 // Don't attempt to go past the end of the init list
490 if (startIndex >= IList->getNumInits())
491 break;
492 Expr* expr = IList->getInit(startIndex);
493 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
494 unsigned newIndex = 0;
495 hadError |= CheckInitializerListTypes(SubInitList, elementType,
496 true, newIndex);
497 ++startIndex;
498 } else {
499 hadError |= CheckInitializerListTypes(IList, elementType,
500 false, startIndex);
501 }
502 }
503 }
504 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
505 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroffedce4ec2008-01-28 02:00:41 +0000506 if (startIndex < IList->getNumInits() && !topLevel &&
507 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
508 DeclType)) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000509 // We found a compatible struct; per the standard, this initializes the
510 // struct. (The C standard technically says that this only applies for
511 // initializers for declarations with automatic scope; however, this
512 // construct is unambiguous anyway because a struct cannot contain
513 // a type compatible with itself. We'll output an error when we check
514 // if the initializer is constant.)
515 // FIXME: Is a call to CheckSingleInitializer required here?
516 ++startIndex;
517 } else {
518 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffee467032008-02-11 00:06:17 +0000519
Steve Naroff576df292008-02-11 21:52:37 +0000520 // If the record is invalid, some of it's members are invalid. To avoid
521 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffee467032008-02-11 00:06:17 +0000522 if (structDecl->isInvalidDecl())
523 return true;
524
Steve Narofff3cb5142008-01-25 00:51:06 +0000525 // If structDecl is a forward declaration, this loop won't do anything;
526 // That's okay, because an error should get printed out elsewhere. It
527 // might be worthwhile to skip over the rest of the initializer, though.
528 int numMembers = structDecl->getNumMembers() -
529 structDecl->hasFlexibleArrayMember();
530 for (int i = 0; i < numMembers; i++) {
531 // Don't attempt to go past the end of the init list
532 if (startIndex >= IList->getNumInits())
533 break;
534 FieldDecl * curField = structDecl->getMember(i);
535 if (!curField->getIdentifier()) {
536 // Don't initialize unnamed fields, e.g. "int : 20;"
537 continue;
538 }
539 QualType fieldType = curField->getType();
540 Expr* expr = IList->getInit(startIndex);
541 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
542 unsigned newStart = 0;
543 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
544 true, newStart);
545 ++startIndex;
546 } else {
547 hadError |= CheckInitializerListTypes(IList, fieldType,
548 false, startIndex);
549 }
550 if (DeclType->isUnionType())
551 break;
552 }
553 // FIXME: Implement flexible array initialization GCC extension (it's a
554 // really messy extension to implement, unfortunately...the necessary
555 // information isn't actually even here!)
556 }
557 } else if (DeclType->isArrayType()) {
558 // Check for the special-case of initializing an array with a string.
559 if (startIndex < IList->getNumInits()) {
560 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
561 DeclType)) {
562 CheckStringLiteralInit(lit, DeclType);
563 ++startIndex;
564 if (topLevel && startIndex < IList->getNumInits()) {
565 // We have leftover initializers; warn
566 Diag(IList->getInit(startIndex)->getLocStart(),
567 diag::err_excess_initializers_in_char_array_initializer,
568 IList->getInit(startIndex)->getSourceRange());
569 }
570 return false;
571 }
572 }
573 int maxElements;
574 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
575 // FIXME: use a proper constant
576 maxElements = 0x7FFFFFFF;
577 // Check for VLAs; in standard C it would be possible to check this
578 // earlier, but I don't know where clang accepts VLAs (gcc accepts
579 // them in all sorts of strange places).
580 if (const Expr *expr = VAT->getSizeExpr()) {
581 Diag(expr->getLocStart(), diag::err_variable_object_no_init,
582 expr->getSourceRange());
583 hadError = true;
584 }
585 } else {
586 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
587 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
588 }
589 QualType elementType = DeclType->getAsArrayType()->getElementType();
590 int numElements = 0;
591 for (int i = 0; i < maxElements; ++i, ++numElements) {
592 // Don't attempt to go past the end of the init list
593 if (startIndex >= IList->getNumInits())
594 break;
595 Expr* expr = IList->getInit(startIndex);
596 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
597 unsigned newIndex = 0;
598 hadError |= CheckInitializerListTypes(SubInitList, elementType,
599 true, newIndex);
600 ++startIndex;
601 } else {
602 hadError |= CheckInitializerListTypes(IList, elementType,
603 false, startIndex);
604 }
605 }
606 if (DeclType->getAsVariableArrayType()) {
607 // If this is an incomplete array type, the actual type needs to
608 // be calculated here
609 if (numElements == 0) {
610 // Sizing an array implicitly to zero is not allowed
611 // (It could in theory be allowed, but it doesn't really matter.)
612 Diag(IList->getLocStart(),
613 diag::err_at_least_one_initializer_needed_to_size_array);
614 hadError = true;
615 } else {
616 llvm::APSInt ConstVal(32);
617 ConstVal = numElements;
618 DeclType = Context.getConstantArrayType(elementType, ConstVal,
619 ArrayType::Normal, 0);
620 }
621 }
622 } else {
623 assert(0 && "Aggregate that isn't a function or array?!");
624 }
625 } else {
626 // In C, all types are either scalars or aggregates, but
627 // additional handling is needed here for C++ (and possibly others?).
628 assert(0 && "Unsupported initializer type");
629 }
630
631 // If this init list is a base list, we set the type; an initializer doesn't
632 // fundamentally have a type, but this makes the ASTs a bit easier to read
633 if (topLevel)
634 IList->setType(DeclType);
635
636 if (topLevel && startIndex < IList->getNumInits()) {
637 // We have leftover initializers; warn
638 Diag(IList->getInit(startIndex)->getLocStart(),
639 diag::warn_excess_initializers,
640 IList->getInit(startIndex)->getSourceRange());
641 }
642 return hadError;
643}
644
645bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff8e9337f2008-01-21 23:53:58 +0000646 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
647 // of unknown size ("[]") or an object type that is not a variable array type.
648 if (const VariableArrayType *VAT = DeclType->getAsVariablyModifiedType())
649 return Diag(VAT->getSizeExpr()->getLocStart(),
650 diag::err_variable_object_no_init,
651 VAT->getSizeExpr()->getSourceRange());
652
Steve Naroffcb69fb72007-12-10 22:44:33 +0000653 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
654 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000655 // FIXME: Handle wide strings
656 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
657 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000658
659 if (DeclType->isArrayType())
660 return Diag(Init->getLocStart(),
661 diag::err_array_init_list_required,
662 Init->getSourceRange());
663
Steve Narofff0b23542008-01-10 22:15:12 +0000664 return CheckSingleInitializer(Init, DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000665 }
Steve Narofff3cb5142008-01-25 00:51:06 +0000666 unsigned newIndex = 0;
667 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroffe14e5542007-09-02 02:04:30 +0000668}
669
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000670Sema::DeclTy *
Steve Naroff0acc9c92007-09-15 18:49:24 +0000671Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000672 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000673 IdentifierInfo *II = D.getIdentifier();
674
675 // All of these full declarators require an identifier. If it doesn't have
676 // one, the ParsedFreeStandingDeclSpec action should be used.
677 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000678 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000679 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000680 D.getDeclSpec().getSourceRange(), D.getSourceRange());
681 return 0;
682 }
683
Chris Lattnera7549902007-08-26 06:24:45 +0000684 // The scope passed in may not be a decl scope. Zip up the scope tree until
685 // we find one that is.
686 while ((S->getFlags() & Scope::DeclScope) == 0)
687 S = S->getParent();
688
Chris Lattner4b009652007-07-25 00:24:17 +0000689 // See if this is a redefinition of a variable in the same scope.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000690 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
691 D.getIdentifierLoc(), S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000692 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000693 bool InvalidDecl = false;
694
Chris Lattner82bb4792007-11-14 06:34:38 +0000695 QualType R = GetTypeForDeclarator(D, S);
696 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
697
Chris Lattner4b009652007-07-25 00:24:17 +0000698 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner82bb4792007-11-14 06:34:38 +0000699 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000700 if (!NewTD) return 0;
701
702 // Handle attributes prior to checking for duplicates in MergeVarDecl
703 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
704 D.getAttributes());
Steve Narofff8a09432008-01-09 23:34:55 +0000705 // Merge the decl with the existing one if appropriate. If the decl is
706 // in an outer scope, it isn't the same thing.
707 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000708 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
709 if (NewTD == 0) return 0;
710 }
711 New = NewTD;
712 if (S->getParent() == 0) {
713 // C99 6.7.7p2: If a typedef name specifies a variably modified type
714 // then it shall have block scope.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000715 if (const VariableArrayType *VAT =
716 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
717 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
718 VAT->getSizeExpr()->getSourceRange());
719 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000720 }
721 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000722 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000723 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000724 switch (D.getDeclSpec().getStorageClassSpec()) {
725 default: assert(0 && "Unknown storage class!");
726 case DeclSpec::SCS_auto:
727 case DeclSpec::SCS_register:
728 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
729 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000730 InvalidDecl = true;
731 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000732 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
733 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
734 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000735 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000736 }
737
738 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000739 D.getDeclSpec().isInlineSpecified(),
Nate Begeman84079d72007-11-13 22:14:47 +0000740 LastDeclarator,
741 D.getDeclSpec().getAttributes());
742
743 // Transfer ownership of DeclSpec attributes to FunctionDecl
744 D.getDeclSpec().clearAttributes();
Chris Lattner4b009652007-07-25 00:24:17 +0000745
Steve Narofff8a09432008-01-09 23:34:55 +0000746 // Merge the decl with the existing one if appropriate. Since C functions
747 // are in a flat namespace, make sure we consider decls in outer scopes.
Chris Lattner4b009652007-07-25 00:24:17 +0000748 if (PrevDecl) {
749 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
750 if (NewFD == 0) return 0;
751 }
752 New = NewFD;
753 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +0000754 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000755 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
756 D.getIdentifier()->getName());
757 InvalidDecl = true;
758 }
Chris Lattner4b009652007-07-25 00:24:17 +0000759
760 VarDecl *NewVD;
761 VarDecl::StorageClass SC;
762 switch (D.getDeclSpec().getStorageClassSpec()) {
763 default: assert(0 && "Unknown storage class!");
Steve Naroff1cbb2762008-01-25 22:14:40 +0000764 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
765 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
766 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
767 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
768 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
769 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000770 }
771 if (S->getParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000772 // C99 6.9p2: The storage-class specifiers auto and register shall not
773 // appear in the declaration specifiers in an external declaration.
774 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
775 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
776 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000777 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000778 }
Chris Lattner4b009652007-07-25 00:24:17 +0000779 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000780 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000781 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000782 }
Chris Lattner4b009652007-07-25 00:24:17 +0000783 // Handle attributes prior to checking for duplicates in MergeVarDecl
784 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
785 D.getAttributes());
786
Steve Narofff8a09432008-01-09 23:34:55 +0000787 // Merge the decl with the existing one if appropriate. If the decl is
788 // in an outer scope, it isn't the same thing.
789 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000790 NewVD = MergeVarDecl(NewVD, PrevDecl);
791 if (NewVD == 0) return 0;
792 }
Chris Lattner4b009652007-07-25 00:24:17 +0000793 New = NewVD;
794 }
795
796 // If this has an identifier, add it to the scope stack.
797 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000798 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000799 II->setFETokenInfo(New);
800 S->AddDecl(New);
801 }
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000802 // If any semantic error occurred, mark the decl as invalid.
803 if (D.getInvalidType() || InvalidDecl)
804 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000805
806 return New;
807}
808
Steve Narofff0b23542008-01-10 22:15:12 +0000809bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
810 SourceLocation loc;
811 // FIXME: Remove the isReference check and handle assignment to a reference.
812 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
813 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
814 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
815 return true;
816 }
817 return false;
818}
819
Steve Naroff6a0e2092007-09-12 14:07:44 +0000820void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000821 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000822 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +0000823 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +0000824
Chris Lattnerf31a2fb2007-10-19 20:10:30 +0000825 // If there is no declaration, there was an error parsing it. Just ignore
826 // the initializer.
827 if (RealDecl == 0) {
828 delete Init;
829 return;
830 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000831
Steve Naroff420d0f52007-09-12 20:13:48 +0000832 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
833 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +0000834 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
835 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +0000836 RealDecl->setInvalidDecl();
837 return;
838 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000839 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +0000840 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +0000841 QualType DclT = VDecl->getType(), SavT = DclT;
842 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000843 VarDecl::StorageClass SC = BVD->getStorageClass();
844 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +0000845 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000846 BVD->setInvalidDecl();
847 } else if (!BVD->isInvalidDecl()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000848 if (CheckInitializerTypes(Init, DclT))
849 BVD->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +0000850 if (SC == VarDecl::Static) // C99 6.7.8p4.
851 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000852 }
Steve Naroff420d0f52007-09-12 20:13:48 +0000853 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000854 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +0000855 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000856 if (!FVD->isInvalidDecl())
Steve Narofff3cb5142008-01-25 00:51:06 +0000857 if (CheckInitializerTypes(Init, DclT))
858 FVD->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +0000859
860 // C99 6.7.8p4. All file scoped initializers need to be constant.
861 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000862 }
863 // If the type changed, it means we had an incomplete type that was
864 // completed by the initializer. For example:
865 // int ary[] = { 1, 3, 5 };
866 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +0000867 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000868 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +0000869 Init->setType(DclT);
870 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000871
872 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +0000873 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000874 return;
875}
876
Chris Lattner4b009652007-07-25 00:24:17 +0000877/// The declarators are chained together backwards, reverse the list.
878Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
879 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000880 Decl *GroupDecl = static_cast<Decl*>(group);
881 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +0000882 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +0000883
884 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
885 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000886 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000887 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000888 else { // reverse the list.
889 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000890 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +0000891 Group->setNextDeclarator(NewGroup);
892 NewGroup = Group;
893 Group = Next;
894 }
895 }
896 // Perform semantic analysis that depends on having fully processed both
897 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000898 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000899 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
900 if (!IDecl)
901 continue;
902 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
903 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
904 QualType T = IDecl->getType();
905
906 // C99 6.7.5.2p2: If an identifier is declared to be an object with
907 // static storage duration, it shall not have a variable length array.
908 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
909 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
910 if (VLA->getSizeExpr()) {
911 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
912 IDecl->setInvalidDecl();
913 }
914 }
915 }
916 // Block scope. C99 6.7p7: If an identifier for an object is declared with
917 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
918 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
919 if (T->isIncompleteType()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +0000920 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
921 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +0000922 IDecl->setInvalidDecl();
923 }
924 }
925 // File scope. C99 6.9.2p2: A declaration of an identifier for and
926 // object that has file scope without an initializer, and without a
927 // storage-class specifier or with the storage-class specifier "static",
928 // constitutes a tentative definition. Note: A tentative definition with
929 // external linkage is valid (C99 6.2.2p5).
Steve Narofffef2f052008-01-18 00:39:39 +0000930 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
931 FVD->getStorageClass() == VarDecl::None)) {
Steve Naroff60685462008-01-18 20:40:52 +0000932 const VariableArrayType *VAT = T->getAsVariableArrayType();
933
934 if (VAT && VAT->getSizeExpr() == 0) {
935 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
936 // array to be completed. Don't issue a diagnostic.
937 } else if (T->isIncompleteType()) {
938 // C99 6.9.2p3: If the declaration of an identifier for an object is
939 // a tentative definition and has internal linkage (C99 6.2.2p3), the
940 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +0000941 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
942 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +0000943 IDecl->setInvalidDecl();
944 }
945 }
Chris Lattner4b009652007-07-25 00:24:17 +0000946 }
947 return NewGroup;
948}
Steve Naroff91b03f72007-08-28 03:03:08 +0000949
950// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000951ParmVarDecl *
Nate Begeman2240f542007-11-13 21:49:48 +0000952Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI, Scope *FnScope)
Steve Naroff434fa8d2007-11-12 03:44:46 +0000953{
Chris Lattner4b009652007-07-25 00:24:17 +0000954 IdentifierInfo *II = PI.Ident;
955 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
956 // Can this happen for params? We already checked that they don't conflict
957 // among each other. Here they can only shadow globals, which is ok.
958 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
959 PI.IdentLoc, FnScope)) {
960
961 }
962
963 // FIXME: Handle storage class (auto, register). No declarator?
964 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000965
966 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
967 // Doing the promotion here has a win and a loss. The win is the type for
968 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
969 // code generator). The loss is the orginal type isn't preserved. For example:
970 //
971 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
972 // int blockvardecl[5];
973 // sizeof(parmvardecl); // size == 4
974 // sizeof(blockvardecl); // size == 20
975 // }
976 //
977 // For expressions, all implicit conversions are captured using the
978 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
979 //
980 // FIXME: If a source translation tool needs to see the original type, then
981 // we need to consider storing both types (in ParmVarDecl)...
982 //
983 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattnerc08564a2008-01-02 22:50:48 +0000984 if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
985 // int x[restrict 4] -> int *restrict
Steve Naroff94cd93f2007-08-07 22:44:21 +0000986 parmDeclType = Context.getPointerType(AT->getElementType());
Chris Lattnerc08564a2008-01-02 22:50:48 +0000987 parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
988 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +0000989 parmDeclType = Context.getPointerType(parmDeclType);
990
991 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Nate Begeman84079d72007-11-13 22:14:47 +0000992 VarDecl::None, 0, PI.AttrList);
Steve Naroffcae537d2007-08-28 18:45:29 +0000993 if (PI.InvalidType)
994 New->setInvalidDecl();
995
Chris Lattner4b009652007-07-25 00:24:17 +0000996 // If this has an identifier, add it to the scope stack.
997 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000998 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000999 II->setFETokenInfo(New);
1000 FnScope->AddDecl(New);
1001 }
1002
1003 return New;
1004}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001005
Chris Lattnerea148702007-10-09 17:14:05 +00001006Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +00001007 assert(CurFunctionDecl == 0 && "Function parsing confused");
1008 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1009 "Not a function declarator!");
1010 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1011
1012 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1013 // for a K&R function.
1014 if (!FTI.hasPrototype) {
1015 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1016 if (FTI.ArgInfo[i].TypeInfo == 0) {
1017 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1018 FTI.ArgInfo[i].Ident->getName());
1019 // Implicitly declare the argument as type 'int' for lack of a better
1020 // type.
1021 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
1022 }
1023 }
1024
1025 // Since this is a function definition, act as though we have information
1026 // about the arguments.
1027 FTI.hasPrototype = true;
1028 } else {
1029 // FIXME: Diagnose arguments without names in C.
1030
1031 }
1032
1033 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001034
1035 // See if this is a redefinition.
1036 ScopedDecl *PrevDcl = LookupScopedDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1037 D.getIdentifierLoc(), GlobalScope);
1038 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1039 if (FD->getBody()) {
1040 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1041 D.getIdentifier()->getName());
1042 Diag(FD->getLocation(), diag::err_previous_definition);
1043 }
1044 }
Steve Naroff4a712442008-02-12 01:09:36 +00001045 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
1046 FunctionDecl *FD = dyn_cast<FunctionDecl>(decl);
Steve Naroff1d5bd642008-01-14 20:51:29 +00001047 assert(FD != 0 && "ActOnDeclarator() didn't return a FunctionDecl");
Chris Lattner4b009652007-07-25 00:24:17 +00001048 CurFunctionDecl = FD;
1049
1050 // Create Decl objects for each parameter, adding them to the FunctionDecl.
1051 llvm::SmallVector<ParmVarDecl*, 16> Params;
1052
1053 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1054 // no arguments, not a function that takes a single void argument.
1055 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnereee2f2b2007-11-28 18:51:29 +00001056 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getQualifiers() &&
1057 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001058 // empty arg list, don't push any params.
1059 } else {
Steve Naroff434fa8d2007-11-12 03:44:46 +00001060 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begeman2240f542007-11-13 21:49:48 +00001061 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroff434fa8d2007-11-12 03:44:46 +00001062 FnBodyScope));
1063 }
Chris Lattner4b009652007-07-25 00:24:17 +00001064 }
1065
1066 FD->setParams(&Params[0], Params.size());
1067
1068 return FD;
1069}
1070
Steve Naroff99ee4302007-11-11 23:20:51 +00001071Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1072 Decl *dcl = static_cast<Decl *>(D);
1073 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1074 FD->setBody((Stmt*)Body);
1075 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff8ba51142007-12-13 18:18:56 +00001076 CurFunctionDecl = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001077 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001078 MD->setBody((Stmt*)Body);
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001079 CurMethodDecl = 0;
Steve Naroff8ba51142007-12-13 18:18:56 +00001080 }
Chris Lattner4b009652007-07-25 00:24:17 +00001081 // Verify and clean out per-function state.
1082
1083 // Check goto/label use.
1084 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1085 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1086 // Verify that we have no forward references left. If so, there was a goto
1087 // or address of a label taken, but no definition of it. Label fwd
1088 // definitions are indicated with a null substmt.
1089 if (I->second->getSubStmt() == 0) {
1090 LabelStmt *L = I->second;
1091 // Emit error.
1092 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1093
1094 // At this point, we have gotos that use the bogus label. Stitch it into
1095 // the function body so that they aren't leaked and that the AST is well
1096 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00001097 if (Body) {
1098 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1099 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1100 } else {
1101 // The whole function wasn't parsed correctly, just delete this.
1102 delete L;
1103 }
Chris Lattner4b009652007-07-25 00:24:17 +00001104 }
1105 }
1106 LabelMap.clear();
1107
Steve Naroff99ee4302007-11-11 23:20:51 +00001108 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001109}
1110
Chris Lattner4b009652007-07-25 00:24:17 +00001111/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1112/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001113ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1114 IdentifierInfo &II, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +00001115 if (getLangOptions().C99) // Extension in C99.
1116 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1117 else // Legal in C90, but warn about it.
1118 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1119
1120 // FIXME: handle stuff like:
1121 // void foo() { extern float X(); }
1122 // void bar() { X(); } <-- implicit decl for X in another scope.
1123
1124 // Set a Declarator for the implicit definition: int foo();
1125 const char *Dummy;
1126 DeclSpec DS;
1127 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1128 Error = Error; // Silence warning.
1129 assert(!Error && "Error setting up implicit decl!");
1130 Declarator D(DS, Declarator::BlockContext);
1131 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1132 D.SetIdentifier(&II, Loc);
1133
1134 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +00001135 if (Scope *FnS = S->getFnParent())
1136 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +00001137 while (S->getParent())
1138 S = S->getParent();
1139
Steve Narofff0c31dd2007-09-16 16:16:00 +00001140 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattner4b009652007-07-25 00:24:17 +00001141}
1142
1143
Chris Lattner82bb4792007-11-14 06:34:38 +00001144TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001145 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001146 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001147 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001148
1149 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001150 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
1151 T, LastDeclarator);
1152 if (D.getInvalidType())
1153 NewTD->setInvalidDecl();
1154 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001155}
1156
Steve Naroff0acc9c92007-09-15 18:49:24 +00001157/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001158/// former case, Name will be non-null. In the later case, Name will be null.
1159/// TagType indicates what kind of tag this is. TK indicates whether this is a
1160/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001161Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001162 SourceLocation KWLoc, IdentifierInfo *Name,
1163 SourceLocation NameLoc, AttributeList *Attr) {
1164 // If this is a use of an existing tag, it must have a name.
1165 assert((Name != 0 || TK == TK_Definition) &&
1166 "Nameless record must be a definition!");
1167
1168 Decl::Kind Kind;
1169 switch (TagType) {
1170 default: assert(0 && "Unknown tag type!");
1171 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1172 case DeclSpec::TST_union: Kind = Decl::Union; break;
1173//case DeclSpec::TST_class: Kind = Decl::Class; break;
1174 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1175 }
1176
1177 // If this is a named struct, check to see if there was a previous forward
1178 // declaration or definition.
1179 if (TagDecl *PrevDecl =
1180 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1181 NameLoc, S))) {
1182
1183 // If this is a use of a previous tag, or if the tag is already declared in
1184 // the same scope (so that the definition/declaration completes or
1185 // rementions the tag), reuse the decl.
1186 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1187 // Make sure that this wasn't declared as an enum and now used as a struct
1188 // or something similar.
1189 if (PrevDecl->getKind() != Kind) {
1190 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1191 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1192 }
1193
1194 // If this is a use or a forward declaration, we're good.
1195 if (TK != TK_Definition)
1196 return PrevDecl;
1197
1198 // Diagnose attempts to redefine a tag.
1199 if (PrevDecl->isDefinition()) {
1200 Diag(NameLoc, diag::err_redefinition, Name->getName());
1201 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1202 // If this is a redefinition, recover by making this struct be
1203 // anonymous, which will make any later references get the previous
1204 // definition.
1205 Name = 0;
1206 } else {
1207 // Okay, this is definition of a previously declared or referenced tag.
1208 // Move the location of the decl to be the definition site.
1209 PrevDecl->setLocation(NameLoc);
1210 return PrevDecl;
1211 }
1212 }
1213 // If we get here, this is a definition of a new struct type in a nested
1214 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1215 // type.
1216 }
1217
1218 // If there is an identifier, use the location of the identifier as the
1219 // location of the decl, otherwise use the location of the struct/union
1220 // keyword.
1221 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1222
1223 // Otherwise, if this is the first time we've seen this tag, create the decl.
1224 TagDecl *New;
1225 switch (Kind) {
1226 default: assert(0 && "Unknown tag kind!");
1227 case Decl::Enum:
1228 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1229 // enum X { A, B, C } D; D should chain to X.
1230 New = new EnumDecl(Loc, Name, 0);
1231 // If this is an undefined enum, warn.
1232 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1233 break;
1234 case Decl::Union:
1235 case Decl::Struct:
1236 case Decl::Class:
1237 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1238 // struct X { int A; } D; D should chain to X.
1239 New = new RecordDecl(Kind, Loc, Name, 0);
1240 break;
1241 }
1242
1243 // If this has an identifier, add it to the scope stack.
1244 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001245 // The scope passed in may not be a decl scope. Zip up the scope tree until
1246 // we find one that is.
1247 while ((S->getFlags() & Scope::DeclScope) == 0)
1248 S = S->getParent();
1249
1250 // Add it to the decl chain.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001251 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001252 Name->setFETokenInfo(New);
1253 S->AddDecl(New);
1254 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00001255
Chris Lattner4b009652007-07-25 00:24:17 +00001256 return New;
1257}
1258
Steve Naroff0acc9c92007-09-15 18:49:24 +00001259/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001260/// to create a FieldDecl object for it.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001261Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001262 SourceLocation DeclStart,
1263 Declarator &D, ExprTy *BitfieldWidth) {
1264 IdentifierInfo *II = D.getIdentifier();
1265 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001266 SourceLocation Loc = DeclStart;
1267 if (II) Loc = D.getIdentifierLoc();
1268
1269 // FIXME: Unnamed fields can be handled in various different ways, for
1270 // example, unnamed unions inject all members into the struct namespace!
1271
1272
1273 if (BitWidth) {
1274 // TODO: Validate.
1275 //printf("WARNING: BITFIELDS IGNORED!\n");
1276
1277 // 6.7.2.1p3
1278 // 6.7.2.1p4
1279
1280 } else {
1281 // Not a bitfield.
1282
1283 // validate II.
1284
1285 }
1286
1287 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001288 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1289 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001290
Chris Lattner4b009652007-07-25 00:24:17 +00001291 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1292 // than a variably modified type.
Steve Naroff5eb879b2007-08-31 17:20:07 +00001293 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1294 Diag(Loc, diag::err_typecheck_illegal_vla,
1295 VAT->getSizeExpr()->getSourceRange());
1296 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001297 }
Chris Lattner4b009652007-07-25 00:24:17 +00001298 // FIXME: Chain fielddecls together.
Steve Naroff75494892007-09-11 21:17:26 +00001299 FieldDecl *NewFD;
1300
1301 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patelf616a242007-11-01 16:29:56 +00001302 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Ted Kremenek42730c52008-01-07 19:49:32 +00001303 else if (isa<ObjCInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1304 isa<ObjCImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
1305 isa<ObjCCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroff4fbfb452007-11-14 14:15:31 +00001306 // FIXME: ivars are currently used to model properties, and
1307 // properties can appear within a protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00001308 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1309 isa<ObjCProtocolDecl>(static_cast<Decl *>(TagDecl)))
1310 NewFD = new ObjCIvarDecl(Loc, II, T);
Steve Naroff75494892007-09-11 21:17:26 +00001311 else
Steve Naroff0acc9c92007-09-15 18:49:24 +00001312 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff75494892007-09-11 21:17:26 +00001313
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001314 if (D.getInvalidType() || InvalidDecl)
1315 NewFD->setInvalidDecl();
1316 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001317}
1318
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001319/// TranslateIvarVisibility - Translate visibility from a token ID to an
1320/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00001321static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001322TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001323 switch (ivarVisibility) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001324 case tok::objc_private: return ObjCIvarDecl::Private;
1325 case tok::objc_public: return ObjCIvarDecl::Public;
1326 case tok::objc_protected: return ObjCIvarDecl::Protected;
1327 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001328 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001329 }
1330}
1331
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00001332void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001333 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001334 DeclTy **Fields, unsigned NumFields,
Steve Naroff1a7fa7b2007-10-29 21:38:07 +00001335 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001336 tok::ObjCKeywordKind *visibility) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001337 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1338 assert(EnclosingDecl && "missing record or interface decl");
1339 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1340
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001341 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001342 // Diagnose code like:
1343 // struct S { struct S {} X; };
1344 // We discover this when we complete the outer S. Reject and ignore the
1345 // outer S.
1346 Diag(Record->getLocation(), diag::err_nested_redefinition,
1347 Record->getKindName());
1348 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001349 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001350 return;
1351 }
Chris Lattner4b009652007-07-25 00:24:17 +00001352 // Verify that all the fields are okay.
1353 unsigned NumNamedMembers = 0;
1354 llvm::SmallVector<FieldDecl*, 32> RecFields;
1355 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00001356
Chris Lattner4b009652007-07-25 00:24:17 +00001357 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001358
Steve Naroff9bb759f2007-09-14 22:20:54 +00001359 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1360 assert(FD && "missing field decl");
1361
1362 // Remember all fields.
1363 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00001364
1365 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001366 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +00001367
Steve Naroffffeaa552007-09-14 23:09:53 +00001368 // If we have visibility info, make sure the AST is set accordingly.
1369 if (visibility)
Ted Kremenek42730c52008-01-07 19:49:32 +00001370 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001371 TranslateIvarVisibility(visibility[i]));
Steve Naroffffeaa552007-09-14 23:09:53 +00001372
Chris Lattner4b009652007-07-25 00:24:17 +00001373 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001374 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001375 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00001376 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001377 FD->setInvalidDecl();
1378 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001379 continue;
1380 }
Chris Lattner4b009652007-07-25 00:24:17 +00001381 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1382 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001383 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001384 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001385 FD->setInvalidDecl();
1386 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001387 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001388 }
Chris Lattner4b009652007-07-25 00:24:17 +00001389 if (i != NumFields-1 || // ... that the last member ...
1390 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001391 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001392 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001393 FD->setInvalidDecl();
1394 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001395 continue;
1396 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001397 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00001398 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1399 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001400 FD->setInvalidDecl();
1401 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001402 continue;
1403 }
Chris Lattner4b009652007-07-25 00:24:17 +00001404 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001405 if (Record)
1406 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001407 }
Chris Lattner4b009652007-07-25 00:24:17 +00001408 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1409 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001410 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001411 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1412 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001413 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner4b009652007-07-25 00:24:17 +00001414 Record->setHasFlexibleArrayMember(true);
1415 } else {
1416 // If this is a struct/class and this is not the last element, reject
1417 // it. Note that GCC supports variable sized arrays in the middle of
1418 // structures.
1419 if (i != NumFields-1) {
1420 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1421 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001422 FD->setInvalidDecl();
1423 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001424 continue;
1425 }
Chris Lattner4b009652007-07-25 00:24:17 +00001426 // We support flexible arrays at the end of structs in other structs
1427 // as an extension.
1428 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1429 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001430 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001431 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001432 }
1433 }
1434 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001435 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00001436 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001437 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1438 FD->getName());
1439 FD->setInvalidDecl();
1440 EnclosingDecl->setInvalidDecl();
1441 continue;
1442 }
Chris Lattner4b009652007-07-25 00:24:17 +00001443 // Keep track of the number of named members.
1444 if (IdentifierInfo *II = FD->getIdentifier()) {
1445 // Detect duplicate member names.
1446 if (!FieldIDs.insert(II)) {
1447 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1448 // Find the previous decl.
1449 SourceLocation PrevLoc;
1450 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1451 assert(i != e && "Didn't find previous def!");
1452 if (RecFields[i]->getIdentifier() == II) {
1453 PrevLoc = RecFields[i]->getLocation();
1454 break;
1455 }
1456 }
1457 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001458 FD->setInvalidDecl();
1459 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001460 continue;
1461 }
1462 ++NumNamedMembers;
1463 }
Chris Lattner4b009652007-07-25 00:24:17 +00001464 }
1465
Chris Lattner4b009652007-07-25 00:24:17 +00001466 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00001467 if (Record) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001468 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattner33aad6e2008-02-06 00:51:33 +00001469 Consumer.HandleTagDeclDefinition(Record);
1470 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00001471 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1472 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1473 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1474 else if (ObjCImplementationDecl *IMPDecl =
1475 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001476 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1477 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00001478 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001479 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001480 }
Chris Lattner4b009652007-07-25 00:24:17 +00001481}
1482
Steve Naroff0acc9c92007-09-15 18:49:24 +00001483Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001484 DeclTy *lastEnumConst,
1485 SourceLocation IdLoc, IdentifierInfo *Id,
1486 SourceLocation EqualLoc, ExprTy *val) {
1487 theEnumDecl = theEnumDecl; // silence unused warning.
1488 EnumConstantDecl *LastEnumConst =
1489 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1490 Expr *Val = static_cast<Expr*>(val);
1491
Chris Lattnera7549902007-08-26 06:24:45 +00001492 // The scope passed in may not be a decl scope. Zip up the scope tree until
1493 // we find one that is.
1494 while ((S->getFlags() & Scope::DeclScope) == 0)
1495 S = S->getParent();
1496
Chris Lattner4b009652007-07-25 00:24:17 +00001497 // Verify that there isn't already something declared with this name in this
1498 // scope.
Steve Naroffcb597472007-09-13 21:41:19 +00001499 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1500 IdLoc, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001501 if (S->isDeclScope(PrevDecl)) {
1502 if (isa<EnumConstantDecl>(PrevDecl))
1503 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1504 else
1505 Diag(IdLoc, diag::err_redefinition, Id->getName());
1506 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1507 // FIXME: Don't leak memory: delete Val;
1508 return 0;
1509 }
1510 }
1511
1512 llvm::APSInt EnumVal(32);
1513 QualType EltTy;
1514 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001515 // Make sure to promote the operand type to int.
1516 UsualUnaryConversions(Val);
1517
Chris Lattner4b009652007-07-25 00:24:17 +00001518 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1519 SourceLocation ExpLoc;
1520 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1521 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1522 Id->getName());
1523 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001524 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001525 } else {
1526 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001527 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001528 }
1529
1530 if (!Val) {
1531 if (LastEnumConst) {
1532 // Assign the last value + 1.
1533 EnumVal = LastEnumConst->getInitVal();
1534 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001535
1536 // Check for overflow on increment.
1537 if (EnumVal < LastEnumConst->getInitVal())
1538 Diag(IdLoc, diag::warn_enum_value_overflow);
1539
Chris Lattnere7f53a42007-08-27 17:37:24 +00001540 EltTy = LastEnumConst->getType();
1541 } else {
1542 // First value, set to zero.
1543 EltTy = Context.IntTy;
Chris Lattner3496d522007-09-04 02:45:27 +00001544 EnumVal.zextOrTrunc(
1545 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001546 }
Chris Lattner4b009652007-07-25 00:24:17 +00001547 }
1548
Chris Lattner4b009652007-07-25 00:24:17 +00001549 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1550 LastEnumConst);
1551
1552 // Register this decl in the current scope stack.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001553 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001554 Id->setFETokenInfo(New);
1555 S->AddDecl(New);
1556 return New;
1557}
1558
Steve Naroff0acc9c92007-09-15 18:49:24 +00001559void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00001560 DeclTy **Elements, unsigned NumElements) {
1561 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1562 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1563
Chris Lattner435c3fd2007-08-28 05:10:31 +00001564 // TODO: If the result value doesn't fit in an int, it must be a long or long
1565 // long value. ISO C does not support this, but GCC does as an extension,
1566 // emit a warning.
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001567 unsigned IntWidth =
1568 Context.Target.getIntWidth(Context.getFullLoc(Enum->getLocation()));
Chris Lattner435c3fd2007-08-28 05:10:31 +00001569
1570
Chris Lattner206754a2007-08-28 06:15:15 +00001571 // Verify that all the values are okay, compute the size of the values, and
1572 // reverse the list.
1573 unsigned NumNegativeBits = 0;
1574 unsigned NumPositiveBits = 0;
1575
1576 // Keep track of whether all elements have type int.
1577 bool AllElementsInt = true;
1578
Chris Lattner4b009652007-07-25 00:24:17 +00001579 EnumConstantDecl *EltList = 0;
1580 for (unsigned i = 0; i != NumElements; ++i) {
1581 EnumConstantDecl *ECD =
1582 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1583 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001584
1585 // If the enum value doesn't fit in an int, emit an extension warning.
1586 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1587 "Should have promoted value to int");
1588 const llvm::APSInt &InitVal = ECD->getInitVal();
1589 if (InitVal.getBitWidth() > IntWidth) {
1590 llvm::APSInt V(InitVal);
1591 V.trunc(IntWidth);
1592 V.extend(InitVal.getBitWidth());
1593 if (V != InitVal)
1594 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1595 InitVal.toString());
1596 }
Chris Lattner206754a2007-08-28 06:15:15 +00001597
1598 // Keep track of the size of positive and negative values.
1599 if (InitVal.isUnsigned() || !InitVal.isNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00001600 NumPositiveBits = std::max(NumPositiveBits,
1601 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00001602 else
Chris Lattneraff63f02008-01-14 21:47:29 +00001603 NumNegativeBits = std::max(NumNegativeBits,
1604 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001605
Chris Lattner206754a2007-08-28 06:15:15 +00001606 // Keep track of whether every enum element has type int (very commmon).
1607 if (AllElementsInt)
1608 AllElementsInt = ECD->getType() == Context.IntTy;
1609
Chris Lattner4b009652007-07-25 00:24:17 +00001610 ECD->setNextDeclarator(EltList);
1611 EltList = ECD;
1612 }
1613
Chris Lattner206754a2007-08-28 06:15:15 +00001614 // Figure out the type that should be used for this enum.
1615 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1616 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001617 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001618
1619 if (NumNegativeBits) {
1620 // If there is a negative value, figure out the smallest integer type (of
1621 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001622 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001623 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001624 BestWidth = IntWidth;
1625 } else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001626 BestWidth =
1627 Context.Target.getLongWidth(Context.getFullLoc(Enum->getLocation()));
1628
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001629 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001630 BestType = Context.LongTy;
1631 else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001632 BestWidth = Context.Target.getLongLongWidth(
1633 Context.getFullLoc(Enum->getLocation()));
1634
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001635 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001636 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1637 BestType = Context.LongLongTy;
1638 }
1639 }
1640 } else {
1641 // If there is no negative value, figure out which of uint, ulong, ulonglong
1642 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001643 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001644 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001645 BestWidth = IntWidth;
1646 } else if (NumPositiveBits <=
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001647 (BestWidth = Context.Target.getLongWidth(
1648 Context.getFullLoc(Enum->getLocation()))))
1649
Chris Lattner206754a2007-08-28 06:15:15 +00001650 BestType = Context.UnsignedLongTy;
1651 else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001652 BestWidth =
1653 Context.Target.getLongLongWidth(Context.getFullLoc(Enum->getLocation()));
1654
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001655 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001656 "How could an initializer get larger than ULL?");
1657 BestType = Context.UnsignedLongLongTy;
1658 }
1659 }
1660
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001661 // Loop over all of the enumerator constants, changing their types to match
1662 // the type of the enum if needed.
1663 for (unsigned i = 0; i != NumElements; ++i) {
1664 EnumConstantDecl *ECD =
1665 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1666 if (!ECD) continue; // Already issued a diagnostic.
1667
1668 // Standard C says the enumerators have int type, but we allow, as an
1669 // extension, the enumerators to be larger than int size. If each
1670 // enumerator value fits in an int, type it as an int, otherwise type it the
1671 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1672 // that X has type 'int', not 'unsigned'.
1673 if (ECD->getType() == Context.IntTy)
1674 continue; // Already int type.
1675
1676 // Determine whether the value fits into an int.
1677 llvm::APSInt InitVal = ECD->getInitVal();
1678 bool FitsInInt;
1679 if (InitVal.isUnsigned() || !InitVal.isNegative())
1680 FitsInInt = InitVal.getActiveBits() < IntWidth;
1681 else
1682 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1683
1684 // If it fits into an integer type, force it. Otherwise force it to match
1685 // the enum decl type.
1686 QualType NewTy;
1687 unsigned NewWidth;
1688 bool NewSign;
1689 if (FitsInInt) {
1690 NewTy = Context.IntTy;
1691 NewWidth = IntWidth;
1692 NewSign = true;
1693 } else if (ECD->getType() == BestType) {
1694 // Already the right type!
1695 continue;
1696 } else {
1697 NewTy = BestType;
1698 NewWidth = BestWidth;
1699 NewSign = BestType->isSignedIntegerType();
1700 }
1701
1702 // Adjust the APSInt value.
1703 InitVal.extOrTrunc(NewWidth);
1704 InitVal.setIsSigned(NewSign);
1705 ECD->setInitVal(InitVal);
1706
1707 // Adjust the Expr initializer and type.
1708 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1709 ECD->setType(NewTy);
1710 }
Chris Lattner206754a2007-08-28 06:15:15 +00001711
Chris Lattner90a018d2007-08-28 18:24:31 +00001712 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00001713 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00001714}
1715
Anders Carlsson4f7f4412008-02-08 00:33:21 +00001716Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1717 ExprTy *expr) {
1718 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1719
1720 return new FileScopeAsmDecl(Loc, AsmString);
1721}
1722
Chris Lattner806a5f52008-01-12 07:05:38 +00001723Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
1724 SourceLocation LBrace,
1725 SourceLocation RBrace,
1726 const char *Lang,
1727 unsigned StrSize,
1728 DeclTy *D) {
1729 LinkageSpecDecl::LanguageIDs Language;
1730 Decl *dcl = static_cast<Decl *>(D);
1731 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1732 Language = LinkageSpecDecl::lang_c;
1733 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1734 Language = LinkageSpecDecl::lang_cxx;
1735 else {
1736 Diag(Loc, diag::err_bad_language);
1737 return 0;
1738 }
1739
1740 // FIXME: Add all the various semantics of linkage specifications
1741 return new LinkageSpecDecl(Loc, Language, dcl);
1742}
1743
Chris Lattner4b009652007-07-25 00:24:17 +00001744void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
Anders Carlsson28e34e32007-12-19 06:16:30 +00001745 const char *attrName = rawAttr->getAttributeName()->getName();
1746 unsigned attrLen = rawAttr->getAttributeName()->getLength();
1747
Anders Carlsson5f558b52007-12-19 17:43:24 +00001748 // Normalize the attribute name, __foo__ becomes foo.
1749 if (attrLen > 4 && attrName[0] == '_' && attrName[1] == '_' &&
1750 attrName[attrLen - 2] == '_' && attrName[attrLen - 1] == '_') {
1751 attrName += 2;
1752 attrLen -= 4;
1753 }
1754
1755 if (attrLen == 11 && !memcmp(attrName, "vector_size", 11)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001756 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1757 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1758 if (!newType.isNull()) // install the new vector type into the decl
1759 vDecl->setType(newType);
1760 }
1761 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1762 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1763 rawAttr);
1764 if (!newType.isNull()) // install the new vector type into the decl
1765 tDecl->setUnderlyingType(newType);
1766 }
Anders Carlsson5f558b52007-12-19 17:43:24 +00001767 } else if (attrLen == 15 && !memcmp(attrName, "ocu_vector_type", 15)) {
Steve Naroff82113e32007-07-29 16:33:31 +00001768 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1769 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1770 else
Chris Lattner4b009652007-07-25 00:24:17 +00001771 Diag(rawAttr->getAttributeLoc(),
1772 diag::err_typecheck_ocu_vector_not_typedef);
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001773 } else if (attrLen == 13 && !memcmp(attrName, "address_space", 13)) {
1774 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1775 QualType newType = HandleAddressSpaceTypeAttribute(
1776 tDecl->getUnderlyingType(),
1777 rawAttr);
1778 if (!newType.isNull()) // install the new addr spaced type into the decl
1779 tDecl->setUnderlyingType(newType);
1780 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1781 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
1782 rawAttr);
1783 if (!newType.isNull()) // install the new addr spaced type into the decl
1784 vDecl->setType(newType);
1785 }
Anders Carlssonc8b44122007-12-19 07:19:40 +00001786 } else if (attrLen == 7 && !memcmp(attrName, "aligned", 7)) {
1787 HandleAlignedAttribute(New, rawAttr);
Chris Lattner4b009652007-07-25 00:24:17 +00001788 }
Anders Carlssonc8b44122007-12-19 07:19:40 +00001789
Chris Lattner4b009652007-07-25 00:24:17 +00001790 // FIXME: add other attributes...
1791}
1792
1793void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1794 AttributeList *declarator_postfix) {
1795 while (declspec_prefix) {
1796 HandleDeclAttribute(New, declspec_prefix);
1797 declspec_prefix = declspec_prefix->getNext();
1798 }
1799 while (declarator_postfix) {
1800 HandleDeclAttribute(New, declarator_postfix);
1801 declarator_postfix = declarator_postfix->getNext();
1802 }
1803}
1804
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001805QualType Sema::HandleAddressSpaceTypeAttribute(QualType curType,
1806 AttributeList *rawAttr) {
1807 // check the attribute arugments.
1808 if (rawAttr->getNumArgs() != 1) {
1809 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1810 std::string("1"));
1811 return QualType();
1812 }
1813 Expr *addrSpaceExpr = static_cast<Expr *>(rawAttr->getArg(0));
1814 llvm::APSInt addrSpace(32);
1815 if (!addrSpaceExpr->isIntegerConstantExpr(addrSpace, Context)) {
1816 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_address_space_not_int,
1817 addrSpaceExpr->getSourceRange());
1818 return QualType();
1819 }
1820 unsigned addressSpace = static_cast<unsigned>(addrSpace.getZExtValue());
1821
1822 // Zero is the default memory space, so no qualification is needed
1823 if (addressSpace == 0)
1824 return curType;
1825
1826 // TODO: Should we convert contained types of address space
1827 // qualified types here or or where they directly participate in conversions
1828 // (i.e. elsewhere)
1829
1830 return Context.getASQualType(curType, addressSpace);
1831}
1832
Steve Naroff82113e32007-07-29 16:33:31 +00001833void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1834 AttributeList *rawAttr) {
1835 QualType curType = tDecl->getUnderlyingType();
Anders Carlssonc8b44122007-12-19 07:19:40 +00001836 // check the attribute arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001837 if (rawAttr->getNumArgs() != 1) {
1838 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1839 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001840 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001841 }
1842 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1843 llvm::APSInt vecSize(32);
1844 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1845 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1846 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001847 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001848 }
1849 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1850 // in conjunction with complex types (pointers, arrays, functions, etc.).
1851 Type *canonType = curType.getCanonicalType().getTypePtr();
1852 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1853 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1854 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001855 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001856 }
1857 // unlike gcc's vector_size attribute, the size is specified as the
1858 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00001859 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00001860
1861 if (vectorSize == 0) {
1862 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1863 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001864 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001865 }
Steve Naroff82113e32007-07-29 16:33:31 +00001866 // Instantiate/Install the vector type, the number of elements is > 0.
1867 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1868 // Remember this typedef decl, we will need it later for diagnostics.
1869 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001870}
1871
1872QualType Sema::HandleVectorTypeAttribute(QualType curType,
1873 AttributeList *rawAttr) {
1874 // check the attribute arugments.
1875 if (rawAttr->getNumArgs() != 1) {
1876 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1877 std::string("1"));
1878 return QualType();
1879 }
1880 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1881 llvm::APSInt vecSize(32);
1882 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1883 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1884 sizeExpr->getSourceRange());
1885 return QualType();
1886 }
1887 // navigate to the base type - we need to provide for vector pointers,
1888 // vector arrays, and functions returning vectors.
1889 Type *canonType = curType.getCanonicalType().getTypePtr();
1890
1891 if (canonType->isPointerType() || canonType->isArrayType() ||
1892 canonType->isFunctionType()) {
Chris Lattner5b5e1982007-12-19 05:38:06 +00001893 assert(0 && "HandleVector(): Complex type construction unimplemented");
Chris Lattner4b009652007-07-25 00:24:17 +00001894 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1895 do {
1896 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1897 canonType = PT->getPointeeType().getTypePtr();
1898 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1899 canonType = AT->getElementType().getTypePtr();
1900 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1901 canonType = FT->getResultType().getTypePtr();
1902 } while (canonType->isPointerType() || canonType->isArrayType() ||
1903 canonType->isFunctionType());
1904 */
1905 }
1906 // the base type must be integer or float.
1907 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1908 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1909 curType.getCanonicalType().getAsString());
1910 return QualType();
1911 }
Chris Lattner3496d522007-09-04 02:45:27 +00001912 unsigned typeSize = static_cast<unsigned>(
1913 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Chris Lattner4b009652007-07-25 00:24:17 +00001914 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00001915 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00001916
1917 // the vector size needs to be an integral multiple of the type size.
1918 if (vectorSize % typeSize) {
1919 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1920 sizeExpr->getSourceRange());
1921 return QualType();
1922 }
1923 if (vectorSize == 0) {
1924 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1925 sizeExpr->getSourceRange());
1926 return QualType();
1927 }
1928 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1929 // the number of elements to be a power of two (unlike GCC).
1930 // Instantiate the vector type, the number of elements is > 0.
1931 return Context.getVectorType(curType, vectorSize/typeSize);
1932}
1933
Anders Carlssonc8b44122007-12-19 07:19:40 +00001934void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
1935{
1936 // check the attribute arguments.
Eli Friedman74820702008-01-30 17:38:42 +00001937 if (rawAttr->getNumArgs() > 1) {
Anders Carlssonc8b44122007-12-19 07:19:40 +00001938 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1939 std::string("1"));
1940 return;
1941 }
Eli Friedman74820702008-01-30 17:38:42 +00001942
Devang Patela31965b2008-01-30 18:00:07 +00001943 // TODO: We probably need to actually do something with aligned attribute.
Eli Friedman74820702008-01-30 17:38:42 +00001944 if (rawAttr->getNumArgs() == 0)
1945 return;
1946
Anders Carlssonc8b44122007-12-19 07:19:40 +00001947 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
1948 llvm::APSInt alignment(32);
1949 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
1950 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1951 alignmentExpr->getSourceRange());
1952 return;
1953 }
1954}