blob: 6b528b6bed4dc4e0a45207c6c0d48caa75f6e6e8 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Anders Carlssonf78915f2008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/Builtins.h"
19#include "clang/AST/Decl.h"
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +000020#include "clang/AST/DeclCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/AST/Expr.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000022#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/AST/Type.h"
24#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "clang/Basic/LangOptions.h"
27#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000028#include "clang/Basic/SourceManager.h"
29// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000030#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000031#include "clang/Lex/HeaderSearch.h"
Steve Naroff563477d2007-09-18 23:55:05 +000032#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000034#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
36
Steve Naroffb327ce02008-04-02 14:35:35 +000037Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
38 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
39
Douglas Gregor2ce52f32008-04-13 21:07:44 +000040 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
41 isa<ObjCInterfaceDecl>(IIDecl) ||
42 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000043 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000044 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000045}
46
Chris Lattner9fdf9c62008-04-22 18:39:57 +000047void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000048 assert( ( (isa<ObjCMethodDecl>(DC) && isa<TranslationUnitDecl>(CurContext))
Chris Lattner9fdf9c62008-04-22 18:39:57 +000049 || DC->getParent() == CurContext ) &&
Chris Lattnerb048c982008-04-06 04:47:34 +000050 "The next DeclContext should be directly contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000051 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000052}
53
Chris Lattnerb048c982008-04-06 04:47:34 +000054void Sema::PopDeclContext() {
55 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000056 // If CurContext is a ObjC method, getParent() will return NULL.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000057 CurContext = isa<ObjCMethodDecl>(CurContext)
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000058 ? Context.getTranslationUnitDecl()
59 : CurContext->getParent();
Chris Lattner0ed844b2008-04-04 06:12:32 +000060}
61
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000062/// Add this decl to the scope shadowed decl chains.
63void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000064 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000065
66 // C++ [basic.scope]p4:
67 // -- exactly one declaration shall declare a class name or
68 // enumeration name that is not a typedef name and the other
69 // declarations shall all refer to the same object or
70 // enumerator, or all refer to functions and function templates;
71 // in this case the class name or enumeration name is hidden.
72 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
73 // We are pushing the name of a tag (enum or class).
74 IdentifierResolver::ctx_iterator
75 CIT = IdResolver.ctx_begin(TD->getIdentifier(), TD->getDeclContext());
76 if (CIT != IdResolver.ctx_end(TD->getIdentifier()) &&
77 IdResolver.isDeclInScope(*CIT, TD->getDeclContext(), S)) {
78 // There is already a declaration with the same name in the same
79 // scope. It must be found before we find the new declaration,
80 // so swap the order on the shadowed declaration chain.
81
82 IdResolver.AddShadowedDecl(TD, *CIT);
83 return;
84 }
85 }
86
87 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000088}
89
Steve Naroffb216c882007-10-09 22:01:59 +000090void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000091 if (S->decl_empty()) return;
92 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000093
Reid Spencer5f016e22007-07-11 17:01:13 +000094 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
95 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000096 Decl *TmpD = static_cast<Decl*>(*I);
97 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +000098
99 if (isa<CXXFieldDecl>(TmpD)) continue;
100
101 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
102 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000103
Reid Spencer5f016e22007-07-11 17:01:13 +0000104 IdentifierInfo *II = D->getIdentifier();
105 if (!II) continue;
106
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000107 // We only want to remove the decls from the identifier decl chains for local
108 // scopes, when inside a function/method.
109 if (S->getFnParent() != 0)
110 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000111
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000112 // Chain this decl to the containing DeclContext.
113 D->setNext(CurContext->getDeclChain());
114 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 }
116}
117
Steve Naroffe8043c32008-04-01 23:04:06 +0000118/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
119/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000120ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000121 // The third "scope" argument is 0 since we aren't enabling lazy built-in
122 // creation from this context.
123 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000124
Steve Naroffb327ce02008-04-02 14:35:35 +0000125 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000126}
127
Steve Naroffe8043c32008-04-01 23:04:06 +0000128/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000129/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000130Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
131 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000133 unsigned NS = NSI;
134 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
135 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000136
Reid Spencer5f016e22007-07-11 17:01:13 +0000137 // Scan up the scope chain looking for a decl that matches this identifier
138 // that is in the appropriate namespace. This search should not take long, as
139 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000140 for (IdentifierResolver::iterator
141 I = IdResolver.begin(II, CurContext), E = IdResolver.end(II); I != E; ++I)
142 if ((*I)->getIdentifierNamespace() & NS)
143 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000144
Reid Spencer5f016e22007-07-11 17:01:13 +0000145 // If we didn't find a use of this identifier, and if the identifier
146 // corresponds to a compiler builtin, create the decl object for the builtin
147 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000148 if (NS & Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000149 if (enableLazyBuiltinCreation) {
150 // If this is a builtin on this (or all) targets, create the decl.
151 if (unsigned BuiltinID = II->getBuiltinID())
152 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
153 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000154 if (getLangOptions().ObjC1) {
155 // @interface and @compatibility_alias introduce typedef-like names.
156 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000157 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000158 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000159 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
160 if (IDI != ObjCInterfaceDecls.end())
161 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000162 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
163 if (I != ObjCAliasDecls.end())
164 return I->second->getClassInterface();
165 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000166 }
167 return 0;
168}
169
Chris Lattner95e2c712008-05-05 22:18:14 +0000170void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000171 if (!Context.getBuiltinVaListType().isNull())
172 return;
173
174 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000175 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000176 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000177 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
178}
179
Reid Spencer5f016e22007-07-11 17:01:13 +0000180/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
181/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000182ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
183 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 Builtin::ID BID = (Builtin::ID)bid;
185
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000186 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattner95e2c712008-05-05 22:18:14 +0000187 BID == Builtin::BI__builtin_va_copy ||
188 BID == Builtin::BI__builtin_va_end)
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000189 InitBuiltinVaListType();
190
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000191 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000192 FunctionDecl *New = FunctionDecl::Create(Context,
193 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000194 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000195 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000196
Chris Lattner95e2c712008-05-05 22:18:14 +0000197 // Create Decl objects for each parameter, adding them to the
198 // FunctionDecl.
199 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
200 llvm::SmallVector<ParmVarDecl*, 16> Params;
201 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
202 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
203 FT->getArgType(i), VarDecl::None, 0,
204 0));
205 New->setParams(&Params[0], Params.size());
206 }
207
208
209
Chris Lattner7f925cc2008-04-11 07:00:53 +0000210 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000211 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000212 return New;
213}
214
215/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
216/// and scope as a previous declaration 'Old'. Figure out how to resolve this
217/// situation, merging decls or emitting diagnostics as appropriate.
218///
Steve Naroffe8043c32008-04-01 23:04:06 +0000219TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000220 // Verify the old decl was also a typedef.
221 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
222 if (!Old) {
223 Diag(New->getLocation(), diag::err_redefinition_different_kind,
224 New->getName());
225 Diag(OldD->getLocation(), diag::err_previous_definition);
226 return New;
227 }
228
Steve Naroff8ee529b2007-10-31 18:42:27 +0000229 // Allow multiple definitions for ObjC built-in typedefs.
230 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000231 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000232 return Old;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000233
234 if (getLangOptions().Microsoft) return New;
235
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000236 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
237 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
238 // *either* declaration is in a system header. The code below implements
239 // this adhoc compatibility rule. FIXME: The following code will not
240 // work properly when compiling ".i" files (containing preprocessed output).
241 SourceManager &SrcMgr = Context.getSourceManager();
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000242 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
Eli Friedman54ecfce2008-06-11 06:20:39 +0000243 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
244 if (OldDeclFile) {
245 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
246 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
247 if (OldDirType != DirectoryLookup::NormalHeaderDir)
248 return New;
249 }
250 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
251 if (NewDeclFile) {
252 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
253 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
254 if (NewDirType != DirectoryLookup::NormalHeaderDir)
255 return New;
256 }
257
Ted Kremenek2d05c082008-05-23 21:28:18 +0000258 Diag(New->getLocation(), diag::err_redefinition, New->getName());
259 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000260 return New;
261}
262
Chris Lattner6b6b5372008-06-26 18:38:35 +0000263/// DeclhasAttr - returns true if decl Declaration already has the target
264/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000265static bool DeclHasAttr(const Decl *decl, const Attr *target) {
266 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
267 if (attr->getKind() == target->getKind())
268 return true;
269
270 return false;
271}
272
273/// MergeAttributes - append attributes from the Old decl to the New one.
274static void MergeAttributes(Decl *New, Decl *Old) {
275 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
276
Chris Lattnerddee4232008-03-03 03:28:21 +0000277 while (attr) {
278 tmp = attr;
279 attr = attr->getNext();
280
281 if (!DeclHasAttr(New, tmp)) {
282 New->addAttr(tmp);
283 } else {
284 tmp->setNext(0);
285 delete(tmp);
286 }
287 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000288
289 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000290}
291
Chris Lattner04421082008-04-08 04:40:51 +0000292/// MergeFunctionDecl - We just parsed a function 'New' from
293/// declarator D which has the same name and scope as a previous
294/// declaration 'Old'. Figure out how to resolve this situation,
295/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000296/// Redeclaration will be set true if thisNew is a redeclaration OldD.
297FunctionDecl *
298Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
299 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 // Verify the old decl was also a function.
301 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
302 if (!Old) {
303 Diag(New->getLocation(), diag::err_redefinition_different_kind,
304 New->getName());
305 Diag(OldD->getLocation(), diag::err_previous_definition);
306 return New;
307 }
Chris Lattner04421082008-04-08 04:40:51 +0000308
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000309 QualType OldQType = Context.getCanonicalType(Old->getType());
310 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000311
Chris Lattner04421082008-04-08 04:40:51 +0000312 // C++ [dcl.fct]p3:
313 // All declarations for a function shall agree exactly in both the
314 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000315 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
316 MergeAttributes(New, Old);
317 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000318 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000319 }
Chris Lattner04421082008-04-08 04:40:51 +0000320
321 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000322 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000323 if (!getLangOptions().CPlusPlus &&
324 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000325 MergeAttributes(New, Old);
326 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000327 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000328 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000329
Steve Naroff837618c2008-01-16 15:01:34 +0000330 // A function that has already been declared has been redeclared or defined
331 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000332 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000333 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000334 PrevDiag = diag::err_previous_definition;
335 else if (Old->isImplicit())
336 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000337 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000338 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000339
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
341 // TODO: This is totally simplistic. It should handle merging functions
342 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000343 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
344 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 return New;
346}
347
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000348/// equivalentArrayTypes - Used to determine whether two array types are
349/// equivalent.
350/// We need to check this explicitly as an incomplete array definition is
351/// considered a VariableArrayType, so will not match a complete array
352/// definition that would be otherwise equivalent.
353static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
354 const ArrayType *NewAT = NewQType->getAsArrayType();
355 const ArrayType *OldAT = OldQType->getAsArrayType();
356
357 if (!NewAT || !OldAT)
358 return false;
359
360 // If either (or both) array types in incomplete we need to strip off the
361 // outer VariableArrayType. Once the outer VAT is removed the remaining
362 // types must be identical if the array types are to be considered
363 // equivalent.
364 // eg. int[][1] and int[1][1] become
365 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
366 // removing the outermost VAT gives
367 // CAT(1, int) and CAT(1, int)
368 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000369 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000370 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
371 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000372 NewQType = NewAT->getElementType().getCanonicalType();
373 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000374 }
375
376 return NewQType == OldQType;
377}
378
Reid Spencer5f016e22007-07-11 17:01:13 +0000379/// MergeVarDecl - We just parsed a variable 'New' which has the same name
380/// and scope as a previous declaration 'Old'. Figure out how to resolve this
381/// situation, merging decls or emitting diagnostics as appropriate.
382///
383/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
384/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
385///
Steve Naroffe8043c32008-04-01 23:04:06 +0000386VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 // Verify the old decl was also a variable.
388 VarDecl *Old = dyn_cast<VarDecl>(OldD);
389 if (!Old) {
390 Diag(New->getLocation(), diag::err_redefinition_different_kind,
391 New->getName());
392 Diag(OldD->getLocation(), diag::err_previous_definition);
393 return New;
394 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000395
396 MergeAttributes(New, Old);
397
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000399 QualType OldCType = Context.getCanonicalType(Old->getType());
400 QualType NewCType = Context.getCanonicalType(New->getType());
401 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 Diag(New->getLocation(), diag::err_redefinition, New->getName());
403 Diag(Old->getLocation(), diag::err_previous_definition);
404 return New;
405 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000406 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
407 if (New->getStorageClass() == VarDecl::Static &&
408 (Old->getStorageClass() == VarDecl::None ||
409 Old->getStorageClass() == VarDecl::Extern)) {
410 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
411 Diag(Old->getLocation(), diag::err_previous_definition);
412 return New;
413 }
414 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
415 if (New->getStorageClass() != VarDecl::Static &&
416 Old->getStorageClass() == VarDecl::Static) {
417 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
418 Diag(Old->getLocation(), diag::err_previous_definition);
419 return New;
420 }
421 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff248a7532008-04-15 22:42:06 +0000422 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb7b032e2008-01-30 00:44:01 +0000423 // Handle C "tentative" external object definitions (C99 6.9.2).
424 bool OldIsTentative = false;
425 bool NewIsTentative = false;
426
Steve Naroff248a7532008-04-15 22:42:06 +0000427 if (!Old->getInit() &&
428 (Old->getStorageClass() == VarDecl::None ||
429 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000430 OldIsTentative = true;
431
432 // FIXME: this check doesn't work (since the initializer hasn't been
433 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
434 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
435 // thrown out the old decl.
Steve Naroff248a7532008-04-15 22:42:06 +0000436 if (!New->getInit() &&
437 (New->getStorageClass() == VarDecl::None ||
438 New->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000439 ; // change to NewIsTentative = true; once the code is moved.
440
441 if (NewIsTentative || OldIsTentative)
442 return New;
443 }
Steve Naroff235549c2008-05-12 22:36:43 +0000444 // Handle __private_extern__ just like extern.
Steve Naroffb7b032e2008-01-30 00:44:01 +0000445 if (Old->getStorageClass() != VarDecl::Extern &&
Steve Naroff235549c2008-05-12 22:36:43 +0000446 Old->getStorageClass() != VarDecl::PrivateExtern &&
447 New->getStorageClass() != VarDecl::Extern &&
448 New->getStorageClass() != VarDecl::PrivateExtern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000449 Diag(New->getLocation(), diag::err_redefinition, New->getName());
450 Diag(Old->getLocation(), diag::err_previous_definition);
451 }
452 return New;
453}
454
Chris Lattner04421082008-04-08 04:40:51 +0000455/// CheckParmsForFunctionDef - Check that the parameters of the given
456/// function are appropriate for the definition of a function. This
457/// takes care of any checks that cannot be performed on the
458/// declaration itself, e.g., that the types of each of the function
459/// parameters are complete.
460bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
461 bool HasInvalidParm = false;
462 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
463 ParmVarDecl *Param = FD->getParamDecl(p);
464
465 // C99 6.7.5.3p4: the parameters in a parameter type list in a
466 // function declarator that is part of a function definition of
467 // that function shall not have incomplete type.
468 if (Param->getType()->isIncompleteType() &&
469 !Param->isInvalidDecl()) {
470 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
471 Param->getType().getAsString());
472 Param->setInvalidDecl();
473 HasInvalidParm = true;
474 }
475 }
476
477 return HasInvalidParm;
478}
479
480/// CreateImplicitParameter - Creates an implicit function parameter
481/// in the scope S and with the given type. This routine is used, for
482/// example, to create the implicit "self" parameter in an Objective-C
483/// method.
Chris Lattner41110242008-06-17 18:05:57 +0000484ImplicitParamDecl *
Chris Lattner04421082008-04-08 04:40:51 +0000485Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
486 SourceLocation IdLoc, QualType Type) {
Chris Lattner41110242008-06-17 18:05:57 +0000487 ImplicitParamDecl *New = ImplicitParamDecl::Create(Context, CurContext,
488 IdLoc, Id, Type, 0);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000489 if (Id)
490 PushOnScopeChains(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000491
492 return New;
493}
494
Reid Spencer5f016e22007-07-11 17:01:13 +0000495/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
496/// no declarator (e.g. "struct foo;") is parsed.
497Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
498 // TODO: emit error on 'int;' or 'const enum foo;'.
499 // TODO: emit error on 'typedef int;'
500 // if (!DS.isMissingDeclaratorOk()) Diag(...);
501
Steve Naroff92199282007-11-17 21:37:36 +0000502 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000503}
504
Steve Naroffd0091aa2008-01-10 22:15:12 +0000505bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000506 // Get the type before calling CheckSingleAssignmentConstraints(), since
507 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000508 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000509
Chris Lattner5cf216b2008-01-04 18:04:52 +0000510 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
511 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
512 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000513}
514
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000515bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000516 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000517 // C99 6.7.8p14. We have an array of character type with unknown size
518 // being initialized to a string literal.
519 llvm::APSInt ConstVal(32);
520 ConstVal = strLiteral->getByteLength() + 1;
521 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000522 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000523 ArrayType::Normal, 0);
524 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
525 // C99 6.7.8p14. We have an array of character type with known size.
526 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
527 Diag(strLiteral->getSourceRange().getBegin(),
528 diag::warn_initializer_string_for_char_array_too_long,
529 strLiteral->getSourceRange());
530 } else {
531 assert(0 && "HandleStringLiteralInit(): Invalid array type");
532 }
533 // Set type from "char *" to "constant array of char".
534 strLiteral->setType(DeclT);
535 // For now, we always return false (meaning success).
536 return false;
537}
538
539StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000540 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000541 if (AT && AT->getElementType()->isCharType()) {
542 return dyn_cast<StringLiteral>(Init);
543 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000544 return 0;
545}
546
Steve Naroffa9960332008-01-25 00:51:06 +0000547bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000548 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
549 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000550 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000551 return Diag(VAT->getSizeExpr()->getLocStart(),
552 diag::err_variable_object_no_init,
553 VAT->getSizeExpr()->getSourceRange());
554
Steve Naroff2fdc3742007-12-10 22:44:33 +0000555 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
556 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000557 // FIXME: Handle wide strings
558 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
559 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000560
561 if (DeclType->isArrayType())
562 return Diag(Init->getLocStart(),
563 diag::err_array_init_list_required,
564 Init->getSourceRange());
565
Steve Naroffd0091aa2008-01-10 22:15:12 +0000566 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000567 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000568
Steve Naroff0cca7492008-05-01 22:18:59 +0000569 InitListChecker CheckInitList(this, InitList, DeclType);
570 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000571}
572
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000573Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000574Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000575 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000576 IdentifierInfo *II = D.getIdentifier();
577
Chris Lattnere80a59c2007-07-25 00:24:17 +0000578 // All of these full declarators require an identifier. If it doesn't have
579 // one, the ParsedFreeStandingDeclSpec action should be used.
580 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000581 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000582 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000583 D.getDeclSpec().getSourceRange(), D.getSourceRange());
584 return 0;
585 }
586
Chris Lattner31e05722007-08-26 06:24:45 +0000587 // The scope passed in may not be a decl scope. Zip up the scope tree until
588 // we find one that is.
589 while ((S->getFlags() & Scope::DeclScope) == 0)
590 S = S->getParent();
591
Reid Spencer5f016e22007-07-11 17:01:13 +0000592 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000593 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000594 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000595 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000596
597 // In C++, the previous declaration we find might be a tag type
598 // (class or enum). In this case, the new declaration will hide the
599 // tag type.
600 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
601 PrevDecl = 0;
602
Chris Lattner41af0932007-11-14 06:34:38 +0000603 QualType R = GetTypeForDeclarator(D, S);
604 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
605
Reid Spencer5f016e22007-07-11 17:01:13 +0000606 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000607 // Check that there are no default arguments (C++ only).
608 if (getLangOptions().CPlusPlus)
609 CheckExtraCXXDefaultArguments(D);
610
Chris Lattner41af0932007-11-14 06:34:38 +0000611 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000612 if (!NewTD) return 0;
613
614 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000615 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000616 // Merge the decl with the existing one if appropriate. If the decl is
617 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000618 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000619 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
620 if (NewTD == 0) return 0;
621 }
622 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000623 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000624 // C99 6.7.7p2: If a typedef name specifies a variably modified type
625 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000626 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
627 // FIXME: Diagnostic needs to be fixed.
628 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000629 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000630 }
631 }
Chris Lattner41af0932007-11-14 06:34:38 +0000632 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000633 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000634 switch (D.getDeclSpec().getStorageClassSpec()) {
635 default: assert(0 && "Unknown storage class!");
636 case DeclSpec::SCS_auto:
637 case DeclSpec::SCS_register:
638 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
639 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000640 InvalidDecl = true;
641 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000642 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
643 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
644 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000645 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000646 }
647
Chris Lattnera98e58d2008-03-15 21:24:04 +0000648 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattner0ed844b2008-04-04 06:12:32 +0000649 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
650 D.getIdentifierLoc(),
Chris Lattnera98e58d2008-03-15 21:24:04 +0000651 II, R, SC, isInline,
652 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000653 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000654 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000655
656 // Copy the parameter declarations from the declarator D to
657 // the function declaration NewFD, if they are available.
658 if (D.getNumTypeObjects() > 0 &&
659 D.getTypeObject(0).Fun.hasPrototype) {
660 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
661
662 // Create Decl objects for each parameter, adding them to the
663 // FunctionDecl.
664 llvm::SmallVector<ParmVarDecl*, 16> Params;
665
666 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
667 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000668 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000669 // We let through "const void" here because Sema::GetTypeForDeclarator
670 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000671 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
672 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000673 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
674 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000675 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
676
Chris Lattnerdef026a2008-04-10 02:26:16 +0000677 // In C++, the empty parameter-type-list must be spelled "void"; a
678 // typedef of void is not permitted.
679 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000680 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000681 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
682 }
683
Chris Lattner04421082008-04-08 04:40:51 +0000684 } else {
685 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
686 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
687 }
688
689 NewFD->setParams(&Params[0], Params.size());
690 }
691
Steve Naroffffce4d52008-01-09 23:34:55 +0000692 // Merge the decl with the existing one if appropriate. Since C functions
693 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000694 if (PrevDecl &&
695 (!getLangOptions().CPlusPlus ||
696 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000697 bool Redeclaration = false;
698 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 if (NewFD == 0) return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +0000700 if (Redeclaration) {
Eli Friedman27424962008-05-27 05:07:37 +0000701 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregorf0097952008-04-21 02:02:58 +0000702 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000703 }
704 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000705
706 // In C++, check default arguments now that we have merged decls.
707 if (getLangOptions().CPlusPlus)
708 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000710 // Check that there are no default arguments (C++ only).
711 if (getLangOptions().CPlusPlus)
712 CheckExtraCXXDefaultArguments(D);
713
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000714 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000715 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
716 D.getIdentifier()->getName());
717 InvalidDecl = true;
718 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000719
720 VarDecl *NewVD;
721 VarDecl::StorageClass SC;
722 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000723 default: assert(0 && "Unknown storage class!");
724 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
725 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
726 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
727 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
728 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
729 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000731 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000732 // C99 6.9p2: The storage-class specifiers auto and register shall not
733 // appear in the declaration specifiers in an external declaration.
734 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
735 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
736 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000737 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 }
Steve Naroff248a7532008-04-15 22:42:06 +0000739 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
740 II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000741 } else {
Steve Naroff248a7532008-04-15 22:42:06 +0000742 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
743 II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000744 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000746 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +0000747
748 // Emit an error if an address space was applied to decl with local storage.
749 // This includes arrays of objects with address space qualifiers, but not
750 // automatic variables that point to other address spaces.
751 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000752 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
753 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
754 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000755 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000756 // Merge the decl with the existing one if appropriate. If the decl is
757 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000758 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000759 NewVD = MergeVarDecl(NewVD, PrevDecl);
760 if (NewVD == 0) return 0;
761 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 New = NewVD;
763 }
764
765 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000766 if (II)
767 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000768 // If any semantic error occurred, mark the decl as invalid.
769 if (D.getInvalidType() || InvalidDecl)
770 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000771
772 return New;
773}
774
Eli Friedmanc594b322008-05-20 13:48:25 +0000775bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
776 switch (Init->getStmtClass()) {
777 default:
778 Diag(Init->getExprLoc(),
779 diag::err_init_element_not_constant, Init->getSourceRange());
780 return true;
781 case Expr::ParenExprClass: {
782 const ParenExpr* PE = cast<ParenExpr>(Init);
783 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
784 }
785 case Expr::CompoundLiteralExprClass:
786 return cast<CompoundLiteralExpr>(Init)->isFileScope();
787 case Expr::DeclRefExprClass: {
788 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +0000789 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
790 if (VD->hasGlobalStorage())
791 return false;
792 Diag(Init->getExprLoc(),
793 diag::err_init_element_not_constant, Init->getSourceRange());
794 return true;
795 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000796 if (isa<FunctionDecl>(D))
797 return false;
798 Diag(Init->getExprLoc(),
799 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Naroffd0091aa2008-01-10 22:15:12 +0000800 return true;
801 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000802 case Expr::MemberExprClass: {
803 const MemberExpr *M = cast<MemberExpr>(Init);
804 if (M->isArrow())
805 return CheckAddressConstantExpression(M->getBase());
806 return CheckAddressConstantExpressionLValue(M->getBase());
807 }
808 case Expr::ArraySubscriptExprClass: {
809 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
810 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
811 return CheckAddressConstantExpression(ASE->getBase()) ||
812 CheckArithmeticConstantExpression(ASE->getIdx());
813 }
814 case Expr::StringLiteralClass:
815 case Expr::PreDefinedExprClass:
816 return false;
817 case Expr::UnaryOperatorClass: {
818 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
819
820 // C99 6.6p9
821 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +0000822 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +0000823
824 Diag(Init->getExprLoc(),
825 diag::err_init_element_not_constant, Init->getSourceRange());
826 return true;
827 }
828 }
829}
830
831bool Sema::CheckAddressConstantExpression(const Expr* Init) {
832 switch (Init->getStmtClass()) {
833 default:
834 Diag(Init->getExprLoc(),
835 diag::err_init_element_not_constant, Init->getSourceRange());
836 return true;
837 case Expr::ParenExprClass: {
838 const ParenExpr* PE = cast<ParenExpr>(Init);
839 return CheckAddressConstantExpression(PE->getSubExpr());
840 }
841 case Expr::StringLiteralClass:
842 case Expr::ObjCStringLiteralClass:
843 return false;
844 case Expr::CallExprClass: {
845 const CallExpr *CE = cast<CallExpr>(Init);
846 if (CE->isBuiltinConstantExpr())
847 return false;
848 Diag(Init->getExprLoc(),
849 diag::err_init_element_not_constant, Init->getSourceRange());
850 return true;
851 }
852 case Expr::UnaryOperatorClass: {
853 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
854
855 // C99 6.6p9
856 if (Exp->getOpcode() == UnaryOperator::AddrOf)
857 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
858
859 if (Exp->getOpcode() == UnaryOperator::Extension)
860 return CheckAddressConstantExpression(Exp->getSubExpr());
861
862 Diag(Init->getExprLoc(),
863 diag::err_init_element_not_constant, Init->getSourceRange());
864 return true;
865 }
866 case Expr::BinaryOperatorClass: {
867 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
868 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
869
870 Expr *PExp = Exp->getLHS();
871 Expr *IExp = Exp->getRHS();
872 if (IExp->getType()->isPointerType())
873 std::swap(PExp, IExp);
874
875 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
876 return CheckAddressConstantExpression(PExp) ||
877 CheckArithmeticConstantExpression(IExp);
878 }
879 case Expr::ImplicitCastExprClass: {
880 const Expr* SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
881
882 // Check for implicit promotion
883 if (SubExpr->getType()->isFunctionType() ||
884 SubExpr->getType()->isArrayType())
885 return CheckAddressConstantExpressionLValue(SubExpr);
886
887 // Check for pointer->pointer cast
888 if (SubExpr->getType()->isPointerType())
889 return CheckAddressConstantExpression(SubExpr);
890
891 if (SubExpr->getType()->isArithmeticType())
892 return CheckArithmeticConstantExpression(SubExpr);
893
894 Diag(Init->getExprLoc(),
895 diag::err_init_element_not_constant, Init->getSourceRange());
896 return true;
897 }
898 case Expr::CastExprClass: {
899 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
900
901 // Check for pointer->pointer cast
902 if (SubExpr->getType()->isPointerType())
903 return CheckAddressConstantExpression(SubExpr);
904
905 // FIXME: Should we pedwarn for (int*)(0+0)?
906 if (SubExpr->getType()->isArithmeticType())
907 return CheckArithmeticConstantExpression(SubExpr);
908
909 Diag(Init->getExprLoc(),
910 diag::err_init_element_not_constant, Init->getSourceRange());
911 return true;
912 }
913 case Expr::ConditionalOperatorClass: {
914 // FIXME: Should we pedwarn here?
915 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
916 if (!Exp->getCond()->getType()->isArithmeticType()) {
917 Diag(Init->getExprLoc(),
918 diag::err_init_element_not_constant, Init->getSourceRange());
919 return true;
920 }
921 if (CheckArithmeticConstantExpression(Exp->getCond()))
922 return true;
923 if (Exp->getLHS() &&
924 CheckAddressConstantExpression(Exp->getLHS()))
925 return true;
926 return CheckAddressConstantExpression(Exp->getRHS());
927 }
928 case Expr::AddrLabelExprClass:
929 return false;
930 }
931}
932
Eli Friedman4caf0552008-06-09 05:05:07 +0000933static const Expr* FindExpressionBaseAddress(const Expr* E);
934
935static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
936 switch (E->getStmtClass()) {
937 default:
938 return E;
939 case Expr::ParenExprClass: {
940 const ParenExpr* PE = cast<ParenExpr>(E);
941 return FindExpressionBaseAddressLValue(PE->getSubExpr());
942 }
943 case Expr::MemberExprClass: {
944 const MemberExpr *M = cast<MemberExpr>(E);
945 if (M->isArrow())
946 return FindExpressionBaseAddress(M->getBase());
947 return FindExpressionBaseAddressLValue(M->getBase());
948 }
949 case Expr::ArraySubscriptExprClass: {
950 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
951 return FindExpressionBaseAddress(ASE->getBase());
952 }
953 case Expr::UnaryOperatorClass: {
954 const UnaryOperator *Exp = cast<UnaryOperator>(E);
955
956 if (Exp->getOpcode() == UnaryOperator::Deref)
957 return FindExpressionBaseAddress(Exp->getSubExpr());
958
959 return E;
960 }
961 }
962}
963
964static const Expr* FindExpressionBaseAddress(const Expr* E) {
965 switch (E->getStmtClass()) {
966 default:
967 return E;
968 case Expr::ParenExprClass: {
969 const ParenExpr* PE = cast<ParenExpr>(E);
970 return FindExpressionBaseAddress(PE->getSubExpr());
971 }
972 case Expr::UnaryOperatorClass: {
973 const UnaryOperator *Exp = cast<UnaryOperator>(E);
974
975 // C99 6.6p9
976 if (Exp->getOpcode() == UnaryOperator::AddrOf)
977 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
978
979 if (Exp->getOpcode() == UnaryOperator::Extension)
980 return FindExpressionBaseAddress(Exp->getSubExpr());
981
982 return E;
983 }
984 case Expr::BinaryOperatorClass: {
985 const BinaryOperator *Exp = cast<BinaryOperator>(E);
986
987 Expr *PExp = Exp->getLHS();
988 Expr *IExp = Exp->getRHS();
989 if (IExp->getType()->isPointerType())
990 std::swap(PExp, IExp);
991
992 return FindExpressionBaseAddress(PExp);
993 }
994 case Expr::ImplicitCastExprClass: {
995 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
996
997 // Check for implicit promotion
998 if (SubExpr->getType()->isFunctionType() ||
999 SubExpr->getType()->isArrayType())
1000 return FindExpressionBaseAddressLValue(SubExpr);
1001
1002 // Check for pointer->pointer cast
1003 if (SubExpr->getType()->isPointerType())
1004 return FindExpressionBaseAddress(SubExpr);
1005
1006 // We assume that we have an arithmetic expression here;
1007 // if we don't, we'll figure it out later
1008 return 0;
1009 }
1010 case Expr::CastExprClass: {
1011 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1012
1013 // Check for pointer->pointer cast
1014 if (SubExpr->getType()->isPointerType())
1015 return FindExpressionBaseAddress(SubExpr);
1016
1017 // We assume that we have an arithmetic expression here;
1018 // if we don't, we'll figure it out later
1019 return 0;
1020 }
1021 }
1022}
1023
Eli Friedmanc594b322008-05-20 13:48:25 +00001024bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1025 switch (Init->getStmtClass()) {
1026 default:
1027 Diag(Init->getExprLoc(),
1028 diag::err_init_element_not_constant, Init->getSourceRange());
1029 return true;
1030 case Expr::ParenExprClass: {
1031 const ParenExpr* PE = cast<ParenExpr>(Init);
1032 return CheckArithmeticConstantExpression(PE->getSubExpr());
1033 }
1034 case Expr::FloatingLiteralClass:
1035 case Expr::IntegerLiteralClass:
1036 case Expr::CharacterLiteralClass:
1037 case Expr::ImaginaryLiteralClass:
1038 case Expr::TypesCompatibleExprClass:
1039 case Expr::CXXBoolLiteralExprClass:
1040 return false;
1041 case Expr::CallExprClass: {
1042 const CallExpr *CE = cast<CallExpr>(Init);
1043 if (CE->isBuiltinConstantExpr())
1044 return false;
1045 Diag(Init->getExprLoc(),
1046 diag::err_init_element_not_constant, Init->getSourceRange());
1047 return true;
1048 }
1049 case Expr::DeclRefExprClass: {
1050 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1051 if (isa<EnumConstantDecl>(D))
1052 return false;
1053 Diag(Init->getExprLoc(),
1054 diag::err_init_element_not_constant, Init->getSourceRange());
1055 return true;
1056 }
1057 case Expr::CompoundLiteralExprClass:
1058 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1059 // but vectors are allowed to be magic.
1060 if (Init->getType()->isVectorType())
1061 return false;
1062 Diag(Init->getExprLoc(),
1063 diag::err_init_element_not_constant, Init->getSourceRange());
1064 return true;
1065 case Expr::UnaryOperatorClass: {
1066 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1067
1068 switch (Exp->getOpcode()) {
1069 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1070 // See C99 6.6p3.
1071 default:
1072 Diag(Init->getExprLoc(),
1073 diag::err_init_element_not_constant, Init->getSourceRange());
1074 return true;
1075 case UnaryOperator::SizeOf:
1076 case UnaryOperator::AlignOf:
1077 case UnaryOperator::OffsetOf:
1078 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1079 // See C99 6.5.3.4p2 and 6.6p3.
1080 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1081 return false;
1082 Diag(Init->getExprLoc(),
1083 diag::err_init_element_not_constant, Init->getSourceRange());
1084 return true;
1085 case UnaryOperator::Extension:
1086 case UnaryOperator::LNot:
1087 case UnaryOperator::Plus:
1088 case UnaryOperator::Minus:
1089 case UnaryOperator::Not:
1090 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1091 }
1092 }
1093 case Expr::SizeOfAlignOfTypeExprClass: {
1094 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1095 // Special check for void types, which are allowed as an extension
1096 if (Exp->getArgumentType()->isVoidType())
1097 return false;
1098 // alignof always evaluates to a constant.
1099 // FIXME: is sizeof(int[3.0]) a constant expression?
1100 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1101 Diag(Init->getExprLoc(),
1102 diag::err_init_element_not_constant, Init->getSourceRange());
1103 return true;
1104 }
1105 return false;
1106 }
1107 case Expr::BinaryOperatorClass: {
1108 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1109
1110 if (Exp->getLHS()->getType()->isArithmeticType() &&
1111 Exp->getRHS()->getType()->isArithmeticType()) {
1112 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1113 CheckArithmeticConstantExpression(Exp->getRHS());
1114 }
1115
Eli Friedman4caf0552008-06-09 05:05:07 +00001116 if (Exp->getLHS()->getType()->isPointerType() &&
1117 Exp->getRHS()->getType()->isPointerType()) {
1118 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1119 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1120
1121 // Only allow a null (constant integer) base; we could
1122 // allow some additional cases if necessary, but this
1123 // is sufficient to cover offsetof-like constructs.
1124 if (!LHSBase && !RHSBase) {
1125 return CheckAddressConstantExpression(Exp->getLHS()) ||
1126 CheckAddressConstantExpression(Exp->getRHS());
1127 }
1128 }
1129
Eli Friedmanc594b322008-05-20 13:48:25 +00001130 Diag(Init->getExprLoc(),
1131 diag::err_init_element_not_constant, Init->getSourceRange());
1132 return true;
1133 }
1134 case Expr::ImplicitCastExprClass:
1135 case Expr::CastExprClass: {
1136 const Expr *SubExpr;
1137 if (const CastExpr *C = dyn_cast<CastExpr>(Init)) {
1138 SubExpr = C->getSubExpr();
1139 } else {
1140 SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1141 }
1142
1143 if (SubExpr->getType()->isArithmeticType())
1144 return CheckArithmeticConstantExpression(SubExpr);
1145
1146 Diag(Init->getExprLoc(),
1147 diag::err_init_element_not_constant, Init->getSourceRange());
1148 return true;
1149 }
1150 case Expr::ConditionalOperatorClass: {
1151 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1152 if (CheckArithmeticConstantExpression(Exp->getCond()))
1153 return true;
1154 if (Exp->getLHS() &&
1155 CheckArithmeticConstantExpression(Exp->getLHS()))
1156 return true;
1157 return CheckArithmeticConstantExpression(Exp->getRHS());
1158 }
1159 }
1160}
1161
1162bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
1163 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1164 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1165 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1166
1167 if (Init->getType()->isReferenceType()) {
1168 // FIXME: Work out how the heck reference types work
1169 return false;
1170#if 0
1171 // A reference is constant if the address of the expression
1172 // is constant
1173 // We look through initlists here to simplify
1174 // CheckAddressConstantExpressionLValue.
1175 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1176 assert(Exp->getNumInits() > 0 &&
1177 "Refernce initializer cannot be empty");
1178 Init = Exp->getInit(0);
1179 }
1180 return CheckAddressConstantExpressionLValue(Init);
1181#endif
1182 }
1183
1184 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1185 unsigned numInits = Exp->getNumInits();
1186 for (unsigned i = 0; i < numInits; i++) {
1187 // FIXME: Need to get the type of the declaration for C++,
1188 // because it could be a reference?
1189 if (CheckForConstantInitializer(Exp->getInit(i),
1190 Exp->getInit(i)->getType()))
1191 return true;
1192 }
1193 return false;
1194 }
1195
1196 if (Init->isNullPointerConstant(Context))
1197 return false;
1198 if (Init->getType()->isArithmeticType()) {
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001199 QualType InitTy = Init->getType().getCanonicalType().getUnqualifiedType();
1200 if (InitTy == Context.BoolTy) {
1201 // Special handling for pointers implicitly cast to bool;
1202 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1203 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1204 Expr* SubE = ICE->getSubExpr();
1205 if (SubE->getType()->isPointerType() ||
1206 SubE->getType()->isArrayType() ||
1207 SubE->getType()->isFunctionType()) {
1208 return CheckAddressConstantExpression(Init);
1209 }
1210 }
1211 } else if (InitTy->isIntegralType()) {
1212 Expr* SubE = 0;
1213 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init))
1214 SubE = ICE->getSubExpr();
1215 else if (CastExpr* CE = dyn_cast<CastExpr>(Init))
1216 SubE = CE->getSubExpr();
1217 // Special check for pointer cast to int; we allow as an extension
1218 // an address constant cast to an integer if the integer
1219 // is of an appropriate width (this sort of code is apparently used
1220 // in some places).
1221 // FIXME: Add pedwarn?
1222 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1223 if (SubE && (SubE->getType()->isPointerType() ||
1224 SubE->getType()->isArrayType() ||
1225 SubE->getType()->isFunctionType())) {
1226 unsigned IntWidth = Context.getTypeSize(Init->getType());
1227 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1228 if (IntWidth >= PointerWidth)
1229 return CheckAddressConstantExpression(Init);
1230 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001231 }
1232
1233 return CheckArithmeticConstantExpression(Init);
1234 }
1235
1236 if (Init->getType()->isPointerType())
1237 return CheckAddressConstantExpression(Init);
1238
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001239 // An array type at the top level that isn't an init-list must
1240 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001241 if (Init->getType()->isArrayType())
1242 return false;
1243
1244 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1245 Init->getSourceRange());
1246 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001247}
1248
Steve Naroffbb204692007-09-12 14:07:44 +00001249void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001250 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001251 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001252 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001253
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001254 // If there is no declaration, there was an error parsing it. Just ignore
1255 // the initializer.
1256 if (RealDecl == 0) {
1257 delete Init;
1258 return;
1259 }
Steve Naroffbb204692007-09-12 14:07:44 +00001260
Steve Naroff410e3e22007-09-12 20:13:48 +00001261 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1262 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001263 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1264 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001265 RealDecl->setInvalidDecl();
1266 return;
1267 }
Steve Naroffbb204692007-09-12 14:07:44 +00001268 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001269 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001270 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001271 if (VDecl->isBlockVarDecl()) {
1272 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001273 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001274 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001275 VDecl->setInvalidDecl();
1276 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +00001277 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001278 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001279 if (SC == VarDecl::Static) // C99 6.7.8p4.
1280 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001281 }
Steve Naroff248a7532008-04-15 22:42:06 +00001282 } else if (VDecl->isFileVarDecl()) {
1283 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001284 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001285 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +00001286 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001287 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001288
1289 // C99 6.7.8p4. All file scoped initializers need to be constant.
1290 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001291 }
1292 // If the type changed, it means we had an incomplete type that was
1293 // completed by the initializer. For example:
1294 // int ary[] = { 1, 3, 5 };
1295 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001296 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001297 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001298 Init->setType(DclT);
1299 }
Steve Naroffbb204692007-09-12 14:07:44 +00001300
1301 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001302 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001303 return;
1304}
1305
Reid Spencer5f016e22007-07-11 17:01:13 +00001306/// The declarators are chained together backwards, reverse the list.
1307Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1308 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001309 Decl *GroupDecl = static_cast<Decl*>(group);
1310 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001311 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001312
1313 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1314 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001315 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001316 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001317 else { // reverse the list.
1318 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001319 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001320 Group->setNextDeclarator(NewGroup);
1321 NewGroup = Group;
1322 Group = Next;
1323 }
1324 }
1325 // Perform semantic analysis that depends on having fully processed both
1326 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001327 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001328 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1329 if (!IDecl)
1330 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001331 QualType T = IDecl->getType();
1332
1333 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1334 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001335 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1336 IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +00001337 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001338 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1339 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001340 }
1341 }
1342 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1343 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001344 if (IDecl->isBlockVarDecl() &&
1345 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001346 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001347 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1348 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001349 IDecl->setInvalidDecl();
1350 }
1351 }
1352 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1353 // object that has file scope without an initializer, and without a
1354 // storage-class specifier or with the storage-class specifier "static",
1355 // constitutes a tentative definition. Note: A tentative definition with
1356 // external linkage is valid (C99 6.2.2p5).
Steve Naroff248a7532008-04-15 22:42:06 +00001357 if (IDecl && !IDecl->getInit() &&
1358 (IDecl->getStorageClass() == VarDecl::Static ||
1359 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001360 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001361 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1362 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001363 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001364 // C99 6.9.2p3: If the declaration of an identifier for an object is
1365 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1366 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001367 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1368 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001369 IDecl->setInvalidDecl();
1370 }
1371 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001372 }
1373 return NewGroup;
1374}
Steve Naroffe1223f72007-08-28 03:03:08 +00001375
Chris Lattner04421082008-04-08 04:40:51 +00001376/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1377/// to introduce parameters into function prototype scope.
1378Sema::DeclTy *
1379Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00001380 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001381
1382 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1383 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1384 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1385 Diag(DS.getStorageClassSpecLoc(),
1386 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001387 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001388 }
1389 if (DS.isThreadSpecified()) {
1390 Diag(DS.getThreadSpecLoc(),
1391 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001392 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001393 }
1394
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001395 // Check that there are no default arguments inside the type of this
1396 // parameter (C++ only).
1397 if (getLangOptions().CPlusPlus)
1398 CheckExtraCXXDefaultArguments(D);
1399
Chris Lattner04421082008-04-08 04:40:51 +00001400 // In this context, we *do not* check D.getInvalidType(). If the declarator
1401 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1402 // though it will not reflect the user specified type.
1403 QualType parmDeclType = GetTypeForDeclarator(D, S);
1404
1405 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1406
Reid Spencer5f016e22007-07-11 17:01:13 +00001407 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1408 // Can this happen for params? We already checked that they don't conflict
1409 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001410 IdentifierInfo *II = D.getIdentifier();
1411 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1412 if (S->isDeclScope(PrevDecl)) {
1413 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1414 dyn_cast<NamedDecl>(PrevDecl)->getName());
1415
1416 // Recover by removing the name
1417 II = 0;
1418 D.SetIdentifier(0, D.getIdentifierLoc());
1419 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001420 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001421
1422 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1423 // Doing the promotion here has a win and a loss. The win is the type for
1424 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1425 // code generator). The loss is the orginal type isn't preserved. For example:
1426 //
1427 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1428 // int blockvardecl[5];
1429 // sizeof(parmvardecl); // size == 4
1430 // sizeof(blockvardecl); // size == 20
1431 // }
1432 //
1433 // For expressions, all implicit conversions are captured using the
1434 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1435 //
1436 // FIXME: If a source translation tool needs to see the original type, then
1437 // we need to consider storing both types (in ParmVarDecl)...
1438 //
Chris Lattnere6327742008-04-02 05:18:44 +00001439 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001440 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001441 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001442 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001443 parmDeclType = Context.getPointerType(parmDeclType);
1444
Chris Lattner04421082008-04-08 04:40:51 +00001445 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1446 D.getIdentifierLoc(), II,
1447 parmDeclType, VarDecl::None,
1448 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001449
Chris Lattner04421082008-04-08 04:40:51 +00001450 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001451 New->setInvalidDecl();
1452
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001453 if (II)
1454 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001455
Chris Lattner3ff30c82008-06-29 00:02:00 +00001456 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001457 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001458
Reid Spencer5f016e22007-07-11 17:01:13 +00001459}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001460
Chris Lattnerb652cea2007-10-09 17:14:05 +00001461Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001462 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00001463 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1464 "Not a function declarator!");
1465 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001466
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1468 // for a K&R function.
1469 if (!FTI.hasPrototype) {
1470 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001471 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1473 FTI.ArgInfo[i].Ident->getName());
1474 // Implicitly declare the argument as type 'int' for lack of a better
1475 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001476 DeclSpec DS;
1477 const char* PrevSpec; // unused
1478 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1479 PrevSpec);
1480 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1481 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1482 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 }
1484 }
Chris Lattner52804082008-02-17 19:31:09 +00001485
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 // Since this is a function definition, act as though we have information
1487 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001488 if (FTI.NumArgs)
1489 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001491 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 }
1493
1494 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001495
1496 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001497 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001498 GlobalScope);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001499 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1500 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1501 const FunctionDecl *Definition;
1502 if (FD->getBody(Definition)) {
1503 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1504 D.getIdentifier()->getName());
1505 Diag(Definition->getLocation(), diag::err_previous_definition);
1506 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001507 }
1508 }
Steve Narofffabbc342008-02-12 01:09:36 +00001509 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001510 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattnerb048c982008-04-06 04:47:34 +00001511 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001512
1513 // Check the validity of our function parameters
1514 CheckParmsForFunctionDef(FD);
1515
1516 // Introduce our parameters into the function scope
1517 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1518 ParmVarDecl *Param = FD->getParamDecl(p);
1519 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001520 if (Param->getIdentifier())
1521 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001522 }
Chris Lattner04421082008-04-08 04:40:51 +00001523
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 return FD;
1525}
1526
Steve Naroffd6d054d2007-11-11 23:20:51 +00001527Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1528 Decl *dcl = static_cast<Decl *>(D);
1529 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1530 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001531 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001532 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001533 MD->setBody((Stmt*)Body);
Steve Naroff4d832202007-12-13 18:18:56 +00001534 }
Chris Lattnerb048c982008-04-06 04:47:34 +00001535 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 // Verify and clean out per-function state.
1537
1538 // Check goto/label use.
1539 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1540 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1541 // Verify that we have no forward references left. If so, there was a goto
1542 // or address of a label taken, but no definition of it. Label fwd
1543 // definitions are indicated with a null substmt.
1544 if (I->second->getSubStmt() == 0) {
1545 LabelStmt *L = I->second;
1546 // Emit error.
1547 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1548
1549 // At this point, we have gotos that use the bogus label. Stitch it into
1550 // the function body so that they aren't leaked and that the AST is well
1551 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001552 if (Body) {
1553 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1554 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1555 } else {
1556 // The whole function wasn't parsed correctly, just delete this.
1557 delete L;
1558 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 }
1560 }
1561 LabelMap.clear();
1562
Steve Naroffd6d054d2007-11-11 23:20:51 +00001563 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001564}
1565
Reid Spencer5f016e22007-07-11 17:01:13 +00001566/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1567/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001568ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1569 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001570 // Extension in C99. Legal in C90, but warn about it.
1571 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001573 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1575
1576 // FIXME: handle stuff like:
1577 // void foo() { extern float X(); }
1578 // void bar() { X(); } <-- implicit decl for X in another scope.
1579
1580 // Set a Declarator for the implicit definition: int foo();
1581 const char *Dummy;
1582 DeclSpec DS;
1583 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1584 Error = Error; // Silence warning.
1585 assert(!Error && "Error setting up implicit decl!");
1586 Declarator D(DS, Declarator::BlockContext);
1587 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1588 D.SetIdentifier(&II, Loc);
1589
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001590 // Insert this function into translation-unit scope.
1591
1592 DeclContext *PrevDC = CurContext;
1593 CurContext = Context.getTranslationUnitDecl();
1594
Steve Naroffe2ef8152008-04-04 14:32:09 +00001595 FunctionDecl *FD =
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001596 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001597 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001598
1599 CurContext = PrevDC;
1600
Steve Naroffe2ef8152008-04-04 14:32:09 +00001601 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001602}
1603
1604
Chris Lattner41af0932007-11-14 06:34:38 +00001605TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001606 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001608 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001609
1610 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001611 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1612 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001613 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001614 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001615 if (D.getInvalidType())
1616 NewTD->setInvalidDecl();
1617 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001618}
1619
Steve Naroff08d92e42007-09-15 18:49:24 +00001620/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001621/// former case, Name will be non-null. In the later case, Name will be null.
1622/// TagType indicates what kind of tag this is. TK indicates whether this is a
1623/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001624Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001625 SourceLocation KWLoc, IdentifierInfo *Name,
1626 SourceLocation NameLoc, AttributeList *Attr) {
1627 // If this is a use of an existing tag, it must have a name.
1628 assert((Name != 0 || TK == TK_Definition) &&
1629 "Nameless record must be a definition!");
1630
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001631 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 switch (TagType) {
1633 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001634 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1635 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1636 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1637 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 }
1639
1640 // If this is a named struct, check to see if there was a previous forward
1641 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001642 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1643 if (ScopedDecl *PrevDecl =
1644 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001645
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001646 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1647 "unexpected Decl type");
1648 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1649 // If this is a use of a previous tag, or if the tag is already declared in
1650 // the same scope (so that the definition/declaration completes or
1651 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001652 if (TK == TK_Reference ||
1653 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001654 // Make sure that this wasn't declared as an enum and now used as a struct
1655 // or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001656 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001657 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1658 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1659 }
1660
1661 // If this is a use or a forward declaration, we're good.
1662 if (TK != TK_Definition)
1663 return PrevDecl;
Reid Spencer5f016e22007-07-11 17:01:13 +00001664
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001665 // Diagnose attempts to redefine a tag.
1666 if (PrevTagDecl->isDefinition()) {
1667 Diag(NameLoc, diag::err_redefinition, Name->getName());
1668 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1669 // If this is a redefinition, recover by making this struct be
1670 // anonymous, which will make any later references get the previous
1671 // definition.
1672 Name = 0;
1673 } else {
1674 // Okay, this is definition of a previously declared or referenced tag.
1675 // Move the location of the decl to be the definition site.
1676 PrevDecl->setLocation(NameLoc);
1677 return PrevDecl;
1678 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001679 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001680 // If we get here, this is a definition of a new struct type in a nested
1681 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1682 // type.
1683 } else {
1684 // The tag name clashes with a namespace name, issue an error and recover
1685 // by making this tag be anonymous.
1686 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1687 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1688 Name = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001690 }
1691
1692 // If there is an identifier, use the location of the identifier as the
1693 // location of the decl, otherwise use the location of the struct/union
1694 // keyword.
1695 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1696
1697 // Otherwise, if this is the first time we've seen this tag, create the decl.
1698 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001699 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1701 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001702 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 // If this is an undefined enum, warn.
1704 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001705 } else {
1706 // struct/union/class
1707
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1709 // struct X { int A; } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001710 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 }
1712
1713 // If this has an identifier, add it to the scope stack.
1714 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001715 // The scope passed in may not be a decl scope. Zip up the scope tree until
1716 // we find one that is.
1717 while ((S->getFlags() & Scope::DeclScope) == 0)
1718 S = S->getParent();
1719
1720 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001721 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001723
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00001724 if (Attr)
1725 ProcessDeclAttributeList(New, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001726 return New;
1727}
1728
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001729/// Collect the instance variables declared in an Objective-C object. Used in
1730/// the creation of structures from objects using the @defs directive.
1731static void CollectIvars(ObjCInterfaceDecl *Class,
1732 llvm::SmallVector<Sema::DeclTy*, 16> &ivars) {
1733 if (Class->getSuperClass())
1734 CollectIvars(Class->getSuperClass(), ivars);
1735 ivars.append(Class->ivar_begin(), Class->ivar_end());
1736}
1737
1738/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1739/// instance variables of ClassName into Decls.
1740void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1741 IdentifierInfo *ClassName,
1742 llvm::SmallVector<DeclTy*, 16> &Decls) {
1743 // Check that ClassName is a valid class
1744 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1745 if (!Class) {
1746 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1747 return;
1748 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001749 // Collect the instance variables
1750 CollectIvars(Class, Decls);
1751}
1752
1753
Eli Friedman1b76ada2008-06-03 21:01:11 +00001754static bool CalcFakeICEVal(const Expr* Expr,
1755 llvm::APSInt& Result,
1756 ASTContext& Context) {
1757 // Calculate the value of an expression that has a calculatable
1758 // value, but isn't an ICE. Currently, this only supports
1759 // a very narrow set of extensions, but it can be expanded if needed.
1760 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Expr))
1761 return CalcFakeICEVal(PE->getSubExpr(), Result, Context);
1762
1763 if (const CastExpr *CE = dyn_cast<CastExpr>(Expr)) {
1764 QualType CETy = CE->getType();
1765 if ((CETy->isIntegralType() && !CETy->isBooleanType()) ||
1766 CETy->isPointerType()) {
1767 if (CalcFakeICEVal(CE->getSubExpr(), Result, Context)) {
1768 Result.extOrTrunc(Context.getTypeSize(CETy));
1769 // FIXME: This assumes pointers are signed.
1770 Result.setIsSigned(CETy->isSignedIntegerType() ||
1771 CETy->isPointerType());
1772 return true;
1773 }
1774 }
1775 }
1776
1777 if (Expr->getType()->isIntegralType())
1778 return Expr->isIntegerConstantExpr(Result, Context);
1779
1780 return false;
1781}
1782
1783QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1784 // This method tries to turn a variable array into a constant
1785 // array even when the size isn't an ICE. This is necessary
1786 // for compatibility with code that depends on gcc's buggy
1787 // constant expression folding, like struct {char x[(int)(char*)2];}
1788 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
1789 llvm::APSInt Result(32);
1790 if (VLATy->getSizeExpr() &&
1791 CalcFakeICEVal(VLATy->getSizeExpr(), Result, Context) &&
1792 Result > llvm::APSInt(Result.getBitWidth(), Result.isUnsigned())) {
1793 return Context.getConstantArrayType(VLATy->getElementType(),
1794 Result, ArrayType::Normal, 0);
1795 }
1796 }
1797 return QualType();
1798}
1799
Steve Naroff08d92e42007-09-15 18:49:24 +00001800/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001801/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001802Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001803 SourceLocation DeclStart,
1804 Declarator &D, ExprTy *BitfieldWidth) {
1805 IdentifierInfo *II = D.getIdentifier();
1806 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001807 SourceLocation Loc = DeclStart;
1808 if (II) Loc = D.getIdentifierLoc();
1809
1810 // FIXME: Unnamed fields can be handled in various different ways, for
1811 // example, unnamed unions inject all members into the struct namespace!
1812
1813
1814 if (BitWidth) {
1815 // TODO: Validate.
1816 //printf("WARNING: BITFIELDS IGNORED!\n");
1817
1818 // 6.7.2.1p3
1819 // 6.7.2.1p4
1820
1821 } else {
1822 // Not a bitfield.
1823
1824 // validate II.
1825
1826 }
1827
1828 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001829 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1830 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001831
Reid Spencer5f016e22007-07-11 17:01:13 +00001832 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1833 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001834 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00001835 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1836 if (!FixedTy.isNull()) {
1837 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1838 T = FixedTy;
1839 } else {
1840 // FIXME: This diagnostic needs work
1841 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1842 InvalidDecl = true;
1843 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001844 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001845 // FIXME: Chain fielddecls together.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001846 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001847
Chris Lattner3ff30c82008-06-29 00:02:00 +00001848 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00001849
Steve Naroff5912a352007-08-28 20:14:24 +00001850 if (D.getInvalidType() || InvalidDecl)
1851 NewFD->setInvalidDecl();
1852 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001853}
1854
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001855/// TranslateIvarVisibility - Translate visibility from a token ID to an
1856/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001857static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001858TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001859 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001860 case tok::objc_private: return ObjCIvarDecl::Private;
1861 case tok::objc_public: return ObjCIvarDecl::Public;
1862 case tok::objc_protected: return ObjCIvarDecl::Protected;
1863 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001864 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001865 }
1866}
1867
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001868/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1869/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001870Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001871 SourceLocation DeclStart,
1872 Declarator &D, ExprTy *BitfieldWidth,
1873 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001874 IdentifierInfo *II = D.getIdentifier();
1875 Expr *BitWidth = (Expr*)BitfieldWidth;
1876 SourceLocation Loc = DeclStart;
1877 if (II) Loc = D.getIdentifierLoc();
1878
1879 // FIXME: Unnamed fields can be handled in various different ways, for
1880 // example, unnamed unions inject all members into the struct namespace!
1881
1882
1883 if (BitWidth) {
1884 // TODO: Validate.
1885 //printf("WARNING: BITFIELDS IGNORED!\n");
1886
1887 // 6.7.2.1p3
1888 // 6.7.2.1p4
1889
1890 } else {
1891 // Not a bitfield.
1892
1893 // validate II.
1894
1895 }
1896
1897 QualType T = GetTypeForDeclarator(D, S);
1898 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1899 bool InvalidDecl = false;
1900
1901 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1902 // than a variably modified type.
1903 if (T->isVariablyModifiedType()) {
1904 // FIXME: This diagnostic needs work
1905 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1906 InvalidDecl = true;
1907 }
1908
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001909 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001910
Chris Lattner3ff30c82008-06-29 00:02:00 +00001911 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001912
1913 if (D.getInvalidType() || InvalidDecl)
1914 NewID->setInvalidDecl();
1915 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001916 if (Visibility != tok::objc_not_keyword)
1917 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001918 return NewID;
1919}
1920
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001921void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001922 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001923 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001924 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001925 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1926 assert(EnclosingDecl && "missing record or interface decl");
1927 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1928
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001929 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001930 // Diagnose code like:
1931 // struct S { struct S {} X; };
1932 // We discover this when we complete the outer S. Reject and ignore the
1933 // outer S.
1934 Diag(Record->getLocation(), diag::err_nested_redefinition,
1935 Record->getKindName());
1936 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001937 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001938 return;
1939 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001940 // Verify that all the fields are okay.
1941 unsigned NumNamedMembers = 0;
1942 llvm::SmallVector<FieldDecl*, 32> RecFields;
1943 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001944
Reid Spencer5f016e22007-07-11 17:01:13 +00001945 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001946
Steve Naroff74216642007-09-14 22:20:54 +00001947 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1948 assert(FD && "missing field decl");
1949
1950 // Remember all fields.
1951 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001952
1953 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001954 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00001955
Reid Spencer5f016e22007-07-11 17:01:13 +00001956 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001957 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001958 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001960 FD->setInvalidDecl();
1961 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001962 continue;
1963 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001964 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1965 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001966 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001967 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001968 FD->setInvalidDecl();
1969 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001970 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001971 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001972 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001973 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001974 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001975 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001976 FD->setInvalidDecl();
1977 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 continue;
1979 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001980 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001981 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1982 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001983 FD->setInvalidDecl();
1984 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001985 continue;
1986 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001987 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001988 if (Record)
1989 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001990 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001991 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1992 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001993 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001994 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1995 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001996 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001997 Record->setHasFlexibleArrayMember(true);
1998 } else {
1999 // If this is a struct/class and this is not the last element, reject
2000 // it. Note that GCC supports variable sized arrays in the middle of
2001 // structures.
2002 if (i != NumFields-1) {
2003 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2004 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002005 FD->setInvalidDecl();
2006 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002007 continue;
2008 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002009 // We support flexible arrays at the end of structs in other structs
2010 // as an extension.
2011 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2012 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002013 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002014 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002015 }
2016 }
2017 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002018 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002019 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002020 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2021 FD->getName());
2022 FD->setInvalidDecl();
2023 EnclosingDecl->setInvalidDecl();
2024 continue;
2025 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 // Keep track of the number of named members.
2027 if (IdentifierInfo *II = FD->getIdentifier()) {
2028 // Detect duplicate member names.
2029 if (!FieldIDs.insert(II)) {
2030 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2031 // Find the previous decl.
2032 SourceLocation PrevLoc;
2033 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2034 assert(i != e && "Didn't find previous def!");
2035 if (RecFields[i]->getIdentifier() == II) {
2036 PrevLoc = RecFields[i]->getLocation();
2037 break;
2038 }
2039 }
2040 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002041 FD->setInvalidDecl();
2042 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002043 continue;
2044 }
2045 ++NumNamedMembers;
2046 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002047 }
2048
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002050 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002051 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00002052 Consumer.HandleTagDeclDefinition(Record);
2053 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002054 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2055 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2056 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2057 else if (ObjCImplementationDecl *IMPDecl =
2058 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002059 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2060 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002061 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002062 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002063 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002064}
2065
Steve Naroff08d92e42007-09-15 18:49:24 +00002066Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002067 DeclTy *lastEnumConst,
2068 SourceLocation IdLoc, IdentifierInfo *Id,
2069 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002070 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002071 EnumConstantDecl *LastEnumConst =
2072 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2073 Expr *Val = static_cast<Expr*>(val);
2074
Chris Lattner31e05722007-08-26 06:24:45 +00002075 // The scope passed in may not be a decl scope. Zip up the scope tree until
2076 // we find one that is.
2077 while ((S->getFlags() & Scope::DeclScope) == 0)
2078 S = S->getParent();
2079
Reid Spencer5f016e22007-07-11 17:01:13 +00002080 // Verify that there isn't already something declared with this name in this
2081 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002082 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00002083 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002084 if (isa<EnumConstantDecl>(PrevDecl))
2085 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2086 else
2087 Diag(IdLoc, diag::err_redefinition, Id->getName());
2088 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002089 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 return 0;
2091 }
2092 }
2093
2094 llvm::APSInt EnumVal(32);
2095 QualType EltTy;
2096 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002097 // Make sure to promote the operand type to int.
2098 UsualUnaryConversions(Val);
2099
Reid Spencer5f016e22007-07-11 17:01:13 +00002100 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2101 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002102 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002103 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2104 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002105 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002106 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002107 } else {
2108 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002110 }
2111
2112 if (!Val) {
2113 if (LastEnumConst) {
2114 // Assign the last value + 1.
2115 EnumVal = LastEnumConst->getInitVal();
2116 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002117
2118 // Check for overflow on increment.
2119 if (EnumVal < LastEnumConst->getInitVal())
2120 Diag(IdLoc, diag::warn_enum_value_overflow);
2121
Chris Lattnerb7416f92007-08-27 17:37:24 +00002122 EltTy = LastEnumConst->getType();
2123 } else {
2124 // First value, set to zero.
2125 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002126 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002127 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002128 }
2129
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002130 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002131 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2132 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002133 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002134
2135 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002136 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002137 return New;
2138}
2139
Steve Naroff08d92e42007-09-15 18:49:24 +00002140void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002141 DeclTy **Elements, unsigned NumElements) {
2142 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
2143 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
2144
Chris Lattnere37f0be2007-08-28 05:10:31 +00002145 // TODO: If the result value doesn't fit in an int, it must be a long or long
2146 // long value. ISO C does not support this, but GCC does as an extension,
2147 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002148 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002149
Chris Lattnerac609682007-08-28 06:15:15 +00002150 // Verify that all the values are okay, compute the size of the values, and
2151 // reverse the list.
2152 unsigned NumNegativeBits = 0;
2153 unsigned NumPositiveBits = 0;
2154
2155 // Keep track of whether all elements have type int.
2156 bool AllElementsInt = true;
2157
Reid Spencer5f016e22007-07-11 17:01:13 +00002158 EnumConstantDecl *EltList = 0;
2159 for (unsigned i = 0; i != NumElements; ++i) {
2160 EnumConstantDecl *ECD =
2161 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2162 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002163
2164 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002165 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002166 assert(InitVal.getBitWidth() >= IntWidth &&
2167 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002168 if (InitVal.getBitWidth() > IntWidth) {
2169 llvm::APSInt V(InitVal);
2170 V.trunc(IntWidth);
2171 V.extend(InitVal.getBitWidth());
2172 if (V != InitVal)
2173 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
2174 InitVal.toString());
2175 }
Chris Lattnerac609682007-08-28 06:15:15 +00002176
2177 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002178 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002179 NumPositiveBits = std::max(NumPositiveBits,
2180 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002181 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002182 NumNegativeBits = std::max(NumNegativeBits,
2183 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002184
Chris Lattnerac609682007-08-28 06:15:15 +00002185 // Keep track of whether every enum element has type int (very commmon).
2186 if (AllElementsInt)
2187 AllElementsInt = ECD->getType() == Context.IntTy;
2188
Reid Spencer5f016e22007-07-11 17:01:13 +00002189 ECD->setNextDeclarator(EltList);
2190 EltList = ECD;
2191 }
2192
Chris Lattnerac609682007-08-28 06:15:15 +00002193 // Figure out the type that should be used for this enum.
2194 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2195 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002196 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002197
2198 if (NumNegativeBits) {
2199 // If there is a negative value, figure out the smallest integer type (of
2200 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002201 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002202 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002203 BestWidth = IntWidth;
2204 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002205 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002206
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002207 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002208 BestType = Context.LongTy;
2209 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002210 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002211
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002212 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002213 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2214 BestType = Context.LongLongTy;
2215 }
2216 }
2217 } else {
2218 // If there is no negative value, figure out which of uint, ulong, ulonglong
2219 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002220 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002221 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002222 BestWidth = IntWidth;
2223 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002224 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002225 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002226 } else {
2227 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002228 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002229 "How could an initializer get larger than ULL?");
2230 BestType = Context.UnsignedLongLongTy;
2231 }
2232 }
2233
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002234 // Loop over all of the enumerator constants, changing their types to match
2235 // the type of the enum if needed.
2236 for (unsigned i = 0; i != NumElements; ++i) {
2237 EnumConstantDecl *ECD =
2238 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2239 if (!ECD) continue; // Already issued a diagnostic.
2240
2241 // Standard C says the enumerators have int type, but we allow, as an
2242 // extension, the enumerators to be larger than int size. If each
2243 // enumerator value fits in an int, type it as an int, otherwise type it the
2244 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2245 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002246 if (ECD->getType() == Context.IntTy) {
2247 // Make sure the init value is signed.
2248 llvm::APSInt IV = ECD->getInitVal();
2249 IV.setIsSigned(true);
2250 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002251 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002252 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002253
2254 // Determine whether the value fits into an int.
2255 llvm::APSInt InitVal = ECD->getInitVal();
2256 bool FitsInInt;
2257 if (InitVal.isUnsigned() || !InitVal.isNegative())
2258 FitsInInt = InitVal.getActiveBits() < IntWidth;
2259 else
2260 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2261
2262 // If it fits into an integer type, force it. Otherwise force it to match
2263 // the enum decl type.
2264 QualType NewTy;
2265 unsigned NewWidth;
2266 bool NewSign;
2267 if (FitsInInt) {
2268 NewTy = Context.IntTy;
2269 NewWidth = IntWidth;
2270 NewSign = true;
2271 } else if (ECD->getType() == BestType) {
2272 // Already the right type!
2273 continue;
2274 } else {
2275 NewTy = BestType;
2276 NewWidth = BestWidth;
2277 NewSign = BestType->isSignedIntegerType();
2278 }
2279
2280 // Adjust the APSInt value.
2281 InitVal.extOrTrunc(NewWidth);
2282 InitVal.setIsSigned(NewSign);
2283 ECD->setInitVal(InitVal);
2284
2285 // Adjust the Expr initializer and type.
2286 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2287 ECD->setType(NewTy);
2288 }
Chris Lattnerac609682007-08-28 06:15:15 +00002289
Chris Lattnere00b18c2007-08-28 18:24:31 +00002290 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002291 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002292}
2293
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002294Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2295 ExprTy *expr) {
2296 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2297
Chris Lattner8e25d862008-03-16 00:16:02 +00002298 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002299}
2300
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002301Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002302 SourceLocation LBrace,
2303 SourceLocation RBrace,
2304 const char *Lang,
2305 unsigned StrSize,
2306 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002307 LinkageSpecDecl::LanguageIDs Language;
2308 Decl *dcl = static_cast<Decl *>(D);
2309 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2310 Language = LinkageSpecDecl::lang_c;
2311 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2312 Language = LinkageSpecDecl::lang_cxx;
2313 else {
2314 Diag(Loc, diag::err_bad_language);
2315 return 0;
2316 }
2317
2318 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002319 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002320}